title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Send mail with attachment from your Gmail account using Python | 22 Oct, 2017
In last article, we have discussed the basics of sending a mail from a Gmail account without any subject as well as without any attachment. Today, we will learn how to send mail with attachment and subject using Python. Before moving on, it is highly recommended to learn how to send a simple mail using Python and learn the basics working of ‘smtplib’ library of Python.If you have read the previous article, you have gained the knowledge how a session is created and how it works. Now, you need to learn to attach a file and subject to the mail. For that you need to import some native libraries of Python. From these libraries, you need to import the tools used in our programs.
Steps to send mail with Attachments from Gmail account:
For adding an attachment, you need to import:import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersThese are some libraries which will make our work simple. These are the native libraries and you dont need to import any external library for this.Firstly, create an instance of MIMEMultipart, namely “msg” to begin with.Mention the sender’s email id, receiver’s email id and the subject in the “From”, “To” and “Subject” key of the created instance “msg”.In a string, write the body of the message you want to send, namely body. Now, attach the body with the instance msg using attach function.Open the file you wish to attach in the “rb” mode. Then create an instance of MIMEBase with two parameters. First one is ‘_maintype’ amd the other one is ‘_subtype’. This is the base class for all the MIME-specific sub-classes of Message.Note that ‘_maintype’ is the Content-Type major type (e.g. text or image), and ‘_subtype’ is the Content-Type minor type (e.g. plain or gif or other media).set_payload is used to change the payload the encoded form. Encode it in encode_base64. And finally attach the file with the MIMEMultipart created instance msg.
For adding an attachment, you need to import:import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersThese are some libraries which will make our work simple. These are the native libraries and you dont need to import any external library for this.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
These are some libraries which will make our work simple. These are the native libraries and you dont need to import any external library for this.
Firstly, create an instance of MIMEMultipart, namely “msg” to begin with.
Mention the sender’s email id, receiver’s email id and the subject in the “From”, “To” and “Subject” key of the created instance “msg”.
In a string, write the body of the message you want to send, namely body. Now, attach the body with the instance msg using attach function.
Open the file you wish to attach in the “rb” mode. Then create an instance of MIMEBase with two parameters. First one is ‘_maintype’ amd the other one is ‘_subtype’. This is the base class for all the MIME-specific sub-classes of Message.Note that ‘_maintype’ is the Content-Type major type (e.g. text or image), and ‘_subtype’ is the Content-Type minor type (e.g. plain or gif or other media).
set_payload is used to change the payload the encoded form. Encode it in encode_base64. And finally attach the file with the MIMEMultipart created instance msg.
After finishing up these steps, follow the instructions described in the previous article to create a session, secure it and check the authenticity and then after sending the mail, terminate the session.
# Python code to illustrate Sending mail with attachments# from your Gmail account # libraries to be importedimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encoders fromaddr = "EMAIL address of the sender"toaddr = "EMAIL address of the receiver" # instance of MIMEMultipartmsg = MIMEMultipart() # storing the senders email address msg['From'] = fromaddr # storing the receivers email address msg['To'] = toaddr # storing the subject msg['Subject'] = "Subject of the Mail" # string to store the body of the mailbody = "Body_of_the_mail" # attach the body with the msg instancemsg.attach(MIMEText(body, 'plain')) # open the file to be sent filename = "File_name_with_extension"attachment = open("Path of the file", "rb") # instance of MIMEBase and named as pp = MIMEBase('application', 'octet-stream') # To change the payload into encoded formp.set_payload((attachment).read()) # encode into base64encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) # attach the instance 'p' to instance 'msg'msg.attach(p) # creates SMTP sessions = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for securitys.starttls() # Authentications.login(fromaddr, "Password_of_the_sender") # Converts the Multipart msg into a stringtext = msg.as_string() # sending the mails.sendmail(fromaddr, toaddr, text) # terminating the sessions.quit()
Important Points:
You can use loops to send mails to a number of people.
This code is simple to implement. But it will not work if you have enabled 2-step verification on your gmail account. It is required to switch off the 2-step verification first.
Using this method, Gmail will always put your mail in the primary section and the mails sent will not be Spam.
This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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.
python-utility
Python
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Oct, 2017"
},
{
"code": null,
"e": 734,
"s": 52,
"text": "In last article, we have discussed the basics of sending a mail from a Gmail account without any subject as well as without any attachment. Today, we will learn how to send mail with attachment and subject using Python. Before moving on, it is highly recommended to learn how to send a simple mail using Python and learn the basics working of ‘smtplib’ library of Python.If you have read the previous article, you have gained the knowledge how a session is created and how it works. Now, you need to learn to attach a file and subject to the mail. For that you need to import some native libraries of Python. From these libraries, you need to import the tools used in our programs."
},
{
"code": null,
"e": 790,
"s": 734,
"text": "Steps to send mail with Attachments from Gmail account:"
},
{
"code": null,
"e": 2042,
"s": 790,
"text": "For adding an attachment, you need to import:import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersThese are some libraries which will make our work simple. These are the native libraries and you dont need to import any external library for this.Firstly, create an instance of MIMEMultipart, namely “msg” to begin with.Mention the sender’s email id, receiver’s email id and the subject in the “From”, “To” and “Subject” key of the created instance “msg”.In a string, write the body of the message you want to send, namely body. Now, attach the body with the instance msg using attach function.Open the file you wish to attach in the “rb” mode. Then create an instance of MIMEBase with two parameters. First one is ‘_maintype’ amd the other one is ‘_subtype’. This is the base class for all the MIME-specific sub-classes of Message.Note that ‘_maintype’ is the Content-Type major type (e.g. text or image), and ‘_subtype’ is the Content-Type minor type (e.g. plain or gif or other media).set_payload is used to change the payload the encoded form. Encode it in encode_base64. And finally attach the file with the MIMEMultipart created instance msg."
},
{
"code": null,
"e": 2393,
"s": 2042,
"text": "For adding an attachment, you need to import:import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersThese are some libraries which will make our work simple. These are the native libraries and you dont need to import any external library for this."
},
{
"code": null,
"e": 2408,
"s": 2393,
"text": "import smtplib"
},
{
"code": null,
"e": 2455,
"s": 2408,
"text": "from email.mime.multipart import MIMEMultipart"
},
{
"code": null,
"e": 2492,
"s": 2455,
"text": "from email.mime.text import MIMEText"
},
{
"code": null,
"e": 2529,
"s": 2492,
"text": "from email.mime.base import MIMEBase"
},
{
"code": null,
"e": 2556,
"s": 2529,
"text": "from email import encoders"
},
{
"code": null,
"e": 2704,
"s": 2556,
"text": "These are some libraries which will make our work simple. These are the native libraries and you dont need to import any external library for this."
},
{
"code": null,
"e": 2778,
"s": 2704,
"text": "Firstly, create an instance of MIMEMultipart, namely “msg” to begin with."
},
{
"code": null,
"e": 2914,
"s": 2778,
"text": "Mention the sender’s email id, receiver’s email id and the subject in the “From”, “To” and “Subject” key of the created instance “msg”."
},
{
"code": null,
"e": 3054,
"s": 2914,
"text": "In a string, write the body of the message you want to send, namely body. Now, attach the body with the instance msg using attach function."
},
{
"code": null,
"e": 3449,
"s": 3054,
"text": "Open the file you wish to attach in the “rb” mode. Then create an instance of MIMEBase with two parameters. First one is ‘_maintype’ amd the other one is ‘_subtype’. This is the base class for all the MIME-specific sub-classes of Message.Note that ‘_maintype’ is the Content-Type major type (e.g. text or image), and ‘_subtype’ is the Content-Type minor type (e.g. plain or gif or other media)."
},
{
"code": null,
"e": 3610,
"s": 3449,
"text": "set_payload is used to change the payload the encoded form. Encode it in encode_base64. And finally attach the file with the MIMEMultipart created instance msg."
},
{
"code": null,
"e": 3814,
"s": 3610,
"text": "After finishing up these steps, follow the instructions described in the previous article to create a session, secure it and check the authenticity and then after sending the mail, terminate the session."
},
{
"code": "# Python code to illustrate Sending mail with attachments# from your Gmail account # libraries to be importedimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encoders fromaddr = \"EMAIL address of the sender\"toaddr = \"EMAIL address of the receiver\" # instance of MIMEMultipartmsg = MIMEMultipart() # storing the senders email address msg['From'] = fromaddr # storing the receivers email address msg['To'] = toaddr # storing the subject msg['Subject'] = \"Subject of the Mail\" # string to store the body of the mailbody = \"Body_of_the_mail\" # attach the body with the msg instancemsg.attach(MIMEText(body, 'plain')) # open the file to be sent filename = \"File_name_with_extension\"attachment = open(\"Path of the file\", \"rb\") # instance of MIMEBase and named as pp = MIMEBase('application', 'octet-stream') # To change the payload into encoded formp.set_payload((attachment).read()) # encode into base64encoders.encode_base64(p) p.add_header('Content-Disposition', \"attachment; filename= %s\" % filename) # attach the instance 'p' to instance 'msg'msg.attach(p) # creates SMTP sessions = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for securitys.starttls() # Authentications.login(fromaddr, \"Password_of_the_sender\") # Converts the Multipart msg into a stringtext = msg.as_string() # sending the mails.sendmail(fromaddr, toaddr, text) # terminating the sessions.quit()",
"e": 5307,
"s": 3814,
"text": null
},
{
"code": null,
"e": 5325,
"s": 5307,
"text": "Important Points:"
},
{
"code": null,
"e": 5380,
"s": 5325,
"text": "You can use loops to send mails to a number of people."
},
{
"code": null,
"e": 5558,
"s": 5380,
"text": "This code is simple to implement. But it will not work if you have enabled 2-step verification on your gmail account. It is required to switch off the 2-step verification first."
},
{
"code": null,
"e": 5669,
"s": 5558,
"text": "Using this method, Gmail will always put your mail in the primary section and the mails sent will not be Spam."
},
{
"code": null,
"e": 5971,
"s": 5669,
"text": "This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6096,
"s": 5971,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6111,
"s": 6096,
"text": "python-utility"
},
{
"code": null,
"e": 6118,
"s": 6111,
"text": "Python"
},
{
"code": null,
"e": 6127,
"s": 6118,
"text": "TechTips"
},
{
"code": null,
"e": 6225,
"s": 6127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6243,
"s": 6225,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6285,
"s": 6243,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6307,
"s": 6285,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6342,
"s": 6307,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 6368,
"s": 6342,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6421,
"s": 6368,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 6447,
"s": 6421,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 6482,
"s": 6447,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 6523,
"s": 6482,
"text": "How to Run a Python Script using Docker?"
}
] |
How to create an unique id in ReactJS ? | 11 Nov, 2021
In this article, we will see the simple steps to create a unique reference ID in react JS. This has many uses such as giving a user uploaded image a unique name for saving in a database.
Approach: We will be using Uuid V4 in this tutorial. Uuid v4 is a React library or package that creates a universally unique identifier (UUID). It is a 128-bit unique identifier generator. The bits that comprise a UUID v4 are generated randomly and with no inherent logic. Because of this, there is no way to identify information about the source by looking at the UUID, so it is very unique.
Below is the step by step implementation:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: After creating, your project directory should look like this.
Project Directory
Step 3: Delete all files from the src folder except for index.js and app.js(not necessary but recommended). Next, install UUID v4 using the following command:
npm install uuidv4
Step 4: Import the package into your component, page or code etc. You can now assign the Unique ID to any variable using the below code. unique_id is an example here, it can be any variable name. We are storing the unique id in it. You can then console.log() it to see the output and also use it wherever needed. Here I am displaying it in a <p> tag.
If the unique id is too long, you can slice it or extract a small part of it to use. We can use the JavaScript slice() function here. It takes 2 parameters, the number of characters and the last character.The variable small_id will store this sliced id. We will output both the ids on the browser to see the difference.
App.js
//import uuid v4import { v4 as uuid } from 'uuid'; export default function App() { const unique_id = uuid(); const small_id = unique_id.slice(0,8) return ( <div className="App"> <h1>Unique ID</h1> <p>{unique_id}</p> <h1>Sliced Unique ID</h1> <p>{small_id}</p> </div> );}
Step to run the application: To run the app, use the following command:
npm start
Output: Now if you run the app, the unique id will be shown below the heading. Each time you refresh, a new and unique id will be shown with no repetition.
Output
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "In this article, we will see the simple steps to create a unique reference ID in react JS. This has many uses such as giving a user uploaded image a unique name for saving in a database."
},
{
"code": null,
"e": 608,
"s": 215,
"text": "Approach: We will be using Uuid V4 in this tutorial. Uuid v4 is a React library or package that creates a universally unique identifier (UUID). It is a 128-bit unique identifier generator. The bits that comprise a UUID v4 are generated randomly and with no inherent logic. Because of this, there is no way to identify information about the source by looking at the UUID, so it is very unique."
},
{
"code": null,
"e": 650,
"s": 608,
"text": "Below is the step by step implementation:"
},
{
"code": null,
"e": 714,
"s": 650,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 746,
"s": 714,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 847,
"s": 746,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 861,
"s": 847,
"text": "cd foldername"
},
{
"code": null,
"e": 942,
"s": 861,
"text": "Project Structure: After creating, your project directory should look like this."
},
{
"code": null,
"e": 960,
"s": 942,
"text": "Project Directory"
},
{
"code": null,
"e": 1119,
"s": 960,
"text": "Step 3: Delete all files from the src folder except for index.js and app.js(not necessary but recommended). Next, install UUID v4 using the following command:"
},
{
"code": null,
"e": 1138,
"s": 1119,
"text": "npm install uuidv4"
},
{
"code": null,
"e": 1489,
"s": 1138,
"text": "Step 4: Import the package into your component, page or code etc. You can now assign the Unique ID to any variable using the below code. unique_id is an example here, it can be any variable name. We are storing the unique id in it. You can then console.log() it to see the output and also use it wherever needed. Here I am displaying it in a <p> tag."
},
{
"code": null,
"e": 1809,
"s": 1489,
"text": "If the unique id is too long, you can slice it or extract a small part of it to use. We can use the JavaScript slice() function here. It takes 2 parameters, the number of characters and the last character.The variable small_id will store this sliced id. We will output both the ids on the browser to see the difference."
},
{
"code": null,
"e": 1816,
"s": 1809,
"text": "App.js"
},
{
"code": "//import uuid v4import { v4 as uuid } from 'uuid'; export default function App() { const unique_id = uuid(); const small_id = unique_id.slice(0,8) return ( <div className=\"App\"> <h1>Unique ID</h1> <p>{unique_id}</p> <h1>Sliced Unique ID</h1> <p>{small_id}</p> </div> );}",
"e": 2118,
"s": 1816,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2118,
"text": "Step to run the application: To run the app, use the following command:"
},
{
"code": null,
"e": 2200,
"s": 2190,
"text": "npm start"
},
{
"code": null,
"e": 2356,
"s": 2200,
"text": "Output: Now if you run the app, the unique id will be shown below the heading. Each time you refresh, a new and unique id will be shown with no repetition."
},
{
"code": null,
"e": 2363,
"s": 2356,
"text": "Output"
},
{
"code": null,
"e": 2379,
"s": 2363,
"text": "React-Questions"
},
{
"code": null,
"e": 2387,
"s": 2379,
"text": "ReactJS"
},
{
"code": null,
"e": 2404,
"s": 2387,
"text": "Web Technologies"
},
{
"code": null,
"e": 2502,
"s": 2404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2540,
"s": 2502,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2567,
"s": 2540,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2606,
"s": 2567,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 2658,
"s": 2606,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2697,
"s": 2658,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2759,
"s": 2697,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2792,
"s": 2759,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2853,
"s": 2792,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2903,
"s": 2853,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | sympy.divisor_sigma() method | 17 Sep, 2019
With the help of sympy.divisor_sigma() method, we can find the divisor function for positive integer n. divisor_sigma(n, k) is equal to the sum of all the divisors of n raised to the power of k or sum([x**k for x in divisors(n)]).
Syntax: divisor_sigma(n, k)
Parameter:n – It denotes an integer.k – It denotes an integer(optional). Default for k is 1.
Returns: Returns the sum of all the divisors of n raised to the power of k.
Example #1:
# import divisor_sigma() method from sympyfrom sympy.ntheory import divisor_sigma n = 8 # Use divisor_sigma() method divisor_sigma_n = divisor_sigma(n) print("divisor_sigma({}) = {} ".format(n, divisor_sigma_n)) # 1 ^ 1 + 2 ^ 1 + 4 ^ 1 + 8 ^ 1 = 15
Output:
divisor_sigma(8) = 15
Example #2:
# import divisor_sigma() method from sympyfrom sympy.ntheory import divisor_sigma n = 15k = 2 # Use divisor_sigma() method divisor_sigma_n = divisor_sigma(n, k) print("divisor_sigma({}, {}) = {} ".format(n, k, divisor_sigma_n)) # 1 ^ 2 + 3 ^ 2 + 5 ^ 2 + 15 ^ 2 = 260
Output:
divisor_sigma(15, 2) = 260
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 260,
"s": 28,
"text": "With the help of sympy.divisor_sigma() method, we can find the divisor function for positive integer n. divisor_sigma(n, k) is equal to the sum of all the divisors of n raised to the power of k or sum([x**k for x in divisors(n)])."
},
{
"code": null,
"e": 288,
"s": 260,
"text": "Syntax: divisor_sigma(n, k)"
},
{
"code": null,
"e": 381,
"s": 288,
"text": "Parameter:n – It denotes an integer.k – It denotes an integer(optional). Default for k is 1."
},
{
"code": null,
"e": 457,
"s": 381,
"text": "Returns: Returns the sum of all the divisors of n raised to the power of k."
},
{
"code": null,
"e": 469,
"s": 457,
"text": "Example #1:"
},
{
"code": "# import divisor_sigma() method from sympyfrom sympy.ntheory import divisor_sigma n = 8 # Use divisor_sigma() method divisor_sigma_n = divisor_sigma(n) print(\"divisor_sigma({}) = {} \".format(n, divisor_sigma_n)) # 1 ^ 1 + 2 ^ 1 + 4 ^ 1 + 8 ^ 1 = 15",
"e": 727,
"s": 469,
"text": null
},
{
"code": null,
"e": 735,
"s": 727,
"text": "Output:"
},
{
"code": null,
"e": 760,
"s": 735,
"text": "divisor_sigma(8) = 15 \n"
},
{
"code": null,
"e": 772,
"s": 760,
"text": "Example #2:"
},
{
"code": "# import divisor_sigma() method from sympyfrom sympy.ntheory import divisor_sigma n = 15k = 2 # Use divisor_sigma() method divisor_sigma_n = divisor_sigma(n, k) print(\"divisor_sigma({}, {}) = {} \".format(n, k, divisor_sigma_n)) # 1 ^ 2 + 3 ^ 2 + 5 ^ 2 + 15 ^ 2 = 260",
"e": 1048,
"s": 772,
"text": null
},
{
"code": null,
"e": 1056,
"s": 1048,
"text": "Output:"
},
{
"code": null,
"e": 1086,
"s": 1056,
"text": "divisor_sigma(15, 2) = 260 \n"
},
{
"code": null,
"e": 1092,
"s": 1086,
"text": "SymPy"
},
{
"code": null,
"e": 1099,
"s": 1092,
"text": "Python"
},
{
"code": null,
"e": 1197,
"s": 1099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1229,
"s": 1197,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1256,
"s": 1229,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1277,
"s": 1256,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1300,
"s": 1277,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1356,
"s": 1300,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1387,
"s": 1356,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1429,
"s": 1387,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1471,
"s": 1429,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1510,
"s": 1471,
"text": "Python | Get unique values from a list"
}
] |
Dynamically Execute JavaScript in ElectronJS | 25 Aug, 2021
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.In Electron, every BrowserWindow Instance can be thought of as an individual webpage within the application. Electron creates and controls these BrowserWindow Instances using the BrowserWindow Object and the webContents property. In traditional web applications, we can type in JavaScript code within the console of the browser for it be executed on the webpage. For achieving the same via scripts, we need to use a browser plugin or an extension. In Electron, the webContents property provides us with certain Instance methods by which we can dynamically inject JavaScript code within the BrowserWindow Instance during runtime. This tutorial will demonstrate how to use those Instance methods of the webContents property. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:
Example: Follow the Steps given in Build a Desktop Application using ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base.
package.json:
{
"name": "electron-execute",
"version": "1.0.0",
"description": "Inject JS Code in Page ",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Create the assets folder according to the project structure. Create the sample.txt file in the assets folder for demo purposes. sample.txt:
Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following Output:
Dynamically Inject JS in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module.index.html: Add the following snippet in that file.
HTML
<h3>Dynamically Inject JS</h3> <button id="inject">Read sample.txt File</button> <button id="print">Print an Array</button>
The Read sample.txt File and Print an Array buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file.index.js:
Javascript
const electron = require('electron') // Importing BrowserWindow from Main Process using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; var inject = document.getElementById('inject');let win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0]; inject.addEventListener('click', (event) => { win.webContents.executeJavaScript('const path = require("path");' + 'const fs = require("fs");' + 'fs.readFile(path.join(__dirname, "../assets/sample.txt"), ' + '{encoding: "utf-8"}, function(err, data) {' + 'if (!err) { console.log("received data: " + data); }' + 'else { console.log(err); } });', true) .then(console.log('JavaScript Executed Successfully'));}); var print = document.getElementById('print');print.addEventListener('click', (event) => { var webSource = { code: 'var numbers = [1, 2, 3, 4, 5];' + 'function filters(num) { return num > 2; }' + 'console.log(numbers.filter(filters));', url: '', startLine: 1 } win.webContents.executeJavaScriptInIsolatedWorld(1, [webSource], true) .then(console.log('JavaScript Executed Successfully'));});
Explanation: The webContents.executeJavaScript(code, userGesture) method simply executes the code in the webpage i.e. the BrowserWindow Instance. This method returns a Promise and it is resolved with the result of the executed code or the Promise is rejected if the result of the code itself is a rejected Promise. This means that the Promise can return any datatype including an object based on the result of the executed code. In case, the executed code throws an Error, it will be displayed on the console. In case, the executed code does not return a Promise but implements a callback instead, then this Promise will be resolved to a void as demonstrated in the above code. It takes in the following parameters. The code execution will be suspended until the webpage is loaded completely. In our code, this method is Invoked by clicking on the Read sample.txt File button.
code: String This value cannot be empty. This value represents the code to be executed in the BrowserWindow instance. In the above code, we have read the contents of the sample.txt file using the fs.readFile() method. The fs.readFile() implements a callback and returns the contents of the file.
userGesture: Boolean (Optional) In the BrowserWindow Instance, some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. This limitation can be removed by setting the userGesture property to true. Default value is false.
The webContents.executeJavaScriptInIsolatedWorld(worldId, scripts, userGesture) also executes the code in the webpage but it does so in an Isolated Context. This method also returns a Promise and it behaves in the same way as described for the webContents.executeJavaScript() method. It takes in the following parameters. In our code, this method is Invoked by clicking on the Print an Array button.
worldId: Integer This value represents the ID of the virtual isolated world to run the JavaScript code in. The default worldID is 0. Electron’s contextIsolation feature uses 999 as the worldID. We can provide any Integer value here. The JavaScript code executed in this virtual isolated world cannot interact with the code of the BrowserWindow Instance and it is evaluated as a completely separate code. Using this method, we can create any number of virtual isolated worlds to run different segments of the JavaScript code.
scripts: webSource[] This property takes in an Array of webSource Objects. Hence this method can execute multiple different code blocks within the same world. Each webSource object takes in the following parameters. code: String This value cannot be empty. This value represents the code to be executed in the BrowserWindow instance. In the above code, we have used the array.filter() function to create a new array satisfying the condition of any number which is greater than 2 from a sample array of numbers.startLine: Integer (Optional) Default value is 1. As the name suggests, this value represents the Integer from which the code String should be evaluated.
code: String This value cannot be empty. This value represents the code to be executed in the BrowserWindow instance. In the above code, we have used the array.filter() function to create a new array satisfying the condition of any number which is greater than 2 from a sample array of numbers.
startLine: Integer (Optional) Default value is 1. As the name suggests, this value represents the Integer from which the code String should be evaluated.
userGesture: Boolean (Optional) In the BrowserWindow Instance, some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. This limitation can be removed by setting the userGesture property to true. Default value is false.
Note: The webContents.executeJavaScript() method can interact with code of the BrowserWindow Instance and hence we can also use NodeJS functions in the code. For example, we can use the require function to import the fs and path modules and they will be recognized by the code. The webContents.executeJavaScriptInIsolatedWorld() method cannot interact with the code of the BrowserWindow Instance and hence we cannot use NodeJS functions since it will not recognize them. In the webContents.executeJavaScriptInIsolatedWorld() method we can only execute pure client-side JavaScript code. In case NodeJS functions are used, it will display an Error in console.
To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object.
BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code.
BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code.
Output:
surinderdawra388
surindertarika1234
simmytarika5
ElectronJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n25 Aug, 2021"
},
{
"code": null,
"e": 1220,
"s": 28,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.In Electron, every BrowserWindow Instance can be thought of as an individual webpage within the application. Electron creates and controls these BrowserWindow Instances using the BrowserWindow Object and the webContents property. In traditional web applications, we can type in JavaScript code within the console of the browser for it be executed on the webpage. For achieving the same via scripts, we need to use a browser plugin or an extension. In Electron, the webContents property provides us with certain Instance methods by which we can dynamically inject JavaScript code within the BrowserWindow Instance during runtime. This tutorial will demonstrate how to use those Instance methods of the webContents property. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system."
},
{
"code": null,
"e": 1240,
"s": 1220,
"text": "Project Structure: "
},
{
"code": null,
"e": 1637,
"s": 1240,
"text": "Example: Follow the Steps given in Build a Desktop Application using ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. "
},
{
"code": null,
"e": 1653,
"s": 1637,
"text": "package.json: "
},
{
"code": null,
"e": 1955,
"s": 1653,
"text": "{\n \"name\": \"electron-execute\",\n \"version\": \"1.0.0\",\n \"description\": \"Inject JS Code in Page \",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}"
},
{
"code": null,
"e": 2096,
"s": 1955,
"text": "Create the assets folder according to the project structure. Create the sample.txt file in the assets folder for demo purposes. sample.txt: "
},
{
"code": null,
"e": 2230,
"s": 2096,
"text": "Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following Output: "
},
{
"code": null,
"e": 2497,
"s": 2230,
"text": "Dynamically Inject JS in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module.index.html: Add the following snippet in that file. "
},
{
"code": null,
"e": 2502,
"s": 2497,
"text": "HTML"
},
{
"code": "<h3>Dynamically Inject JS</h3> <button id=\"inject\">Read sample.txt File</button> <button id=\"print\">Print an Array</button>",
"e": 2628,
"s": 2502,
"text": null
},
{
"code": null,
"e": 2807,
"s": 2628,
"text": "The Read sample.txt File and Print an Array buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file.index.js: "
},
{
"code": null,
"e": 2818,
"s": 2807,
"text": "Javascript"
},
{
"code": "const electron = require('electron') // Importing BrowserWindow from Main Process using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; var inject = document.getElementById('inject');let win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0]; inject.addEventListener('click', (event) => { win.webContents.executeJavaScript('const path = require(\"path\");' + 'const fs = require(\"fs\");' + 'fs.readFile(path.join(__dirname, \"../assets/sample.txt\"), ' + '{encoding: \"utf-8\"}, function(err, data) {' + 'if (!err) { console.log(\"received data: \" + data); }' + 'else { console.log(err); } });', true) .then(console.log('JavaScript Executed Successfully'));}); var print = document.getElementById('print');print.addEventListener('click', (event) => { var webSource = { code: 'var numbers = [1, 2, 3, 4, 5];' + 'function filters(num) { return num > 2; }' + 'console.log(numbers.filter(filters));', url: '', startLine: 1 } win.webContents.executeJavaScriptInIsolatedWorld(1, [webSource], true) .then(console.log('JavaScript Executed Successfully'));});",
"e": 4009,
"s": 2818,
"text": null
},
{
"code": null,
"e": 4886,
"s": 4009,
"text": "Explanation: The webContents.executeJavaScript(code, userGesture) method simply executes the code in the webpage i.e. the BrowserWindow Instance. This method returns a Promise and it is resolved with the result of the executed code or the Promise is rejected if the result of the code itself is a rejected Promise. This means that the Promise can return any datatype including an object based on the result of the executed code. In case, the executed code throws an Error, it will be displayed on the console. In case, the executed code does not return a Promise but implements a callback instead, then this Promise will be resolved to a void as demonstrated in the above code. It takes in the following parameters. The code execution will be suspended until the webpage is loaded completely. In our code, this method is Invoked by clicking on the Read sample.txt File button."
},
{
"code": null,
"e": 5182,
"s": 4886,
"text": "code: String This value cannot be empty. This value represents the code to be executed in the BrowserWindow instance. In the above code, we have read the contents of the sample.txt file using the fs.readFile() method. The fs.readFile() implements a callback and returns the contents of the file."
},
{
"code": null,
"e": 5431,
"s": 5182,
"text": "userGesture: Boolean (Optional) In the BrowserWindow Instance, some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. This limitation can be removed by setting the userGesture property to true. Default value is false."
},
{
"code": null,
"e": 5832,
"s": 5431,
"text": "The webContents.executeJavaScriptInIsolatedWorld(worldId, scripts, userGesture) also executes the code in the webpage but it does so in an Isolated Context. This method also returns a Promise and it behaves in the same way as described for the webContents.executeJavaScript() method. It takes in the following parameters. In our code, this method is Invoked by clicking on the Print an Array button. "
},
{
"code": null,
"e": 6357,
"s": 5832,
"text": "worldId: Integer This value represents the ID of the virtual isolated world to run the JavaScript code in. The default worldID is 0. Electron’s contextIsolation feature uses 999 as the worldID. We can provide any Integer value here. The JavaScript code executed in this virtual isolated world cannot interact with the code of the BrowserWindow Instance and it is evaluated as a completely separate code. Using this method, we can create any number of virtual isolated worlds to run different segments of the JavaScript code."
},
{
"code": null,
"e": 7021,
"s": 6357,
"text": "scripts: webSource[] This property takes in an Array of webSource Objects. Hence this method can execute multiple different code blocks within the same world. Each webSource object takes in the following parameters. code: String This value cannot be empty. This value represents the code to be executed in the BrowserWindow instance. In the above code, we have used the array.filter() function to create a new array satisfying the condition of any number which is greater than 2 from a sample array of numbers.startLine: Integer (Optional) Default value is 1. As the name suggests, this value represents the Integer from which the code String should be evaluated."
},
{
"code": null,
"e": 7316,
"s": 7021,
"text": "code: String This value cannot be empty. This value represents the code to be executed in the BrowserWindow instance. In the above code, we have used the array.filter() function to create a new array satisfying the condition of any number which is greater than 2 from a sample array of numbers."
},
{
"code": null,
"e": 7470,
"s": 7316,
"text": "startLine: Integer (Optional) Default value is 1. As the name suggests, this value represents the Integer from which the code String should be evaluated."
},
{
"code": null,
"e": 7719,
"s": 7470,
"text": "userGesture: Boolean (Optional) In the BrowserWindow Instance, some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. This limitation can be removed by setting the userGesture property to true. Default value is false."
},
{
"code": null,
"e": 8377,
"s": 7719,
"text": "Note: The webContents.executeJavaScript() method can interact with code of the BrowserWindow Instance and hence we can also use NodeJS functions in the code. For example, we can use the require function to import the fs and path modules and they will be recognized by the code. The webContents.executeJavaScriptInIsolatedWorld() method cannot interact with the code of the BrowserWindow Instance and hence we cannot use NodeJS functions since it will not recognize them. In the webContents.executeJavaScriptInIsolatedWorld() method we can only execute pure client-side JavaScript code. In case NodeJS functions are used, it will display an Error in console."
},
{
"code": null,
"e": 8522,
"s": 8377,
"text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. "
},
{
"code": null,
"e": 8761,
"s": 8522,
"text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code."
},
{
"code": null,
"e": 9083,
"s": 8761,
"text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code."
},
{
"code": null,
"e": 9093,
"s": 9083,
"text": "Output: "
},
{
"code": null,
"e": 9112,
"s": 9095,
"text": "surinderdawra388"
},
{
"code": null,
"e": 9131,
"s": 9112,
"text": "surindertarika1234"
},
{
"code": null,
"e": 9144,
"s": 9131,
"text": "simmytarika5"
},
{
"code": null,
"e": 9155,
"s": 9144,
"text": "ElectronJS"
},
{
"code": null,
"e": 9166,
"s": 9155,
"text": "JavaScript"
},
{
"code": null,
"e": 9183,
"s": 9166,
"text": "Web Technologies"
},
{
"code": null,
"e": 9281,
"s": 9183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9342,
"s": 9281,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 9414,
"s": 9342,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 9454,
"s": 9414,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 9506,
"s": 9454,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 9547,
"s": 9506,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 9609,
"s": 9547,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 9642,
"s": 9609,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 9703,
"s": 9642,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 9753,
"s": 9703,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to convert array to string in PHP ? | 31 Jul, 2021
We have given an array and the task is to convert the array elements into string. In this article, we are using two methods to convert array to string.
Method 1: Using implode() function: The implode() method is an inbuilt function in PHP and is used to join the elements of an array. The implode() method is an alias for PHP | join() function and works exactly same as that of join() function.
Syntax:
string implode($separator, $array)
Example:
PHP
<?php // Declare an array $arr = array("Welcome","to", "GeeksforGeeks", "A", "Computer","Science","Portal"); // Converting array elements into// strings using implode functionecho implode(" ",$arr); ?>
Output:
Welcome to GeeksforGeeks A Computer Science Portal
Method 2: Using json_encode() Function: The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.Syntax:
string json_encode( $value, $option, $depth )
Example:
PHP
<?php // Declare multi-dimensional array $value = array( "name"=>"GFG", array( "email"=>"[email protected]", "mobile"=>"XXXXXXXXXX" ) ); // Use json_encode() function $json = json_encode($value); // Display the output echo($json); ?>
Output:
{"name":"GFG","0":{"email":"[email protected]","mobile":"XXXXXXXXXX"}}
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-Misc
Picked
Technical Scripter 2020
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 205,
"s": 53,
"text": "We have given an array and the task is to convert the array elements into string. In this article, we are using two methods to convert array to string."
},
{
"code": null,
"e": 448,
"s": 205,
"text": "Method 1: Using implode() function: The implode() method is an inbuilt function in PHP and is used to join the elements of an array. The implode() method is an alias for PHP | join() function and works exactly same as that of join() function."
},
{
"code": null,
"e": 456,
"s": 448,
"text": "Syntax:"
},
{
"code": null,
"e": 491,
"s": 456,
"text": "string implode($separator, $array)"
},
{
"code": null,
"e": 500,
"s": 491,
"text": "Example:"
},
{
"code": null,
"e": 504,
"s": 500,
"text": "PHP"
},
{
"code": "<?php // Declare an array $arr = array(\"Welcome\",\"to\", \"GeeksforGeeks\", \"A\", \"Computer\",\"Science\",\"Portal\"); // Converting array elements into// strings using implode functionecho implode(\" \",$arr); ?>",
"e": 720,
"s": 504,
"text": null
},
{
"code": null,
"e": 728,
"s": 720,
"text": "Output:"
},
{
"code": null,
"e": 779,
"s": 728,
"text": "Welcome to GeeksforGeeks A Computer Science Portal"
},
{
"code": null,
"e": 954,
"s": 779,
"text": "Method 2: Using json_encode() Function: The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.Syntax:"
},
{
"code": null,
"e": 1000,
"s": 954,
"text": "string json_encode( $value, $option, $depth )"
},
{
"code": null,
"e": 1009,
"s": 1000,
"text": "Example:"
},
{
"code": null,
"e": 1013,
"s": 1009,
"text": "PHP"
},
{
"code": "<?php // Declare multi-dimensional array $value = array( \"name\"=>\"GFG\", array( \"email\"=>\"[email protected]\", \"mobile\"=>\"XXXXXXXXXX\" ) ); // Use json_encode() function $json = json_encode($value); // Display the output echo($json); ?> ",
"e": 1277,
"s": 1013,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1277,
"text": "Output:"
},
{
"code": null,
"e": 1350,
"s": 1285,
"text": "{\"name\":\"GFG\",\"0\":{\"email\":\"[email protected]\",\"mobile\":\"XXXXXXXXXX\"}}"
},
{
"code": null,
"e": 1519,
"s": 1350,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 1528,
"s": 1519,
"text": "PHP-Misc"
},
{
"code": null,
"e": 1535,
"s": 1528,
"text": "Picked"
},
{
"code": null,
"e": 1559,
"s": 1535,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1563,
"s": 1559,
"text": "PHP"
},
{
"code": null,
"e": 1576,
"s": 1563,
"text": "PHP Programs"
},
{
"code": null,
"e": 1595,
"s": 1576,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1612,
"s": 1595,
"text": "Web Technologies"
},
{
"code": null,
"e": 1639,
"s": 1612,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1643,
"s": 1639,
"text": "PHP"
}
] |
Python Program to Find the Area of a Rectangle Using Classes | When it is required to find the area of a rectangle using classes, object oriented method is used. Here, a class is defined, attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to find the area of rectangle.
Below is a demonstration for the same −
Live Demo
class shape_rectangle():
def __init__(self,my_length, my_breadth):
self.length = my_length
self.breadth = my_breadth
def calculate_area(self):
return self.length*self.breadth
len_val = 6
bread_val = 45
print("The length of the rectangle is : ")
print(len_val)
print("The breadth of the rectangle is : ")
print(bread_val)
my_instance = shape_rectangle(len_val,bread_val)
print("The area of the rectangle : ")
print(my_instance.calculate_area())
print()
The length of the rectangle is :
6
The breadth of the rectangle is :
45
The area of the rectangle :
270
A class named ‘shape_rectangle’ is defined.
It has the ‘init’ method that initializes values.
It also has a method that calculates the area of the rectangle given the specific parameters.
An instance of this class is created.
The function to calculate area is called by passing required parameters.
It is displayed as output on the console. | [
{
"code": null,
"e": 1503,
"s": 1187,
"text": "When it is required to find the area of a rectangle using classes, object oriented method is used. Here, a class is defined, attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to find the area of rectangle."
},
{
"code": null,
"e": 1543,
"s": 1503,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1554,
"s": 1543,
"text": " Live Demo"
},
{
"code": null,
"e": 2015,
"s": 1554,
"text": "class shape_rectangle():\ndef __init__(self,my_length, my_breadth):\n self.length = my_length\n self.breadth = my_breadth\ndef calculate_area(self):\n return self.length*self.breadth\nlen_val = 6\nbread_val = 45\nprint(\"The length of the rectangle is : \")\nprint(len_val)\nprint(\"The breadth of the rectangle is : \")\nprint(bread_val)\nmy_instance = shape_rectangle(len_val,bread_val)\nprint(\"The area of the rectangle : \")\nprint(my_instance.calculate_area())\nprint()"
},
{
"code": null,
"e": 2119,
"s": 2015,
"text": "The length of the rectangle is :\n6\nThe breadth of the rectangle is :\n45\nThe area of the rectangle :\n270"
},
{
"code": null,
"e": 2163,
"s": 2119,
"text": "A class named ‘shape_rectangle’ is defined."
},
{
"code": null,
"e": 2213,
"s": 2163,
"text": "It has the ‘init’ method that initializes values."
},
{
"code": null,
"e": 2307,
"s": 2213,
"text": "It also has a method that calculates the area of the rectangle given the specific parameters."
},
{
"code": null,
"e": 2345,
"s": 2307,
"text": "An instance of this class is created."
},
{
"code": null,
"e": 2418,
"s": 2345,
"text": "The function to calculate area is called by passing required parameters."
},
{
"code": null,
"e": 2460,
"s": 2418,
"text": "It is displayed as output on the console."
}
] |
Extract Values from Matrix by Column and Row Names in R | 23 May, 2021
In this article, we will discuss how to extract values from the matrix by column and row names in R Programming Language.
A row subset matrix can be extracted from the original matrix using a filter for the selected row names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out.
Syntax:
matrix[ vec , ]
Where, vec contains the row names to be fetched
All the columns are retrieved from the data frame. The order of the rows and columns remains unmodified. The rows and column names remain unchanged after extraction. The result returned is a subset of the original matrix. The row names should be a proper subset of the original row names pertaining to matrix.
Example:
R
# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c("C1","C2","C3") # naming rowsrownames(mat) <- c("R1","R2","R3","R4")print ("Original Matrix")print (mat) # extracting rows row_vec <- c("R2","R4")row_mat <- mat[row_vec ,] print ("Modified Matrix")print (row_mat)
Output
[1] "Original Matrix"
C1 C2 C3
R1 "a" "e" "i"
R2 "b" "f" "j"
R3 "c" "g" "k"
R4 "d" "h" "l"
[1] "Modified Matrix"
C1 C2 C3
R2 "b" "f" "j"
R4 "d" "h" "l"
A column subset matrix can be extracted from the original matrix using a filter for the selected column names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out.
Syntax:
matrix[ , vec ]
Where, vec contains the column names to be fetched
All the rows for the selected columns are retrieved from the data frame. The order of the rows and columns remains unmodified. The rows and column names remain unchanged after extraction. The result returned is a subset of the original matrix. The column names to be chosen should be a proper subset of the original row names pertaining to the matrix.
Example:
R
# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c("C1","C2","C3") # naming rowsrownames(mat) <- c("R1","R2","R3","R4")print ("Original Matrix")print (mat) # extracting rows col_vec <- c("C1","C3")col_mat <- mat[,col_vec]print ("Modified Matrix")print (col_mat)
Output
[1] "Original Matrix"
C1 C2 C3
R1 "a" "e" "i"
R2 "b" "f" "j"
R3 "c" "g" "k"
R4 "d" "h" "l"
[1] "Modified Matrix"
C1 C3
R1 "a" "i"
R2 "b" "j"
R3 "c" "k"
R4 "d" "l"
Similar to the above approaches, the rows, and columns can also be extracted, by specifying the chosen vectors for both indexes.
Syntax:
matrix[ rowvec , colvec ]
Where, rowvec contains the row names to be fetched and colvec the column names
Example:
R
# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c("C1","C2","C3") # naming rowsrownames(mat) <- c("R1","R2","R3","R4")print ("Original Matrix")print (mat) # extracting rows row_vec <- c("R1","R3") # extracting columns col_vec <- c("C1","C3")col_mat <- mat[row_vec ,col_vec]print ("Modified Matrix")print (col_mat)
Output
[1] "Original Matrix"
C1 C2 C3
R1 "a" "e" "i"
R2 "b" "f" "j"
R3 "c" "g" "k"
R4 "d" "h" "l"
[1] "Modified Matrix"
C1 C3
R1 "a" "i"
R3 "c" "k"
Any single element or cell value can also be fetched from the matrix, by simply specifying the row name and column name as the indexes for retrieval.
Example:
R
# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c("C1","C2","C3") # naming rowsrownames(mat) <- c("R1","R2","R3","R4")print ("Original Matrix")print (mat) # extracting single elementcol_mat <- mat["R3" , "C2"]print ("Modified Matrix")print (col_mat)
Output
[1] "Original Matrix"
C1 C2 C3
R1 "a" "e" "i"
R2 "b" "f" "j"
R3 "c" "g" "k"
R4 "d" "h" "l"
[1] "Modified Matrix"
[1] "k"
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
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?
How to filter R DataFrame by values in a column?
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
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "In this article, we will discuss how to extract values from the matrix by column and row names in R Programming Language."
},
{
"code": null,
"e": 363,
"s": 150,
"text": "A row subset matrix can be extracted from the original matrix using a filter for the selected row names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out."
},
{
"code": null,
"e": 371,
"s": 363,
"text": "Syntax:"
},
{
"code": null,
"e": 388,
"s": 371,
"text": "matrix[ vec , ] "
},
{
"code": null,
"e": 436,
"s": 388,
"text": "Where, vec contains the row names to be fetched"
},
{
"code": null,
"e": 747,
"s": 436,
"text": "All the columns are retrieved from the data frame. The order of the rows and columns remains unmodified. The rows and column names remain unchanged after extraction. The result returned is a subset of the original matrix. The row names should be a proper subset of the original row names pertaining to matrix. "
},
{
"code": null,
"e": 756,
"s": 747,
"text": "Example:"
},
{
"code": null,
"e": 758,
"s": 756,
"text": "R"
},
{
"code": "# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c(\"C1\",\"C2\",\"C3\") # naming rowsrownames(mat) <- c(\"R1\",\"R2\",\"R3\",\"R4\")print (\"Original Matrix\")print (mat) # extracting rows row_vec <- c(\"R2\",\"R4\")row_mat <- mat[row_vec ,] print (\"Modified Matrix\")print (row_mat)",
"e": 1068,
"s": 758,
"text": null
},
{
"code": null,
"e": 1075,
"s": 1068,
"text": "Output"
},
{
"code": null,
"e": 1235,
"s": 1075,
"text": "[1] \"Original Matrix\"\n C1 C2 C3\nR1 \"a\" \"e\" \"i\"\nR2 \"b\" \"f\" \"j\"\nR3 \"c\" \"g\" \"k\"\nR4 \"d\" \"h\" \"l\"\n[1] \"Modified Matrix\"\n C1 C2 C3\nR2 \"b\" \"f\" \"j\"\nR4 \"d\" \"h\" \"l\""
},
{
"code": null,
"e": 1454,
"s": 1235,
"text": "A column subset matrix can be extracted from the original matrix using a filter for the selected column names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out."
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Syntax:"
},
{
"code": null,
"e": 1480,
"s": 1462,
"text": "matrix[ , vec ] "
},
{
"code": null,
"e": 1531,
"s": 1480,
"text": "Where, vec contains the column names to be fetched"
},
{
"code": null,
"e": 1884,
"s": 1531,
"text": "All the rows for the selected columns are retrieved from the data frame. The order of the rows and columns remains unmodified. The rows and column names remain unchanged after extraction. The result returned is a subset of the original matrix. The column names to be chosen should be a proper subset of the original row names pertaining to the matrix. "
},
{
"code": null,
"e": 1893,
"s": 1884,
"text": "Example:"
},
{
"code": null,
"e": 1895,
"s": 1893,
"text": "R"
},
{
"code": "# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c(\"C1\",\"C2\",\"C3\") # naming rowsrownames(mat) <- c(\"R1\",\"R2\",\"R3\",\"R4\")print (\"Original Matrix\")print (mat) # extracting rows col_vec <- c(\"C1\",\"C3\")col_mat <- mat[,col_vec]print (\"Modified Matrix\")print (col_mat)",
"e": 2202,
"s": 1895,
"text": null
},
{
"code": null,
"e": 2209,
"s": 2202,
"text": "Output"
},
{
"code": null,
"e": 2379,
"s": 2209,
"text": "[1] \"Original Matrix\"\n C1 C2 C3\nR1 \"a\" \"e\" \"i\"\nR2 \"b\" \"f\" \"j\"\nR3 \"c\" \"g\" \"k\"\nR4 \"d\" \"h\" \"l\"\n[1] \"Modified Matrix\"\n C1 C3\nR1 \"a\" \"i\"\nR2 \"b\" \"j\"\nR3 \"c\" \"k\"\nR4 \"d\" \"l\""
},
{
"code": null,
"e": 2509,
"s": 2379,
"text": "Similar to the above approaches, the rows, and columns can also be extracted, by specifying the chosen vectors for both indexes. "
},
{
"code": null,
"e": 2517,
"s": 2509,
"text": "Syntax:"
},
{
"code": null,
"e": 2545,
"s": 2517,
"text": "matrix[ rowvec , colvec ] "
},
{
"code": null,
"e": 2624,
"s": 2545,
"text": "Where, rowvec contains the row names to be fetched and colvec the column names"
},
{
"code": null,
"e": 2633,
"s": 2624,
"text": "Example:"
},
{
"code": null,
"e": 2635,
"s": 2633,
"text": "R"
},
{
"code": "# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c(\"C1\",\"C2\",\"C3\") # naming rowsrownames(mat) <- c(\"R1\",\"R2\",\"R3\",\"R4\")print (\"Original Matrix\")print (mat) # extracting rows row_vec <- c(\"R1\",\"R3\") # extracting columns col_vec <- c(\"C1\",\"C3\")col_mat <- mat[row_vec ,col_vec]print (\"Modified Matrix\")print (col_mat)",
"e": 2996,
"s": 2635,
"text": null
},
{
"code": null,
"e": 3003,
"s": 2996,
"text": "Output"
},
{
"code": null,
"e": 3151,
"s": 3003,
"text": "[1] \"Original Matrix\"\n C1 C2 C3\nR1 \"a\" \"e\" \"i\"\nR2 \"b\" \"f\" \"j\"\nR3 \"c\" \"g\" \"k\"\nR4 \"d\" \"h\" \"l\"\n[1] \"Modified Matrix\"\n C1 C3\nR1 \"a\" \"i\"\nR3 \"c\" \"k\""
},
{
"code": null,
"e": 3302,
"s": 3151,
"text": "Any single element or cell value can also be fetched from the matrix, by simply specifying the row name and column name as the indexes for retrieval. "
},
{
"code": null,
"e": 3311,
"s": 3302,
"text": "Example:"
},
{
"code": null,
"e": 3313,
"s": 3311,
"text": "R"
},
{
"code": "# declaring matrix mat <- matrix(letters[1:12], ncol = 3) # naming columnscolnames(mat) <- c(\"C1\",\"C2\",\"C3\") # naming rowsrownames(mat) <- c(\"R1\",\"R2\",\"R3\",\"R4\")print (\"Original Matrix\")print (mat) # extracting single elementcol_mat <- mat[\"R3\" , \"C2\"]print (\"Modified Matrix\")print (col_mat)",
"e": 3609,
"s": 3313,
"text": null
},
{
"code": null,
"e": 3616,
"s": 3609,
"text": "Output"
},
{
"code": null,
"e": 3741,
"s": 3616,
"text": "[1] \"Original Matrix\"\n C1 C2 C3\nR1 \"a\" \"e\" \"i\"\nR2 \"b\" \"f\" \"j\"\nR3 \"c\" \"g\" \"k\"\nR4 \"d\" \"h\" \"l\"\n[1] \"Modified Matrix\"\n[1] \"k\""
},
{
"code": null,
"e": 3748,
"s": 3741,
"text": "Picked"
},
{
"code": null,
"e": 3766,
"s": 3748,
"text": "R Matrix-Programs"
},
{
"code": null,
"e": 3775,
"s": 3766,
"text": "R-Matrix"
},
{
"code": null,
"e": 3786,
"s": 3775,
"text": "R Language"
},
{
"code": null,
"e": 3797,
"s": 3786,
"text": "R Programs"
},
{
"code": null,
"e": 3895,
"s": 3797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3947,
"s": 3895,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4005,
"s": 3947,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4040,
"s": 4005,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4078,
"s": 4040,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4127,
"s": 4078,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4185,
"s": 4127,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4234,
"s": 4185,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4277,
"s": 4234,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4315,
"s": 4277,
"text": "Merge DataFrames by Column Names in R"
}
] |
Find the smallest and second smallest elements in an array in C++ | Suppose we have an array of n elements. We have to find the first, second smallest elements in the array. First smallest is the minimum of the array, second smallest is minimum but larger than the first smallest number.
Scan through each element, then check the element, and relate the condition for first, and second smallest elements conditions to solve this problem.
#include<iostream>
using namespace std;
int getTwoSmallest(int arr[], int n) {
int first = INT_MAX, sec = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] < first) {
sec = first;
first = arr[i];
}else if (arr[i] < sec) {
sec = arr[i];
}
}
cout << "First smallest = " << first << endl;
cout << "Second smallest = " << sec << endl;
}
int main() {
int array[] = {4, 9, 18, 32, 12};
int n = sizeof(array) / sizeof(array[0]);
getTwoSmallest(array, n);
}
First smallest = 4
Second smallest = 9 | [
{
"code": null,
"e": 1407,
"s": 1187,
"text": "Suppose we have an array of n elements. We have to find the first, second smallest elements in the array. First smallest is the minimum of the array, second smallest is minimum but larger than the first smallest number."
},
{
"code": null,
"e": 1557,
"s": 1407,
"text": "Scan through each element, then check the element, and relate the condition for first, and second smallest elements conditions to solve this problem."
},
{
"code": null,
"e": 2076,
"s": 1557,
"text": "#include<iostream>\nusing namespace std;\nint getTwoSmallest(int arr[], int n) {\n int first = INT_MAX, sec = INT_MAX;\n for (int i = 0; i < n; i++) {\n if (arr[i] < first) {\n sec = first;\n first = arr[i];\n }else if (arr[i] < sec) {\n sec = arr[i];\n }\n }\n cout << \"First smallest = \" << first << endl;\n cout << \"Second smallest = \" << sec << endl;\n}\nint main() {\n int array[] = {4, 9, 18, 32, 12};\n int n = sizeof(array) / sizeof(array[0]);\n getTwoSmallest(array, n);\n}"
},
{
"code": null,
"e": 2115,
"s": 2076,
"text": "First smallest = 4\nSecond smallest = 9"
}
] |
Move Axis Labels in ggplot in R | 17 Jun, 2021
In this article, we are going to see how to move the axis labels using ggplot2 bar plot in the R programming language.
First, you need to install the ggplot2 package if it is not previously installed in R Studio. For creating a simple bar plot we will use the function geom_bar( ).
Syntax:
geom_bar(stat, fill, color, width)
Parameters :
stat : Set the stat parameter to identify the mode.
fill : Represents color inside the bars.
color : Represents color of outlines of the bars.
width : Represents width of the bars.
Data in use:
Let us see what the default plot will look like without any modifications.
R
library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf
Output:
By default, R adds the vector names which are assigned in the Data Frame as the axis title. To manually add axis title use the following commands :
// To modify the x axis label
xlab(“X_axis_Labelname”)
// To modify the y axis label
ylab(“Y_axis_Labelname”)
// Simultaneously modify both x and y axes title
labs(x=”X_axis_Labelname”,y=”Y_axis_Labelname”)
Example:
R
library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels ggp <- perf+labs(x="Matches",y="Runs Scored")ggp
Output:
To perform any modifications in the axis labels we use the function element_text( ). The arguments of this function are :
Color
Size
Face
Family
lineheight
hjust and vjust
The argument hjust (Horizontal Adjust) or vjust (Vertical Adjust) is used to move the axis labels. They take numbers in range [0,1] where :
// Depicts left most corner of the axis
hjust = 0
// Depicts middle of the axis
hjust = 0.5
// Depicts right most corner of the axis
hjust = 1
Let us first create a plot with axis labels towards the left.
Example:
R
library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels ggp <- perf+labs(x="Matches",y="Runs Scored")ggp # Moving axis label to leftggp + theme( axis.title.x = element_text(hjust=0), axis.title.y = element_text(hjust=0) )
Output:
Now lets move them to the center.
Example:
R
library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels ggp <- perf+labs(x="Matches",y="Runs Scored")ggp # Moving axis label in middleggp + theme( axis.title.x = element_text(hjust=0.5), axis.title.y = element_text(hjust=0.5))
Output:
Similar can be done for moving them towards the right.
Example:
R
library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels ggp <- perf+labs(x="Matches",y="Runs Scored")ggp # Moving axis label to rightggp + theme( axis.title.x = element_text(hjust=1), axis.title.y = element_text(hjust=1))
Output:
Picked
R-ggplot
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?
How to filter R DataFrame by values in a column?
R - if statement
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": "\n17 Jun, 2021"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "In this article, we are going to see how to move the axis labels using ggplot2 bar plot in the R programming language."
},
{
"code": null,
"e": 310,
"s": 147,
"text": "First, you need to install the ggplot2 package if it is not previously installed in R Studio. For creating a simple bar plot we will use the function geom_bar( )."
},
{
"code": null,
"e": 318,
"s": 310,
"text": "Syntax:"
},
{
"code": null,
"e": 353,
"s": 318,
"text": "geom_bar(stat, fill, color, width)"
},
{
"code": null,
"e": 368,
"s": 353,
"text": "Parameters : "
},
{
"code": null,
"e": 420,
"s": 368,
"text": "stat : Set the stat parameter to identify the mode."
},
{
"code": null,
"e": 461,
"s": 420,
"text": "fill : Represents color inside the bars."
},
{
"code": null,
"e": 511,
"s": 461,
"text": "color : Represents color of outlines of the bars."
},
{
"code": null,
"e": 549,
"s": 511,
"text": "width : Represents width of the bars."
},
{
"code": null,
"e": 562,
"s": 549,
"text": "Data in use:"
},
{
"code": null,
"e": 637,
"s": 562,
"text": "Let us see what the default plot will look like without any modifications."
},
{
"code": null,
"e": 639,
"s": 637,
"text": "R"
},
{
"code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf",
"e": 904,
"s": 639,
"text": null
},
{
"code": null,
"e": 912,
"s": 904,
"text": "Output:"
},
{
"code": null,
"e": 1060,
"s": 912,
"text": "By default, R adds the vector names which are assigned in the Data Frame as the axis title. To manually add axis title use the following commands :"
},
{
"code": null,
"e": 1090,
"s": 1060,
"text": "// To modify the x axis label"
},
{
"code": null,
"e": 1116,
"s": 1090,
"text": "xlab(“X_axis_Labelname”) "
},
{
"code": null,
"e": 1147,
"s": 1116,
"text": "// To modify the y axis label "
},
{
"code": null,
"e": 1173,
"s": 1147,
"text": "ylab(“Y_axis_Labelname”) "
},
{
"code": null,
"e": 1222,
"s": 1173,
"text": "// Simultaneously modify both x and y axes title"
},
{
"code": null,
"e": 1271,
"s": 1222,
"text": "labs(x=”X_axis_Labelname”,y=”Y_axis_Labelname”) "
},
{
"code": null,
"e": 1280,
"s": 1271,
"text": "Example:"
},
{
"code": null,
"e": 1282,
"s": 1280,
"text": "R"
},
{
"code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels ggp <- perf+labs(x=\"Matches\",y=\"Runs Scored\")ggp",
"e": 1627,
"s": 1282,
"text": null
},
{
"code": null,
"e": 1635,
"s": 1627,
"text": "Output:"
},
{
"code": null,
"e": 1757,
"s": 1635,
"text": "To perform any modifications in the axis labels we use the function element_text( ). The arguments of this function are :"
},
{
"code": null,
"e": 1763,
"s": 1757,
"text": "Color"
},
{
"code": null,
"e": 1768,
"s": 1763,
"text": "Size"
},
{
"code": null,
"e": 1773,
"s": 1768,
"text": "Face"
},
{
"code": null,
"e": 1780,
"s": 1773,
"text": "Family"
},
{
"code": null,
"e": 1791,
"s": 1780,
"text": "lineheight"
},
{
"code": null,
"e": 1807,
"s": 1791,
"text": "hjust and vjust"
},
{
"code": null,
"e": 1947,
"s": 1807,
"text": "The argument hjust (Horizontal Adjust) or vjust (Vertical Adjust) is used to move the axis labels. They take numbers in range [0,1] where :"
},
{
"code": null,
"e": 1987,
"s": 1947,
"text": "// Depicts left most corner of the axis"
},
{
"code": null,
"e": 1998,
"s": 1987,
"text": "hjust = 0 "
},
{
"code": null,
"e": 2028,
"s": 1998,
"text": "// Depicts middle of the axis"
},
{
"code": null,
"e": 2040,
"s": 2028,
"text": "hjust = 0.5"
},
{
"code": null,
"e": 2082,
"s": 2040,
"text": "// Depicts right most corner of the axis "
},
{
"code": null,
"e": 2093,
"s": 2082,
"text": "hjust = 1 "
},
{
"code": null,
"e": 2155,
"s": 2093,
"text": "Let us first create a plot with axis labels towards the left."
},
{
"code": null,
"e": 2164,
"s": 2155,
"text": "Example:"
},
{
"code": null,
"e": 2166,
"s": 2164,
"text": "R"
},
{
"code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels ggp <- perf+labs(x=\"Matches\",y=\"Runs Scored\")ggp # Moving axis label to leftggp + theme( axis.title.x = element_text(hjust=0), axis.title.y = element_text(hjust=0) )",
"e": 2632,
"s": 2166,
"text": null
},
{
"code": null,
"e": 2640,
"s": 2632,
"text": "Output:"
},
{
"code": null,
"e": 2674,
"s": 2640,
"text": "Now lets move them to the center."
},
{
"code": null,
"e": 2683,
"s": 2674,
"text": "Example:"
},
{
"code": null,
"e": 2685,
"s": 2683,
"text": "R"
},
{
"code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels ggp <- perf+labs(x=\"Matches\",y=\"Runs Scored\")ggp # Moving axis label in middleggp + theme( axis.title.x = element_text(hjust=0.5), axis.title.y = element_text(hjust=0.5))",
"e": 3155,
"s": 2685,
"text": null
},
{
"code": null,
"e": 3163,
"s": 3155,
"text": "Output:"
},
{
"code": null,
"e": 3218,
"s": 3163,
"text": "Similar can be done for moving them towards the right."
},
{
"code": null,
"e": 3227,
"s": 3218,
"text": "Example:"
},
{
"code": null,
"e": 3229,
"s": 3227,
"text": "R"
},
{
"code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10))head(ODI) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels ggp <- perf+labs(x=\"Matches\",y=\"Runs Scored\")ggp # Moving axis label to rightggp + theme( axis.title.x = element_text(hjust=1), axis.title.y = element_text(hjust=1))",
"e": 3694,
"s": 3229,
"text": null
},
{
"code": null,
"e": 3702,
"s": 3694,
"text": "Output:"
},
{
"code": null,
"e": 3709,
"s": 3702,
"text": "Picked"
},
{
"code": null,
"e": 3718,
"s": 3709,
"text": "R-ggplot"
},
{
"code": null,
"e": 3729,
"s": 3718,
"text": "R Language"
},
{
"code": null,
"e": 3827,
"s": 3729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3879,
"s": 3827,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3937,
"s": 3879,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3972,
"s": 3937,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4010,
"s": 3972,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4059,
"s": 4010,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4076,
"s": 4059,
"text": "R - if statement"
},
{
"code": null,
"e": 4113,
"s": 4076,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4156,
"s": 4113,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4193,
"s": 4156,
"text": "How to import an Excel File into R ?"
}
] |
How to Print Multiple Arguments in Python? | 29 Dec, 2020
An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition.
Example: Simple argument
Python3
def GFG(name, num): print("Hello from ", name + ', ' + num) GFG("geeks for geeks", "25")
Output:
Hello from geeks for geeks, 25
Calling the above code with no arguments or just one argument generates an error.
As shown above, functions had a fixed number of arguments. In Python, there are other ways to define a function that can take the variable number of arguments.Different forms are discussed below:
Python Default Arguments: Function arguments can have default values in Python. We provide a default value to an argument by using the assignment operator (=).
Example:
Python3
def GFG(name, num="25"): print("Hello from", name + ', ' + num) GFG("gfg")GFG("gfg", "26")
Output:
Hello from gfg, 25
Hello from gfg, 26
Pass it as a tuple
Python3
def GFG(name, num): print("hello from %s , %s" % (name, num)) GFG("gfg", "25")
Output:
hello from gfg , 25
Pass it as a dictionary
Python3
def GFG(name, num): print("hello from %(n)s , %(s)s" % {'n': name, 's': num}) GFG("gfg", "25")
Output:
hello from gfg , 25
Using new-style string formatting with number
Python3
def GFG(name, num): print("hello from {0} , {1}".format(name, num)) GFG("gfg", "25")
Output:
hello from gfg , 25
Using new-style string formatting with explicit names
Python3
def GFG(name, num): print("hello from {n} , {r}".format(n=name, r=num)) GFG("gfg", "25")
Output:
hello from gfg , 25
Concatenate strings
Python3
def GFG(name, num): print("hello from " + str(name) + " , " + str(num)) GFG("gfg", "25")
Output:
hello from gfg , 25
Using the new f-string formatting in Python 3.6
Python3
def GFG(name, num): print(f'hello from {name} , {num}') GFG("gfg", "25")
Output:
hello from gfg , 25
Using *args
Python3
def GFG(*args): for info in args: print(info) GFG(["Hello from", "geeks", 25], ["Hello", "gfg", 26])
Output:
[‘Hello from’, ‘geeks’, 25]
[‘Hello’, ‘gfg’, 26]
Using **kwargs
Python3
def GFG(**kwargs): for key, value in kwargs.items(): print(key, value) GFG(name="geeks", n="- 25")GFG(name="best", n="- 26")
Output:
name geeks
n – 25
name best
n – 26
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 300,
"s": 54,
"text": "An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition."
},
{
"code": null,
"e": 325,
"s": 300,
"text": "Example: Simple argument"
},
{
"code": null,
"e": 333,
"s": 325,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(\"Hello from \", name + ', ' + num) GFG(\"geeks for geeks\", \"25\")",
"e": 428,
"s": 333,
"text": null
},
{
"code": null,
"e": 436,
"s": 428,
"text": "Output:"
},
{
"code": null,
"e": 468,
"s": 436,
"text": "Hello from geeks for geeks, 25"
},
{
"code": null,
"e": 550,
"s": 468,
"text": "Calling the above code with no arguments or just one argument generates an error."
},
{
"code": null,
"e": 746,
"s": 550,
"text": "As shown above, functions had a fixed number of arguments. In Python, there are other ways to define a function that can take the variable number of arguments.Different forms are discussed below:"
},
{
"code": null,
"e": 906,
"s": 746,
"text": "Python Default Arguments: Function arguments can have default values in Python. We provide a default value to an argument by using the assignment operator (=)."
},
{
"code": null,
"e": 915,
"s": 906,
"text": "Example:"
},
{
"code": null,
"e": 923,
"s": 915,
"text": "Python3"
},
{
"code": "def GFG(name, num=\"25\"): print(\"Hello from\", name + ', ' + num) GFG(\"gfg\")GFG(\"gfg\", \"26\")",
"e": 1020,
"s": 923,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1020,
"text": "Output:"
},
{
"code": null,
"e": 1047,
"s": 1028,
"text": "Hello from gfg, 25"
},
{
"code": null,
"e": 1066,
"s": 1047,
"text": "Hello from gfg, 26"
},
{
"code": null,
"e": 1086,
"s": 1066,
"text": "Pass it as a tuple "
},
{
"code": null,
"e": 1094,
"s": 1086,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(\"hello from %s , %s\" % (name, num)) GFG(\"gfg\", \"25\")",
"e": 1179,
"s": 1094,
"text": null
},
{
"code": null,
"e": 1187,
"s": 1179,
"text": "Output:"
},
{
"code": null,
"e": 1207,
"s": 1187,
"text": "hello from gfg , 25"
},
{
"code": null,
"e": 1232,
"s": 1207,
"text": "Pass it as a dictionary "
},
{
"code": null,
"e": 1240,
"s": 1232,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(\"hello from %(n)s , %(s)s\" % {'n': name, 's': num}) GFG(\"gfg\", \"25\")",
"e": 1341,
"s": 1240,
"text": null
},
{
"code": null,
"e": 1349,
"s": 1341,
"text": "Output:"
},
{
"code": null,
"e": 1369,
"s": 1349,
"text": "hello from gfg , 25"
},
{
"code": null,
"e": 1416,
"s": 1369,
"text": "Using new-style string formatting with number "
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(\"hello from {0} , {1}\".format(name, num)) GFG(\"gfg\", \"25\")",
"e": 1515,
"s": 1424,
"text": null
},
{
"code": null,
"e": 1523,
"s": 1515,
"text": "Output:"
},
{
"code": null,
"e": 1543,
"s": 1523,
"text": "hello from gfg , 25"
},
{
"code": null,
"e": 1598,
"s": 1543,
"text": "Using new-style string formatting with explicit names "
},
{
"code": null,
"e": 1606,
"s": 1598,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(\"hello from {n} , {r}\".format(n=name, r=num)) GFG(\"gfg\", \"25\")",
"e": 1701,
"s": 1606,
"text": null
},
{
"code": null,
"e": 1709,
"s": 1701,
"text": "Output:"
},
{
"code": null,
"e": 1729,
"s": 1709,
"text": "hello from gfg , 25"
},
{
"code": null,
"e": 1750,
"s": 1729,
"text": "Concatenate strings "
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(\"hello from \" + str(name) + \" , \" + str(num)) GFG(\"gfg\", \"25\")",
"e": 1853,
"s": 1758,
"text": null
},
{
"code": null,
"e": 1861,
"s": 1853,
"text": "Output:"
},
{
"code": null,
"e": 1881,
"s": 1861,
"text": "hello from gfg , 25"
},
{
"code": null,
"e": 1931,
"s": 1881,
"text": " Using the new f-string formatting in Python 3.6 "
},
{
"code": null,
"e": 1939,
"s": 1931,
"text": "Python3"
},
{
"code": "def GFG(name, num): print(f'hello from {name} , {num}') GFG(\"gfg\", \"25\")",
"e": 2018,
"s": 1939,
"text": null
},
{
"code": null,
"e": 2026,
"s": 2018,
"text": "Output:"
},
{
"code": null,
"e": 2046,
"s": 2026,
"text": "hello from gfg , 25"
},
{
"code": null,
"e": 2059,
"s": 2046,
"text": "Using *args "
},
{
"code": null,
"e": 2067,
"s": 2059,
"text": "Python3"
},
{
"code": "def GFG(*args): for info in args: print(info) GFG([\"Hello from\", \"geeks\", 25], [\"Hello\", \"gfg\", 26])",
"e": 2181,
"s": 2067,
"text": null
},
{
"code": null,
"e": 2189,
"s": 2181,
"text": "Output:"
},
{
"code": null,
"e": 2217,
"s": 2189,
"text": "[‘Hello from’, ‘geeks’, 25]"
},
{
"code": null,
"e": 2238,
"s": 2217,
"text": "[‘Hello’, ‘gfg’, 26]"
},
{
"code": null,
"e": 2254,
"s": 2238,
"text": "Using **kwargs "
},
{
"code": null,
"e": 2262,
"s": 2254,
"text": "Python3"
},
{
"code": "def GFG(**kwargs): for key, value in kwargs.items(): print(key, value) GFG(name=\"geeks\", n=\"- 25\")GFG(name=\"best\", n=\"- 26\")",
"e": 2400,
"s": 2262,
"text": null
},
{
"code": null,
"e": 2408,
"s": 2400,
"text": "Output:"
},
{
"code": null,
"e": 2419,
"s": 2408,
"text": "name geeks"
},
{
"code": null,
"e": 2426,
"s": 2419,
"text": "n – 25"
},
{
"code": null,
"e": 2436,
"s": 2426,
"text": "name best"
},
{
"code": null,
"e": 2443,
"s": 2436,
"text": "n – 26"
},
{
"code": null,
"e": 2468,
"s": 2443,
"text": "Python function-programs"
},
{
"code": null,
"e": 2485,
"s": 2468,
"text": "Python-Functions"
},
{
"code": null,
"e": 2492,
"s": 2485,
"text": "Python"
},
{
"code": null,
"e": 2590,
"s": 2492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2635,
"s": 2590,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2651,
"s": 2635,
"text": "Deque in Python"
},
{
"code": null,
"e": 2673,
"s": 2651,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2689,
"s": 2673,
"text": "Queue in Python"
},
{
"code": null,
"e": 2739,
"s": 2689,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2781,
"s": 2739,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2808,
"s": 2781,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2831,
"s": 2808,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 2852,
"s": 2831,
"text": "Python OOPs Concepts"
}
] |
Minimum number of bracket reversals needed to make an expression balanced | Set - 2 - GeeksforGeeks | 21 Apr, 2021
Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. The task is to find minimum number of bracket reversals to make the expression balanced.Examples:
Input : exp = "}{"
Output : 2
We need to change '}' to '{' and '{' to
'}' so that the expression becomes balanced,
the balanced expression is '{}'
Input : exp = "}{{}}{{{"
Output : 3
The balanced expression is "{{{}}{}}"
The solution discussed in previous post requires O(n) extra space. The problem can be solved using constant space. The idea is to use two variables open and close where, open represents number of unbalanced opening brackets and close represents number of unbalanced close brackets. Traverse the string and if current character is an opening bracket increment open. If current character is a closing bracket then check if there are unbalanced opening brackets(open > 0). If yes then decrement open else increment close as this bracket is unbalanced.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string expr){ int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2) return -1; // To store number of reversals required. int ans = 0; int i; // To store number of unbalanced opening brackets. int open = 0; // To store number of unbalanced closing brackets. int close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr[i] == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (!open) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: "}{" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close) ans += 2; return ans;} // Driver Codeint main(){ string expr = "}}{{"; cout << countMinReversals(expr); return 0;}
// Java program to find minimum number of// reversals required to balance an expressionclass GFG{ // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.static int countMinReversals(String expr){ int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2 != 0) return -1; // To store number of reversals required. int ans = 0; int i; // To store number of unbalanced opening brackets. int open = 0; // To store number of unbalanced closing brackets. int close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr.charAt(i) == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (open == 0) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: "}{" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close != 0) ans += 2; return ans;} // Driver Codepublic static void main(String args[]){ String expr = "}}{{"; System.out.println(countMinReversals(expr));}} // This code is contributed by Arnab Kundu
# Python3 program to find minimum number of# reversals required to balance an expression # Returns count of minimum reversals for# making expr balanced. Returns -1 if# expr cannot be balanced.def countMinReversals(expr): length = len(expr) # length of expression must be even to # make it balanced by using reversals. if length % 2: return -1 # To store number of reversals required. ans = 0 # To store number of unbalanced # opening brackets. open = 0 # To store number of unbalanced # closing brackets. close = 0 for i in range(0, length): # If current bracket is open # then increment open count. if expr[i] == "": open += 1 # If current bracket is close, check if it # balances opening bracket. If yes then # decrement count of unbalanced opening # bracket else increment count of # closing bracket. else: if not open: close += 1 else: open -= 1 ans = (close // 2) + (open // 2) # For the case: "" or when one closing # and one opening bracket remains for # pairing, then both need to be reversed. close %= 2 open %= 2 if close > 0: ans += 2 return ans # Driver Codeif __name__ == "__main__": expr = "}}{{" print(countMinReversals(expr)) # This code is contributed by Rituraj Jain
// C# program to find minimum number of// reversals required to balance an expressionusing System; class GFG{ // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.static int countMinReversals(String expr){ int len = expr.Length; // length of expression must be even to make // it balanced by using reversals. if (len % 2 != 0) return -1; // To store number of reversals required. int ans = 0; int i; // To store number of unbalanced opening brackets. int open = 0; // To store number of unbalanced closing brackets. int close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr[i] == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (open == 0) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: "}{" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close != 0) ans += 2; return ans;} // Driver Codepublic static void Main(String []args){ String expr = "}}{{"; Console.WriteLine(countMinReversals(expr));}} // This code contributed by Rajput-Ji
<script> // Javascript program to find minimum number of// reversals required to balance an expression // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.function countMinReversals(expr){ var len = expr.length; // length of expression must be even to make // it balanced by using reversals. if (len % 2) return -1; // To store number of reversals required. var ans = 0; var i; // To store number of unbalanced opening brackets. var open = 0; // To store number of unbalanced closing brackets. var close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr[i] == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (!open) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: "}{" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close) ans += 2; return ans;} // Driver Codevar expr = "}}{{";document.write( countMinReversals(expr)); // This code is contributed by noob2000.</script>
2
Time Complexity: O(N), where N is the length of the string. Auxiliary Space: O(1)
andrew1234
rituraj_jain
Rajput-Ji
noob2000
Parentheses-Problems
Data Structures
Strings
Data Structures
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Introduction to Tree Data Structure
Hash Map in Python
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 25090,
"s": 25062,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25269,
"s": 25090,
"text": "Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. The task is to find minimum number of bracket reversals to make the expression balanced.Examples: "
},
{
"code": null,
"e": 25492,
"s": 25269,
"text": "Input : exp = \"}{\"\nOutput : 2\nWe need to change '}' to '{' and '{' to\n'}' so that the expression becomes balanced, \nthe balanced expression is '{}'\n\nInput : exp = \"}{{}}{{{\"\nOutput : 3\nThe balanced expression is \"{{{}}{}}\""
},
{
"code": null,
"e": 26091,
"s": 25494,
"text": "The solution discussed in previous post requires O(n) extra space. The problem can be solved using constant space. The idea is to use two variables open and close where, open represents number of unbalanced opening brackets and close represents number of unbalanced close brackets. Traverse the string and if current character is an opening bracket increment open. If current character is a closing bracket then check if there are unbalanced opening brackets(open > 0). If yes then decrement open else increment close as this bracket is unbalanced.Below is the implementation of above approach: "
},
{
"code": null,
"e": 26095,
"s": 26091,
"text": "C++"
},
{
"code": null,
"e": 26100,
"s": 26095,
"text": "Java"
},
{
"code": null,
"e": 26108,
"s": 26100,
"text": "Python3"
},
{
"code": null,
"e": 26111,
"s": 26108,
"text": "C#"
},
{
"code": null,
"e": 26122,
"s": 26111,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string expr){ int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2) return -1; // To store number of reversals required. int ans = 0; int i; // To store number of unbalanced opening brackets. int open = 0; // To store number of unbalanced closing brackets. int close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr[i] == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (!open) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: \"}{\" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close) ans += 2; return ans;} // Driver Codeint main(){ string expr = \"}}{{\"; cout << countMinReversals(expr); return 0;}",
"e": 27595,
"s": 26122,
"text": null
},
{
"code": "// Java program to find minimum number of// reversals required to balance an expressionclass GFG{ // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.static int countMinReversals(String expr){ int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2 != 0) return -1; // To store number of reversals required. int ans = 0; int i; // To store number of unbalanced opening brackets. int open = 0; // To store number of unbalanced closing brackets. int close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr.charAt(i) == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (open == 0) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: \"}{\" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close != 0) ans += 2; return ans;} // Driver Codepublic static void main(String args[]){ String expr = \"}}{{\"; System.out.println(countMinReversals(expr));}} // This code is contributed by Arnab Kundu",
"e": 29143,
"s": 27595,
"text": null
},
{
"code": "# Python3 program to find minimum number of# reversals required to balance an expression # Returns count of minimum reversals for# making expr balanced. Returns -1 if# expr cannot be balanced.def countMinReversals(expr): length = len(expr) # length of expression must be even to # make it balanced by using reversals. if length % 2: return -1 # To store number of reversals required. ans = 0 # To store number of unbalanced # opening brackets. open = 0 # To store number of unbalanced # closing brackets. close = 0 for i in range(0, length): # If current bracket is open # then increment open count. if expr[i] == \"\": open += 1 # If current bracket is close, check if it # balances opening bracket. If yes then # decrement count of unbalanced opening # bracket else increment count of # closing bracket. else: if not open: close += 1 else: open -= 1 ans = (close // 2) + (open // 2) # For the case: \"\" or when one closing # and one opening bracket remains for # pairing, then both need to be reversed. close %= 2 open %= 2 if close > 0: ans += 2 return ans # Driver Codeif __name__ == \"__main__\": expr = \"}}{{\" print(countMinReversals(expr)) # This code is contributed by Rituraj Jain",
"e": 30562,
"s": 29143,
"text": null
},
{
"code": "// C# program to find minimum number of// reversals required to balance an expressionusing System; class GFG{ // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.static int countMinReversals(String expr){ int len = expr.Length; // length of expression must be even to make // it balanced by using reversals. if (len % 2 != 0) return -1; // To store number of reversals required. int ans = 0; int i; // To store number of unbalanced opening brackets. int open = 0; // To store number of unbalanced closing brackets. int close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr[i] == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (open == 0) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: \"}{\" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close != 0) ans += 2; return ans;} // Driver Codepublic static void Main(String []args){ String expr = \"}}{{\"; Console.WriteLine(countMinReversals(expr));}} // This code contributed by Rajput-Ji",
"e": 32111,
"s": 30562,
"text": null
},
{
"code": "<script> // Javascript program to find minimum number of// reversals required to balance an expression // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.function countMinReversals(expr){ var len = expr.length; // length of expression must be even to make // it balanced by using reversals. if (len % 2) return -1; // To store number of reversals required. var ans = 0; var i; // To store number of unbalanced opening brackets. var open = 0; // To store number of unbalanced closing brackets. var close = 0; for (i = 0; i < len; i++) { // If current bracket is open then increment // open count. if (expr[i] == '{') open++; // If current bracket is close, check if it // balances opening bracket. If yes then // decrement count of unbalanced opening // bracket else increment count of // closing bracket. else { if (!open) close++; else open--; } } ans = (close / 2) + (open / 2); // For the case: \"}{\" or when one closing and // one opening bracket remains for pairing, then // both need to be reversed. close %= 2; open %= 2; if (close) ans += 2; return ans;} // Driver Codevar expr = \"}}{{\";document.write( countMinReversals(expr)); // This code is contributed by noob2000.</script>",
"e": 33573,
"s": 32111,
"text": null
},
{
"code": null,
"e": 33575,
"s": 33573,
"text": "2"
},
{
"code": null,
"e": 33660,
"s": 33577,
"text": "Time Complexity: O(N), where N is the length of the string. Auxiliary Space: O(1) "
},
{
"code": null,
"e": 33671,
"s": 33660,
"text": "andrew1234"
},
{
"code": null,
"e": 33684,
"s": 33671,
"text": "rituraj_jain"
},
{
"code": null,
"e": 33694,
"s": 33684,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33703,
"s": 33694,
"text": "noob2000"
},
{
"code": null,
"e": 33724,
"s": 33703,
"text": "Parentheses-Problems"
},
{
"code": null,
"e": 33740,
"s": 33724,
"text": "Data Structures"
},
{
"code": null,
"e": 33748,
"s": 33740,
"text": "Strings"
},
{
"code": null,
"e": 33764,
"s": 33748,
"text": "Data Structures"
},
{
"code": null,
"e": 33772,
"s": 33764,
"text": "Strings"
},
{
"code": null,
"e": 33870,
"s": 33772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33879,
"s": 33870,
"text": "Comments"
},
{
"code": null,
"e": 33892,
"s": 33879,
"text": "Old Comments"
},
{
"code": null,
"e": 33941,
"s": 33892,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 33966,
"s": 33941,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33993,
"s": 33966,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 34029,
"s": 33993,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 34048,
"s": 34029,
"text": "Hash Map in Python"
},
{
"code": null,
"e": 34073,
"s": 34048,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34119,
"s": 34073,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34153,
"s": 34119,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34168,
"s": 34153,
"text": "C++ Data Types"
}
] |
DateTimeOffset.AddMonths() Method in C# - GeeksforGeeks | 21 Feb, 2019
This method is used to return a new DateTimeOffset object that adds a specified number of months to the value of the current instance.
Syntax: public DateTimeOffset AddMonths (int months);Here, it takes a number of whole months. The number can be negative or positive.
Return Value: This method returns an object whose value is the sum of the date and time represented by the current DateTimeOffset object and the number of months represented by months.
Exception: This method will give ArgumentOutOfRangeException if the resulting DateTimeOffset value is less than MinValue or the resulting DateTimeOffset value is greater than MaxValue.
Below programs illustrate the use of DateTimeOffset.AddMonths(Int32) Method:
Example 1:
// C# program to demonstrate the// DateTimeOffset.AddMonths(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // adding a specified number of whole and // fractional months to the value of this // instance using AddMonths() method DateTimeOffset value = offset.AddMonths(10); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
DateTimeOffset is 04/01/2008 07:55:00 -05:00
Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// DateTimeOffset.AddMonths(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = DateTimeOffset.MaxValue; // adding a specified number of whole and // fractional months to the value of this // instance using AddMonths() method DateTimeOffset value = offset.AddMonths(10); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.ArgumentOutOfRangeException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.addmonths?view=netframework-4.7.2
CSharp-DateTimeOffset-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C# | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 25682,
"s": 25547,
"text": "This method is used to return a new DateTimeOffset object that adds a specified number of months to the value of the current instance."
},
{
"code": null,
"e": 25816,
"s": 25682,
"text": "Syntax: public DateTimeOffset AddMonths (int months);Here, it takes a number of whole months. The number can be negative or positive."
},
{
"code": null,
"e": 26001,
"s": 25816,
"text": "Return Value: This method returns an object whose value is the sum of the date and time represented by the current DateTimeOffset object and the number of months represented by months."
},
{
"code": null,
"e": 26186,
"s": 26001,
"text": "Exception: This method will give ArgumentOutOfRangeException if the resulting DateTimeOffset value is less than MinValue or the resulting DateTimeOffset value is greater than MaxValue."
},
{
"code": null,
"e": 26263,
"s": 26186,
"text": "Below programs illustrate the use of DateTimeOffset.AddMonths(Int32) Method:"
},
{
"code": null,
"e": 26274,
"s": 26263,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTimeOffset.AddMonths(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // adding a specified number of whole and // fractional months to the value of this // instance using AddMonths() method DateTimeOffset value = offset.AddMonths(10); // Display the time Console.WriteLine(\"DateTimeOffset is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 27126,
"s": 26274,
"text": null
},
{
"code": null,
"e": 27172,
"s": 27126,
"text": "DateTimeOffset is 04/01/2008 07:55:00 -05:00\n"
},
{
"code": null,
"e": 27215,
"s": 27172,
"text": "Example 2: For ArgumentOutOfRangeException"
},
{
"code": "// C# program to demonstrate the// DateTimeOffset.AddMonths(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = DateTimeOffset.MaxValue; // adding a specified number of whole and // fractional months to the value of this // instance using AddMonths() method DateTimeOffset value = offset.AddMonths(10); // Display the time Console.WriteLine(\"DateTimeOffset is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 28007,
"s": 27215,
"text": null
},
{
"code": null,
"e": 28061,
"s": 28007,
"text": "Exception Thrown: System.ArgumentOutOfRangeException\n"
},
{
"code": null,
"e": 28072,
"s": 28061,
"text": "Reference:"
},
{
"code": null,
"e": 28172,
"s": 28072,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.addmonths?view=netframework-4.7.2"
},
{
"code": null,
"e": 28201,
"s": 28172,
"text": "CSharp-DateTimeOffset-Struct"
},
{
"code": null,
"e": 28215,
"s": 28201,
"text": "CSharp-method"
},
{
"code": null,
"e": 28218,
"s": 28215,
"text": "C#"
},
{
"code": null,
"e": 28316,
"s": 28218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28339,
"s": 28316,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28367,
"s": 28339,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28389,
"s": 28367,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28406,
"s": 28389,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28435,
"s": 28406,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28475,
"s": 28435,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28498,
"s": 28475,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 28538,
"s": 28498,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28581,
"s": 28538,
"text": "C# | How to insert an element in an Array?"
}
] |
Firebase - Deploying | In this chapter, we will show you how to host your app on the Firebase server.
Before we begin, let us just add some text to index.html body tag. In this example, we will add the following text.
<h1>WELCOME TO FIREBASE TUTORIALS APP</h1>
We need to install firebase tools globally in the command prompt window.
npm install -g firebase-tools
First we need to login to Firebase in the command prompt.
firebase login
Open the root folder of your app in the command prompt and run the following command.
firebase init
This command will initialize your app.
NOTE − If you have used a default configuration, the public folder will be created and the index.html inside this folder will be the starting point of your app. You can copy your app file inside the public folder as a workaround.
This is the last step in this chapter. Run the following command from the command prompt to deploy your app.
firebase deploy
After this step, the console will log your apps Firebase URL. In our case, it is called https://tutorialsfirebase.firebaseapp.com. We can run this link in the browser to see our app.
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2245,
"s": 2166,
"text": "In this chapter, we will show you how to host your app on the Firebase server."
},
{
"code": null,
"e": 2361,
"s": 2245,
"text": "Before we begin, let us just add some text to index.html body tag. In this example, we will add the following text."
},
{
"code": null,
"e": 2404,
"s": 2361,
"text": "<h1>WELCOME TO FIREBASE TUTORIALS APP</h1>"
},
{
"code": null,
"e": 2477,
"s": 2404,
"text": "We need to install firebase tools globally in the command prompt window."
},
{
"code": null,
"e": 2508,
"s": 2477,
"text": "npm install -g firebase-tools\n"
},
{
"code": null,
"e": 2566,
"s": 2508,
"text": "First we need to login to Firebase in the command prompt."
},
{
"code": null,
"e": 2582,
"s": 2566,
"text": "firebase login\n"
},
{
"code": null,
"e": 2668,
"s": 2582,
"text": "Open the root folder of your app in the command prompt and run the following command."
},
{
"code": null,
"e": 2683,
"s": 2668,
"text": "firebase init\n"
},
{
"code": null,
"e": 2722,
"s": 2683,
"text": "This command will initialize your app."
},
{
"code": null,
"e": 2952,
"s": 2722,
"text": "NOTE − If you have used a default configuration, the public folder will be created and the index.html inside this folder will be the starting point of your app. You can copy your app file inside the public folder as a workaround."
},
{
"code": null,
"e": 3061,
"s": 2952,
"text": "This is the last step in this chapter. Run the following command from the command prompt to deploy your app."
},
{
"code": null,
"e": 3078,
"s": 3061,
"text": "firebase deploy\n"
},
{
"code": null,
"e": 3261,
"s": 3078,
"text": "After this step, the console will log your apps Firebase URL. In our case, it is called https://tutorialsfirebase.firebaseapp.com. We can run this link in the browser to see our app."
},
{
"code": null,
"e": 3294,
"s": 3261,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3311,
"s": 3294,
"text": " University Code"
},
{
"code": null,
"e": 3346,
"s": 3311,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3357,
"s": 3346,
"text": " Appeteria"
},
{
"code": null,
"e": 3393,
"s": 3357,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 3404,
"s": 3393,
"text": " Appeteria"
},
{
"code": null,
"e": 3439,
"s": 3404,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3456,
"s": 3439,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 3491,
"s": 3456,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3506,
"s": 3491,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 3542,
"s": 3506,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 3557,
"s": 3542,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 3564,
"s": 3557,
"text": " Print"
},
{
"code": null,
"e": 3575,
"s": 3564,
"text": " Add Notes"
}
] |
Algorithms | Analysis of Algorithms | Question 3 - GeeksforGeeks | 06 Feb, 2013
The recurrence relation capturing the optimal time of the Tower of Hanoi problem with n discs is. (GATE CS 2012)(A) T(n) = 2T(n – 2) + 2(B) T(n) = 2T(n – 1) + n
(C) T(n) = 2T(n/2) + 1(D) T(n) = 2T(n – 1) + 1Answer: (D)Explanation: Following are the steps to follow to solve Tower of Hanoi problem recursively.
Let the three pegs be A, B and C. The goal is to move n pegs from A to C.
To move n discs from peg A to peg C:
move n-1 discs from A to B. This leaves disc n alone on peg A
move disc n from A to C
move n?1 discs from B to C so they sit on disc n
The recurrence function T(n) for time complexity of the above recursive solution can be written as following.
T(n) = 2T(n-1) + 1
Algorithms-Analysis of Algorithms
Analysis of Algorithms
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Sorting | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
GATE | GATE MOCK 2017 | Question 23
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Sorting | Question 5
Algorithms | Bit Algorithms | Question 3
Algorithms | Sorting | Question 6 | [
{
"code": null,
"e": 25012,
"s": 24984,
"text": "\n06 Feb, 2013"
},
{
"code": null,
"e": 25173,
"s": 25012,
"text": "The recurrence relation capturing the optimal time of the Tower of Hanoi problem with n discs is. (GATE CS 2012)(A) T(n) = 2T(n – 2) + 2(B) T(n) = 2T(n – 1) + n"
},
{
"code": null,
"e": 25322,
"s": 25173,
"text": "(C) T(n) = 2T(n/2) + 1(D) T(n) = 2T(n – 1) + 1Answer: (D)Explanation: Following are the steps to follow to solve Tower of Hanoi problem recursively."
},
{
"code": null,
"e": 25580,
"s": 25322,
"text": "Let the three pegs be A, B and C. The goal is to move n pegs from A to C.\nTo move n discs from peg A to peg C:\n move n-1 discs from A to B. This leaves disc n alone on peg A\n move disc n from A to C\n move n?1 discs from B to C so they sit on disc n"
},
{
"code": null,
"e": 25690,
"s": 25580,
"text": "The recurrence function T(n) for time complexity of the above recursive solution can be written as following."
},
{
"code": null,
"e": 25709,
"s": 25690,
"text": "T(n) = 2T(n-1) + 1"
},
{
"code": null,
"e": 25743,
"s": 25709,
"text": "Algorithms-Analysis of Algorithms"
},
{
"code": null,
"e": 25766,
"s": 25743,
"text": "Analysis of Algorithms"
},
{
"code": null,
"e": 25782,
"s": 25766,
"text": "Algorithms Quiz"
},
{
"code": null,
"e": 25880,
"s": 25782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25889,
"s": 25880,
"text": "Comments"
},
{
"code": null,
"e": 25902,
"s": 25889,
"text": "Old Comments"
},
{
"code": null,
"e": 25948,
"s": 25902,
"text": "Algorithms | Dynamic Programming | Question 2"
},
{
"code": null,
"e": 25994,
"s": 25948,
"text": "Algorithms | Dynamic Programming | Question 3"
},
{
"code": null,
"e": 26028,
"s": 25994,
"text": "Algorithms | Sorting | Question 9"
},
{
"code": null,
"e": 26079,
"s": 26028,
"text": "Algorithms Quiz | Dynamic Programming | Question 8"
},
{
"code": null,
"e": 26115,
"s": 26079,
"text": "GATE | GATE MOCK 2017 | Question 23"
},
{
"code": null,
"e": 26159,
"s": 26115,
"text": "Algorithms | Graph Traversals | Question 12"
},
{
"code": null,
"e": 26202,
"s": 26159,
"text": "Algorithms | Graph Traversals | Question 1"
},
{
"code": null,
"e": 26236,
"s": 26202,
"text": "Algorithms | Sorting | Question 5"
},
{
"code": null,
"e": 26277,
"s": 26236,
"text": "Algorithms | Bit Algorithms | Question 3"
}
] |
Kotlin - Booleans | Many times we come across a situation where we need to take decision in Yes or No, or may be we can say True or False. To handle such situation Kotlin has a Boolean data type, which can take the values either true or false.
Kotlin also has a nullable counterpart Boolean? that can have the null value.
A boolean variable can be created using Boolean keyword and this variable can only take the values either true or false:
fun main(args: Array<String>) {
val isSummer: Boolean = true
val isCold: Boolean = false
println(isSummer)
println(isCold)
}
When you run the above Kotlin program, it will generate the following output:
true
false
In fact, we can create Kotlin boolean variables without using Boolean keyword and Kotlin will understand the variable type based on the assigned values either true or false
Kotlin provides following built-in operators for boolean variables. These operators are also called Logical Operators:
Following example shows different calculations using Kotlin Logical Operators:
fun main(args: Array<String>) {
var x: Boolean = true
var y:Boolean = false
println("x && y = " + (x && y))
println("x || y = " + (x || y))
println("!y = " + (!y))
}
When you run the above Kotlin program, it will generate the following output:
x && y = false
x || y = true
!y = true
A Boolean expression returns either true or false value and majorly used in checking the condition with if...else expressions. A boolean expression makes use of relational operators, for example >, <, >= etc.
fun main(args: Array<String>) {
val x: Int = 40
val y: Int = 20
println("x > y = " + (x > y))
println("x < y = " + (x < y))
println("x >= y = " + (x >= y))
println("x <= y = " + (x <= y))
println("x == y = " + (x == y))
println("x != y = " + (x != y))
}
When you run the above Kotlin program, it will generate the following output:
x > y = true
x < y = false
x >= y = true
x <= y = false
x == y = false
x != y = true
Kotlin provides and() and or() functions to perform logical AND and logical OR operations between two boolean operands.
These functions are different from && and || operators because these functions do not perform short-circuit evaluation but they always evaluate both the operands.
fun main(args: Array<String>) {
val x: Boolean = true
val y: Boolean = false
val z: Boolean = true
println("x.and(y) = " + x.and(y))
println("x.or(y) = " + x.or(y))
println("x.and(z) = " + x.and(z))
}
When you run the above Kotlin program, it will generate the following output:
x.and(y) = false
x.or(y) = true
x.and(z) = true
Kotlin also provides not() and xor() functions to perform Logical NOT and XOR operations respectively.
You can use toString() function to convert a Boolean object into its equivalent string representation.
You will need this conversion when assigning a true or false value in a String variable.
fun main(args: Array<String>) {
val x: Boolean = true
var z: String
z = x.toString()
println("x.toString() = " + x.toString())
println("z = " + z)
}
When you run the above Kotlin program, it will generate the following output:
x.toString() = true
z = true
Q 1 - Which of the following is true about Kotlin Boolean Data type?
A - Boolean data type can have two values true and false
B - Boolean data type can have two values 0 and 1
C - We can assign Boolean value to integer variable
D - All of the above
Kotlin Boolean variable can have only two values either true or false
Q 2 - What will be the output of the following program:
fun main(args: Array<String>) {
val x: Boolean = true
var y: String
y = x
}
A - This will compile successfully without error and warning
B - This will raise just a warning
C - Compilation will stop with error
D - None of the above
Compilation will stop with type mismatch error because we are trying to store a boolean value into a String variable. We should use toString() to convert Boolean value into string value before we assign it into string variable.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2649,
"s": 2425,
"text": "Many times we come across a situation where we need to take decision in Yes or No, or may be we can say True or False. To handle such situation Kotlin has a Boolean data type, which can take the values either true or false."
},
{
"code": null,
"e": 2727,
"s": 2649,
"text": "Kotlin also has a nullable counterpart Boolean? that can have the null value."
},
{
"code": null,
"e": 2848,
"s": 2727,
"text": "A boolean variable can be created using Boolean keyword and this variable can only take the values either true or false:"
},
{
"code": null,
"e": 2993,
"s": 2848,
"text": "fun main(args: Array<String>) {\n val isSummer: Boolean = true\n val isCold: Boolean = false\n \n println(isSummer)\n println(isCold)\n \n}\n"
},
{
"code": null,
"e": 3071,
"s": 2993,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3083,
"s": 3071,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 3257,
"s": 3083,
"text": "In fact, we can create Kotlin boolean variables without using Boolean keyword and Kotlin will understand the variable type based on the assigned values either true or false"
},
{
"code": null,
"e": 3376,
"s": 3257,
"text": "Kotlin provides following built-in operators for boolean variables. These operators are also called Logical Operators:"
},
{
"code": null,
"e": 3455,
"s": 3376,
"text": "Following example shows different calculations using Kotlin Logical Operators:"
},
{
"code": null,
"e": 3641,
"s": 3455,
"text": "fun main(args: Array<String>) {\n var x: Boolean = true\n var y:Boolean = false\n\n println(\"x && y = \" + (x && y))\n println(\"x || y = \" + (x || y))\n println(\"!y = \" + (!y))\n}\n"
},
{
"code": null,
"e": 3719,
"s": 3641,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3759,
"s": 3719,
"text": "x && y = false\nx || y = true\n!y = true\n"
},
{
"code": null,
"e": 3968,
"s": 3759,
"text": "A Boolean expression returns either true or false value and majorly used in checking the condition with if...else expressions. A boolean expression makes use of relational operators, for example >, <, >= etc."
},
{
"code": null,
"e": 4254,
"s": 3968,
"text": "fun main(args: Array<String>) {\n val x: Int = 40\n val y: Int = 20\n\n println(\"x > y = \" + (x > y))\n println(\"x < y = \" + (x < y))\n println(\"x >= y = \" + (x >= y))\n println(\"x <= y = \" + (x <= y))\n println(\"x == y = \" + (x == y))\n println(\"x != y = \" + (x != y))\n}\n"
},
{
"code": null,
"e": 4332,
"s": 4254,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4418,
"s": 4332,
"text": "x > y = true\nx < y = false\nx >= y = true\nx <= y = false\nx == y = false\nx != y = true\n"
},
{
"code": null,
"e": 4539,
"s": 4418,
"text": "Kotlin provides and() and or() functions to perform logical AND and logical OR operations between two boolean operands.\n"
},
{
"code": null,
"e": 4702,
"s": 4539,
"text": "These functions are different from && and || operators because these functions do not perform short-circuit evaluation but they always evaluate both the operands."
},
{
"code": null,
"e": 4926,
"s": 4702,
"text": "fun main(args: Array<String>) {\n val x: Boolean = true\n val y: Boolean = false\n val z: Boolean = true\n\n println(\"x.and(y) = \" + x.and(y))\n println(\"x.or(y) = \" + x.or(y))\n println(\"x.and(z) = \" + x.and(z))\n}\n"
},
{
"code": null,
"e": 5004,
"s": 4926,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5053,
"s": 5004,
"text": "x.and(y) = false\nx.or(y) = true\nx.and(z) = true\n"
},
{
"code": null,
"e": 5156,
"s": 5053,
"text": "Kotlin also provides not() and xor() functions to perform Logical NOT and XOR operations respectively."
},
{
"code": null,
"e": 5260,
"s": 5156,
"text": "You can use toString() function to convert a Boolean object into its equivalent string representation.\n"
},
{
"code": null,
"e": 5349,
"s": 5260,
"text": "You will need this conversion when assigning a true or false value in a String variable."
},
{
"code": null,
"e": 5521,
"s": 5349,
"text": "fun main(args: Array<String>) {\n val x: Boolean = true\n var z: String\n \n z = x.toString()\n\n println(\"x.toString() = \" + x.toString())\n println(\"z = \" + z)\n}\n"
},
{
"code": null,
"e": 5599,
"s": 5521,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5629,
"s": 5599,
"text": "x.toString() = true\nz = true\n"
},
{
"code": null,
"e": 5698,
"s": 5629,
"text": "Q 1 - Which of the following is true about Kotlin Boolean Data type?"
},
{
"code": null,
"e": 5755,
"s": 5698,
"text": "A - Boolean data type can have two values true and false"
},
{
"code": null,
"e": 5805,
"s": 5755,
"text": "B - Boolean data type can have two values 0 and 1"
},
{
"code": null,
"e": 5857,
"s": 5805,
"text": "C - We can assign Boolean value to integer variable"
},
{
"code": null,
"e": 5878,
"s": 5857,
"text": "D - All of the above"
},
{
"code": null,
"e": 5948,
"s": 5878,
"text": "Kotlin Boolean variable can have only two values either true or false"
},
{
"code": null,
"e": 6004,
"s": 5948,
"text": "Q 2 - What will be the output of the following program:"
},
{
"code": null,
"e": 6094,
"s": 6004,
"text": "fun main(args: Array<String>) {\n val x: Boolean = true\n var y: String\n \n y = x\n}\n"
},
{
"code": null,
"e": 6155,
"s": 6094,
"text": "A - This will compile successfully without error and warning"
},
{
"code": null,
"e": 6190,
"s": 6155,
"text": "B - This will raise just a warning"
},
{
"code": null,
"e": 6227,
"s": 6190,
"text": "C - Compilation will stop with error"
},
{
"code": null,
"e": 6249,
"s": 6227,
"text": "D - None of the above"
},
{
"code": null,
"e": 6477,
"s": 6249,
"text": "Compilation will stop with type mismatch error because we are trying to store a boolean value into a String variable. We should use toString() to convert Boolean value into string value before we assign it into string variable."
},
{
"code": null,
"e": 6512,
"s": 6477,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6531,
"s": 6512,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6566,
"s": 6531,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6583,
"s": 6566,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6618,
"s": 6583,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6635,
"s": 6618,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 6668,
"s": 6635,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6684,
"s": 6668,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 6719,
"s": 6684,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6739,
"s": 6719,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6772,
"s": 6739,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6789,
"s": 6772,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 6796,
"s": 6789,
"text": " Print"
},
{
"code": null,
"e": 6807,
"s": 6796,
"text": " Add Notes"
}
] |
Lolcode - Variables | As in any other programming language, LOLCODE allows you to define variables of various types. This chapter will make you familiar with working with variables in LOLCODE.
The scope of a variable is local to the function or to the program block, i.e. a variable defined in one scope cannot be called in any other scope of the same program. Variables are accessible only after they are declared.
Please note that there is no global scope of variables in LOLCODE.
Variable names are usually called identifiers. Here are some of the conventions for naming variables in LOLCODE −
Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two).
Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two).
They can only begin with a letter and then may be followed by other letters, numbers, and underscores.
They can only begin with a letter and then may be followed by other letters, numbers, and underscores.
LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable.
LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable.
Variable identifiers are case sensitive.
Variable identifiers are case sensitive.
Here are some of the rules for valid and invalid names for variables in LOLCODE−
The name should always begin with an alphabet. For example, name, Name are valid.
The name should always begin with an alphabet. For example, name, Name are valid.
The name of a variable cannot begin with a digit. For example, 2var is invalid.
The name of a variable cannot begin with a digit. For example, 2var is invalid.
The name of a variable cannot begin with a special character.
The name of a variable cannot begin with a special character.
A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name.
A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name.
Some examples of valid names in LOLCODE are shown below −
HAI 1.2
I HAS A food ITZ "111.00033"
I HAS A food2 ITZ "111"
I HAS A fo_od ITZ "1"
VISIBLE food
VISIBLE food2
VISIBLE fo_od
KTHXBYE
All the declaration statements in the above code are valid and will produce the following output when executed −
sh-4.3$ lci main.lo
111.00033
111
1
Some examples of invalid statements and their output are given below −
HAI 1.2
I HAS A 2food ITZ "111.00033"
KTHXBYE
The above code will give the following output when you execute it −
sh-4.3$ lci main.lo
Line 2: Expected: identifier; Got: int(2).
HAI 1.2
I HAS A _food ITZ "111.00033"
KTHXBYE
The above code will give the following output when you execute it −
sh-4.3$ lci main.lo
Line 2: Unrecognized sequence at: _food ITZ "111.00033".
HAI 1.2
I HAS A f$ood ITZ "111.00033"
KTHXBYE
The above code will give the following output when you execute it −
sh-4.3$ lci main.lo
Line 2: Unrecognized sequence at: $ood ITZ "111.00033".
To declare a variable, LOLCODE provides a keyword “I HAS A” which is followed by the variable name. You can find below the syntax for declaring a variable.
I HAS A VAR BTW VAR is empty now, You can use any name instead of var
To assign the variable a value in the same statement, you can then follow the variable name with “ITZ” and then give the value you want to assign. Use the following syntax to assign a value to a variable −
<variable> R <expression>
VAR R "Green" BTW VAR is now a YARN and equals "Green"
VAR R 30 BTW VAR is now a NUMBR and equals 30
You can also declare and assign variables at the same time using the following syntax−
I HAS A VAR ITZ VALUE
I HAS A NAME ITS “TUTORIALS POINT”
HAI 1.2
BTW this is how we declare variables
I HAS A food
I HAS A bird
BTW this is how we assign variables
food R 1
bird R 5
BTW this is how initialize variables
I HAS A biz ITZ "OMG!"
VISIBLE food
VISIBLE biz
VISIBLE bird
KTHXBYE
The above program shows the declaration of variables and prints them. The output is −
sh-
4.3$ lci main.lo
1
OMG!
5
To convert a value of one type to another type, we use type casting. Casting a NUMBAR to a NUMBR truncates the decimal portion of the floating point number. Casting a NUMBAR to a YARN (by printing it, for example), truncates the output to a default 2 decimal places.
HAI 1.2
I HAS A food ITZ "111.00033"
VISIBLE food
BTW this is how we do type casting
MAEK food A NUMBAR
VISIBLE food
KTHXBYE
The above line of code will produce the following output −
sh-4.3$ lci main.lo
111.00033
111.00033
All the variables declared in a LOLCODE program are local variables and there is no global scope in this language for any variable.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2011,
"s": 1840,
"text": "As in any other programming language, LOLCODE allows you to define variables of various types. This chapter will make you familiar with working with variables in LOLCODE."
},
{
"code": null,
"e": 2234,
"s": 2011,
"text": "The scope of a variable is local to the function or to the program block, i.e. a variable defined in one scope cannot be called in any other scope of the same program. Variables are accessible only after they are declared."
},
{
"code": null,
"e": 2301,
"s": 2234,
"text": "Please note that there is no global scope of variables in LOLCODE."
},
{
"code": null,
"e": 2415,
"s": 2301,
"text": "Variable names are usually called identifiers. Here are some of the conventions for naming variables in LOLCODE −"
},
{
"code": null,
"e": 2506,
"s": 2415,
"text": "Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two)."
},
{
"code": null,
"e": 2597,
"s": 2506,
"text": "Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two)."
},
{
"code": null,
"e": 2700,
"s": 2597,
"text": "They can only begin with a letter and then may be followed by other letters, numbers, and underscores."
},
{
"code": null,
"e": 2803,
"s": 2700,
"text": "They can only begin with a letter and then may be followed by other letters, numbers, and underscores."
},
{
"code": null,
"e": 2891,
"s": 2803,
"text": "LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable."
},
{
"code": null,
"e": 2979,
"s": 2891,
"text": "LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable."
},
{
"code": null,
"e": 3020,
"s": 2979,
"text": "Variable identifiers are case sensitive."
},
{
"code": null,
"e": 3061,
"s": 3020,
"text": "Variable identifiers are case sensitive."
},
{
"code": null,
"e": 3142,
"s": 3061,
"text": "Here are some of the rules for valid and invalid names for variables in LOLCODE−"
},
{
"code": null,
"e": 3224,
"s": 3142,
"text": "The name should always begin with an alphabet. For example, name, Name are valid."
},
{
"code": null,
"e": 3306,
"s": 3224,
"text": "The name should always begin with an alphabet. For example, name, Name are valid."
},
{
"code": null,
"e": 3386,
"s": 3306,
"text": "The name of a variable cannot begin with a digit. For example, 2var is invalid."
},
{
"code": null,
"e": 3466,
"s": 3386,
"text": "The name of a variable cannot begin with a digit. For example, 2var is invalid."
},
{
"code": null,
"e": 3528,
"s": 3466,
"text": "The name of a variable cannot begin with a special character."
},
{
"code": null,
"e": 3590,
"s": 3528,
"text": "The name of a variable cannot begin with a special character."
},
{
"code": null,
"e": 3720,
"s": 3590,
"text": "A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name."
},
{
"code": null,
"e": 3850,
"s": 3720,
"text": "A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name."
},
{
"code": null,
"e": 3908,
"s": 3850,
"text": "Some examples of valid names in LOLCODE are shown below −"
},
{
"code": null,
"e": 4040,
"s": 3908,
"text": "HAI 1.2\nI HAS A food ITZ \"111.00033\"\nI HAS A food2 ITZ \"111\"\nI HAS A fo_od ITZ \"1\"\nVISIBLE food\nVISIBLE food2\nVISIBLE fo_od\nKTHXBYE"
},
{
"code": null,
"e": 4153,
"s": 4040,
"text": "All the declaration statements in the above code are valid and will produce the following output when executed −"
},
{
"code": null,
"e": 4190,
"s": 4153,
"text": "sh-4.3$ lci main.lo\n111.00033\n111\n1\n"
},
{
"code": null,
"e": 4261,
"s": 4190,
"text": "Some examples of invalid statements and their output are given below −"
},
{
"code": null,
"e": 4308,
"s": 4261,
"text": "HAI 1.2\nI HAS A 2food ITZ \"111.00033\"\nKTHXBYE\n"
},
{
"code": null,
"e": 4376,
"s": 4308,
"text": "The above code will give the following output when you execute it −"
},
{
"code": null,
"e": 4440,
"s": 4376,
"text": "sh-4.3$ lci main.lo\nLine 2: Expected: identifier; Got: int(2).\n"
},
{
"code": null,
"e": 4487,
"s": 4440,
"text": "HAI 1.2\nI HAS A _food ITZ \"111.00033\"\nKTHXBYE\n"
},
{
"code": null,
"e": 4555,
"s": 4487,
"text": "The above code will give the following output when you execute it −"
},
{
"code": null,
"e": 4633,
"s": 4555,
"text": "sh-4.3$ lci main.lo\nLine 2: Unrecognized sequence at: _food ITZ \"111.00033\".\n"
},
{
"code": null,
"e": 4680,
"s": 4633,
"text": "HAI 1.2\nI HAS A f$ood ITZ \"111.00033\"\nKTHXBYE\n"
},
{
"code": null,
"e": 4748,
"s": 4680,
"text": "The above code will give the following output when you execute it −"
},
{
"code": null,
"e": 4825,
"s": 4748,
"text": "sh-4.3$ lci main.lo\nLine 2: Unrecognized sequence at: $ood ITZ \"111.00033\".\n"
},
{
"code": null,
"e": 4981,
"s": 4825,
"text": "To declare a variable, LOLCODE provides a keyword “I HAS A” which is followed by the variable name. You can find below the syntax for declaring a variable."
},
{
"code": null,
"e": 5052,
"s": 4981,
"text": "I HAS A VAR BTW VAR is empty now, You can use any name instead of var\n"
},
{
"code": null,
"e": 5258,
"s": 5052,
"text": "To assign the variable a value in the same statement, you can then follow the variable name with “ITZ” and then give the value you want to assign. Use the following syntax to assign a value to a variable −"
},
{
"code": null,
"e": 5285,
"s": 5258,
"text": "<variable> R <expression>\n"
},
{
"code": null,
"e": 5387,
"s": 5285,
"text": "VAR R \"Green\" BTW VAR is now a YARN and equals \"Green\"\nVAR R 30 BTW VAR is now a NUMBR and equals 30\n"
},
{
"code": null,
"e": 5474,
"s": 5387,
"text": "You can also declare and assign variables at the same time using the following syntax−"
},
{
"code": null,
"e": 5497,
"s": 5474,
"text": "I HAS A VAR ITZ VALUE\n"
},
{
"code": null,
"e": 5533,
"s": 5497,
"text": "I HAS A NAME ITS “TUTORIALS POINT”\n"
},
{
"code": null,
"e": 5765,
"s": 5533,
"text": "HAI 1.2\nBTW this is how we declare variables\nI HAS A food\nI HAS A bird\nBTW this is how we assign variables\nfood R 1\nbird R 5\nBTW this is how initialize variables\nI HAS A biz ITZ \"OMG!\"\nVISIBLE food\nVISIBLE biz\nVISIBLE bird\nKTHXBYE\n"
},
{
"code": null,
"e": 5851,
"s": 5765,
"text": "The above program shows the declaration of variables and prints them. The output is −"
},
{
"code": null,
"e": 5882,
"s": 5851,
"text": "sh-\n4.3$ lci main.lo\n1\nOMG!\n5\n"
},
{
"code": null,
"e": 6149,
"s": 5882,
"text": "To convert a value of one type to another type, we use type casting. Casting a NUMBAR to a NUMBR truncates the decimal portion of the floating point number. Casting a NUMBAR to a YARN (by printing it, for example), truncates the output to a default 2 decimal places."
},
{
"code": null,
"e": 6275,
"s": 6149,
"text": "HAI 1.2\nI HAS A food ITZ \"111.00033\"\nVISIBLE food\nBTW this is how we do type casting\nMAEK food A NUMBAR\nVISIBLE food\nKTHXBYE\n"
},
{
"code": null,
"e": 6334,
"s": 6275,
"text": "The above line of code will produce the following output −"
},
{
"code": null,
"e": 6375,
"s": 6334,
"text": "sh-4.3$ lci main.lo\n111.00033\n111.00033\n"
},
{
"code": null,
"e": 6507,
"s": 6375,
"text": "All the variables declared in a LOLCODE program are local variables and there is no global scope in this language for any variable."
},
{
"code": null,
"e": 6514,
"s": 6507,
"text": " Print"
},
{
"code": null,
"e": 6525,
"s": 6514,
"text": " Add Notes"
}
] |
GATE | GATE-CS-2000 | Question 49 - GeeksforGeeks | 12 Sep, 2019
Given the following expression grammar:
E -> E * F | F + E | F
F -> F - F | id
which of the following is true?(A) * has higher precedence than +(B) – has higher precedence than *(C) + and — have same precedence(D) + has higher precedence than *Answer: (B)Explanation: Let say i/p is 3*4-5 when we draw parse tree according to grammar
E
/ | \
E * F
| / | \
F F - F
| | |
id(3) id(4) id(5)
As we can see first ‘- ‘ will be evaluated then ‘ * ‘ is evaluated so ‘ – ‘ has higher precedence then *.
So correct choice is B
See question 1 of https://www.geeksforgeeks.org/compilers-set-2/Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7 | [
{
"code": null,
"e": 24456,
"s": 24428,
"text": "\n12 Sep, 2019"
},
{
"code": null,
"e": 24496,
"s": 24456,
"text": "Given the following expression grammar:"
},
{
"code": null,
"e": 24536,
"s": 24496,
"text": "E -> E * F | F + E | F\nF -> F - F | id "
},
{
"code": null,
"e": 24791,
"s": 24536,
"text": "which of the following is true?(A) * has higher precedence than +(B) – has higher precedence than *(C) + and — have same precedence(D) + has higher precedence than *Answer: (B)Explanation: Let say i/p is 3*4-5 when we draw parse tree according to grammar"
},
{
"code": null,
"e": 24884,
"s": 24791,
"text": " E\n / | \\\n E * F\n | / | \\\n F F - F\n | | |\nid(3) id(4) id(5)"
},
{
"code": null,
"e": 24990,
"s": 24884,
"text": "As we can see first ‘- ‘ will be evaluated then ‘ * ‘ is evaluated so ‘ – ‘ has higher precedence then *."
},
{
"code": null,
"e": 25013,
"s": 24990,
"text": "So correct choice is B"
},
{
"code": null,
"e": 25099,
"s": 25013,
"text": "See question 1 of https://www.geeksforgeeks.org/compilers-set-2/Quiz of this Question"
},
{
"code": null,
"e": 25112,
"s": 25099,
"text": "GATE-CS-2000"
},
{
"code": null,
"e": 25130,
"s": 25112,
"text": "GATE-GATE-CS-2000"
},
{
"code": null,
"e": 25135,
"s": 25130,
"text": "GATE"
},
{
"code": null,
"e": 25233,
"s": 25135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25267,
"s": 25233,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25309,
"s": 25267,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25351,
"s": 25309,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25385,
"s": 25351,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 25418,
"s": 25385,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25452,
"s": 25418,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25486,
"s": 25452,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 25520,
"s": 25486,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 25562,
"s": 25520,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
}
] |
Neo4j vs Grakn | Towards Data Science | Dear readers, in this series of articles I compared two popular knowledge bases: Neo4j and Grakn. I decided to write this comparison long time ago upon your requests, however kismet is for now 😊
This is a detailed comparison in 3 parts: first part is devoted to technical details, the second part dives into details of semantics and modeling. The introduction parts give quick information about how Neo4j and Grakn works, as well as some details of what those bring us new. If you already know about the first parts, you can directly dive into the semantic power part. The third part is devoted to comparison of graph algorithms, core of recommender systems and social networks. The series will continue with graph learning, chatbot NLU and more semantics with both platforms.
In this article, I will briefly compare how Neo4j way of doing is different from Grakn way of doing things. As you will follow the examples of how to create a schema, how to insert, delete and query; you will notice the paradigm difference. This part is not a battle, rather a comparison.
I know you cannot wait for the content, let the comparison begin ... here are some highlights:
Grakn is the knowledge graph, Graql is the query language notes Grakn homepage. Grakn is a knowledge graph, completely true; but the language Graql is data oriented and ontology like. Graql is declarative, one both defines data and manipulates data. We will see more on Graql in the next sections.
In my opinion Grakn is a knowledge base, Graql is an data oriented query language; all these built onto a graph data structure but you never feel the graph is there. This is how it is described in their website:
When writing Graql queries, we simply describe what information we would like to retrieve, rather than how should it be obtained. Once we specify the target information to retrieve, the Graql query processor will take care of finding an optimal way to retrieve it.
When I first met Grakn, I thought this is a knowledge modeler and still I feel the same. Best explanation of what Grakn indeed is comes from themselves:
Grakn is a database in the form of a knowledge graph, that uses an intuitive ontology to model extremely complex datasets. It stores data in a way that allows machines to understand the meaning of information in the complete context of their relationships. Consequently, Grakn allows computers to process complex information more intelligently with less human interventionGraql is a declarative, knowledge-oriented graph query language that uses machine reasoning for retrieving explicitly stored and implicitly derived knowledge from Grakn.
As I said before, even though themselves said Grakn is a database , I still raise my objections and insist that Grakn is a knowledge base 😄
Neo4j is a graph-looking knowledge graph 😄 Though in their home page I see the connected data once, one has to go through their documentation to see the semantics they actually bring:
Although they wrote only a graph database in their front page, I highly disagree. Neo4j is a knowledge graph definitely. One can see relations, classes, instances, properties i.e. the schema definition. This is semantics, that’s it. Neo4j definitely is not just a graph database, one can model the knowledge.
OK if we already can write down some OWL then, why should we use Grakn instead, one might think. Grakn explained this issue in their post in detail. For me, first plus is definitely Graql, easy to read and write. OWL is usually created by Protégé or other similar frameworks, the resulting XML is basically unreadable. Below find the same descends relationship in OWL-XML and Graql:
From the view of production, Grakn is
scalable
highly efficient
has Python, Java, Node.js clients
decently wrapped up as the whole framework
... i.e. production ready. From the view of development
queries are highly optimized
underlying data structure is flexible for semantic modeling
graph algorithms are also provided.
From the view of semantics, Grakn has more power; the data model
is easy to update/add onto
allows abstract types (we will come to this)
has a huge plus over OWL, it guarantees logical integrity. OWL has an open world assumption, whereas Grakn offers a chic combination of open world and closed world assumptions. You can read more about this at Logical Integrity section.
allows more abstraction details in general. For instance the underlying hypergraph allows n-ary relations. It’s a bit painful to model n-ary relations in OWL, there is a whole description here.
Honestly I don’t know where to start. Neo4j shines in NoSQL world with providing connected data, shines among graph databases with his superior back end and high performance. Unlike many other graph databases, Neo4j offers
fast reads and writes
high availability
horizontal scaling. Horizontal scaling is provided through 2 types of clustering: high availability clustering and causal clustering.
cache sharding
multiclustering
no joins. Data is connected via edges, complex joins is not necessary to retrieve connected/related data
granular security.
Personally I fell from my chair while reading Neo4j’s unmatched scalability skills. I highly recommend visiting the corresponding page. Warning: you may fall in love as well ❤️
From data perspective Neo4j offers
temporal data support
3D spatial data support
real-time analytics .
If you want to model a social network, build a recommendation system or model connected data for any other task; you want to manipulate temporal or spatial data, you want a scalable, high performance, secure application the choice is Neo4j. No more words here.
Getting started with Grakn is easy: first one installs the Grakn, then make a grakn server start . After, one either can work with Grakn console or Grakn workbase .
Same applies to Neo4j, download and install is provided in a very professional way. If you need, Docker configuration and framework configuration manuals are there as well. Afterwards, you can download Neo4j browser and start playing or you can discover the back end more. You can also experiment with Neo4j without downloading via their Sandbox which I really really liked. You can play around without any download hustle.
I must say I totally fell in love with Neo4j documentation as a side note, level of effort and professionalism is huge.
Both Grakn and Neo4j offers IDEs for easy use and visualization.
Grakn workbase offers 2 functionalities: visualization of your knowledge graph and an easy way to interact with your schema. You can perform match-get queries and make path queries within the workbase.
Neo4j offers their browser for 2 purposes as well: easy interaction and visualization. One can also explore patterns, clusters, and traversals in their graph.
Moreover, Neo4j offer much more for visualization Neo4j Bloom and other developer tools for visualization, mainly JS integration. With Neo4j Bloom one can discover the clusters, patterns and more.
It does not end here, Neo4j has even more visualization tools for spatial data and 3D. Neo4j is a master of spatial data in general, but visualization tools carry Neo4j to a different level:
Both platforms offer great visualization, Neo4j offers more due to being older 😄
We covered basics of the both platforms, now we can move onto development details.
For short Grakn is a hypergraph, Neo4j is a directed graph. If you are further interested how Neo4j stores his nodes, relations and attributes you can visit their developer manual or Stack overflow questions.
Data modeling is the way we know from good old OWL.
Neo4j works with knowledge graph notions: nodes (instance), labels (class), relationships, relationship types (attributes) and properties (data attributes).
Grakn style knowledge modeling is closer to ontology ways, declarative and more semantics oriented. Notions are:
entities (classes)
instances
attributes
roles
rules
type hierarchies
abstract types
If you are more onto the ontology side, Grakn way of thinking is really similar. Modeling easy, providing semantic power and efficient.
Graql is declarative and more data oriented. Neo4j’s Cypher is also declarative, however flavor is SQL. For me, Graql feels like ontology, Cypher feels like database query. Compare the following simple queries in both languages:
//CypherMATCH (p:Person { name: "Duygu" })RETURN p//Graqlmatch $p isa person, has name "Duygu";get $p;
Personally I find Graql more semantics friendly.
Creating a schema in Grakn is easy, remember Graql is declarative. Basically you open a .gql file and start creating your schema, that’s it 😄. Here is an example from their front page:
defineperson sub entity, has name, plays employee;company sub entity, has name, plays employer;employment sub relation, relates employee, relates employer;name sub attribute, datatype string;
Neo4j way of creation of entities and instances is CREATE . Once those ones are created, then one can make a MATCH query to get the corresponding nodes and create a relationship between them. One creates the nodes, edges and their attributes:
CREATE (d:Person { name:"Duygu"})CREATE (g:Company {name: "German Autolabs"})MATCH (a:Person),(b:Company)WHERE a.name = 'Duygu' AND b.name = 'German Autolabs'CREATE (a)-[r:Employed { since: '2018' }]->(b)RETURN type(r), r.name
Graql is declarative, querying is in ontology fashion again. Querying is done by match clauses. Here are some simple queries about customers of a bank:
match $p isa customer; get;match $p isa customer, has first-name "Rebecca"; get;match $p isa customer, has full-name $fn; { $fn contains "Rebecca"; } or { $fn contains "Michell"; }; get;
So far so good. Now, we can get some insights from our customers. This is a query for average debt of the Mastercard owner customers, who are younger than 25 :
match $person isa customer, has age < 25; $card isa credit-card, has type "Mastercard"; (customer: $person, credit-card: $card) isa contract, has debt $debt;get $debt; mean $debt;
Looks clean. How about Neo4j? Cypher querying is done by MATCH clause as well, but with a completely different syntax; rather a database match flavor with a WHERE. When there is a WHERE , you can play some string method games as well😄:
MATCH (customer:Customer)RETURN customerMATCH (customer:Customer)WHERE customer.first_name = 'Rebecca'RETURN customer//or equivalently with a bit syntactic sugarMATCH (customer:Customer {first_name: "Rebecca"})RETURN customer//MATCH (customer:Customer)WHERE p.first_name STARTS WITH 'Steph'RETURN p
Coming to the relations, one needs to keep an eye on the edge direction via arrows. Here is a query for the bank customers who drives an Audi; notice the DRIVES relation is directed from customer to their car:
MATCH (car:Car {brand: "Audi"})<-[:DRIVES]-(customers)RETURN customers.first_name
Aggregation is similar to SQL as well, here is the same query for the young Mastercard user customers’ debt:
MATCH (customer:Customer)-[:OWNS]->(card:CreditCard {type: "Mastercard"})WHERE customer.age < 25 RETURN AVG(card.debt)
SQL syntax applies to Cypher queries in general, if you like to write SQL then definitely you feel at home with Cypher. This is a query for finding the node with most properties:
MATCH (n)RETURN labels(n), keys(n), size(keys(n)), count(*)ORDER BY size(keys(n)) DESC
Coming back to semantics, one can query how to entities/instances related:
MATCH (:Person { name: "Oliver Stone" })-[r]->(movie)RETURN type(r) //DIRECTED
What about “joins” i.e. queries about related nodes? One usually handles such queries just as in Grakn counterpart, just a bit more instances and more relation arrows:
//Name of the movies that Charlee Sheen acted and their directorsMATCH (charlie { name: 'Charlie Sheen' })-[:ACTED_IN]->(movie)<-[:DIRECTED]-(director)RETURN movie.title, director.name
Time to time I emphasized Neo4j being a graphie graph, now let’s see it on action ... One can make path queries with Cypher, or usual semantic queries with path restrictions .
Let’s say you have a social network and you would like to find all persons who is related to Alicia in a distance of 2 and who follows who in which direction is not important:
MATCH (p1:Person)-[:FOLLOWS*1..2]-(p2:Person)WHERE p1.name = "Alicia"RETURN p1, p2
Of course shortest path is a classic in social networks, you might want to know how close Alicia and Amerie are socially linked:
MATCH p = shortestPath((p1:Person)-[*]-(p2:Person))WHERE p1.name = "Alicia" AND p2.name = 'Amerie'RETURN p
This way we look for the shortest path via any relation type. If we want we can replace [*] with [:FOLLOWS] to specify we want this relation. (There might be other relation types attending the same college, living in the same city...)
As you see Cypher offers much more than meets the eye. It is true that the syntax looks like SQL ... but story is very different, graph concepts and semantic concepts meet to fuel up Neo4j.
Semantic reasoners exist since RDF times. Inferring new relations and facts from schema knowledge and already existing data is easy for human brain, but not so straightforward for the knowledge base systems. Are we allowing open-world assumptions(if you do not know sth for sure it does not mean it is wrong, you just do not know); does world consist of what we already know (what happens then an unseen entity comes to our closed-world), how much should we infer, should we allow long paths ... Hermit was a popular choice for OWL (I used it as well) and it can be used as a plugin in Protégé.
Inference in Neo4j does not have built-in tool. Here I will introduce how Grakn tackles it.
Inference in Grakn is handled via rules . Here is how they described what a rule is:
Grakn is capable of reasoning over data via pre-defined rules. Graql rules look for a given pattern in the dataset and when found, create the given queryable relation.Graql reasoning is performed at query time and is guaranteed to be complete.
Let’s see an example of a sibling rule, if two person has same mother and father; then one can deduce they are siblings. How to express this inference in Grakn is as follows:
Grakn rule creation is intuitive: when some conditions are met, then we should infer the following fact. I found the syntax refreshing and sweet. Especially in drug discovery and any other sort of discovery tasks one needs reasoning %100. If I was involved in discovery type tasks, I would use Grakn only for this reason.
Once you create your schema and can infer new relations, after that you would like your schema to stay intact and do not allow incorrect data to get into your model. For instance, you would not want to allow a marriage relation between a person and a carpet (though person + tree is legal in some parts of the world😄).
Though Neo4j has constraints on their documentation, those are just database conventions for data validation and null checks:
Neo4j helps enforce data integrity with the use of constraints. Constraints can be applied to either nodes or relationships. Unique node property constraints can be created, as well as node and relationship property existence constraints.
Graql ensures the logical integrity via roles , each role comes from a class as you see in above examples. Again, mandatory for discovery type tasks.
Both are super scalable. I spoke a lot about Neo4j scalability above but kept Grakn way of scalability as a secret 😄 Grakn leverages Cassandra under the hood, hence Grakn is enjoys being strongly consistent, scalable and fault tolerant.
is subject of the next-next post. You will have to wait 2 more posts 😉
... looks very different, but very similar at the same time. Grakn way of things are more knowledge oriented and Neo4j feels the graph taste a bit more. Both frameworks are fascinating, then only one more question left: who is better ? Upcoming next, the great battle of semantics between Grakn and Neo4j 😉
Dear readers, we reached the end of this exhausting article but I won’t wave goodbye yet 😄 Please continue reading with the Part II and meet me for exploring the fascinating world of semantics. Until then take care and hack happily. 👋 | [
{
"code": null,
"e": 367,
"s": 172,
"text": "Dear readers, in this series of articles I compared two popular knowledge bases: Neo4j and Grakn. I decided to write this comparison long time ago upon your requests, however kismet is for now 😊"
},
{
"code": null,
"e": 949,
"s": 367,
"text": "This is a detailed comparison in 3 parts: first part is devoted to technical details, the second part dives into details of semantics and modeling. The introduction parts give quick information about how Neo4j and Grakn works, as well as some details of what those bring us new. If you already know about the first parts, you can directly dive into the semantic power part. The third part is devoted to comparison of graph algorithms, core of recommender systems and social networks. The series will continue with graph learning, chatbot NLU and more semantics with both platforms."
},
{
"code": null,
"e": 1238,
"s": 949,
"text": "In this article, I will briefly compare how Neo4j way of doing is different from Grakn way of doing things. As you will follow the examples of how to create a schema, how to insert, delete and query; you will notice the paradigm difference. This part is not a battle, rather a comparison."
},
{
"code": null,
"e": 1333,
"s": 1238,
"text": "I know you cannot wait for the content, let the comparison begin ... here are some highlights:"
},
{
"code": null,
"e": 1631,
"s": 1333,
"text": "Grakn is the knowledge graph, Graql is the query language notes Grakn homepage. Grakn is a knowledge graph, completely true; but the language Graql is data oriented and ontology like. Graql is declarative, one both defines data and manipulates data. We will see more on Graql in the next sections."
},
{
"code": null,
"e": 1843,
"s": 1631,
"text": "In my opinion Grakn is a knowledge base, Graql is an data oriented query language; all these built onto a graph data structure but you never feel the graph is there. This is how it is described in their website:"
},
{
"code": null,
"e": 2115,
"s": 1843,
"text": "When writing Graql queries, we simply describe what information we would like to retrieve, rather than how should it be obtained. Once we specify the target information to retrieve, the Graql query processor will take care of finding an optimal way to retrieve it. "
},
{
"code": null,
"e": 2268,
"s": 2115,
"text": "When I first met Grakn, I thought this is a knowledge modeler and still I feel the same. Best explanation of what Grakn indeed is comes from themselves:"
},
{
"code": null,
"e": 2813,
"s": 2268,
"text": "Grakn is a database in the form of a knowledge graph, that uses an intuitive ontology to model extremely complex datasets. It stores data in a way that allows machines to understand the meaning of information in the complete context of their relationships. Consequently, Grakn allows computers to process complex information more intelligently with less human interventionGraql is a declarative, knowledge-oriented graph query language that uses machine reasoning for retrieving explicitly stored and implicitly derived knowledge from Grakn."
},
{
"code": null,
"e": 2953,
"s": 2813,
"text": "As I said before, even though themselves said Grakn is a database , I still raise my objections and insist that Grakn is a knowledge base 😄"
},
{
"code": null,
"e": 3137,
"s": 2953,
"text": "Neo4j is a graph-looking knowledge graph 😄 Though in their home page I see the connected data once, one has to go through their documentation to see the semantics they actually bring:"
},
{
"code": null,
"e": 3446,
"s": 3137,
"text": "Although they wrote only a graph database in their front page, I highly disagree. Neo4j is a knowledge graph definitely. One can see relations, classes, instances, properties i.e. the schema definition. This is semantics, that’s it. Neo4j definitely is not just a graph database, one can model the knowledge."
},
{
"code": null,
"e": 3831,
"s": 3446,
"text": "OK if we already can write down some OWL then, why should we use Grakn instead, one might think. Grakn explained this issue in their post in detail. For me, first plus is definitely Graql, easy to read and write. OWL is usually created by Protégé or other similar frameworks, the resulting XML is basically unreadable. Below find the same descends relationship in OWL-XML and Graql:"
},
{
"code": null,
"e": 3869,
"s": 3831,
"text": "From the view of production, Grakn is"
},
{
"code": null,
"e": 3878,
"s": 3869,
"text": "scalable"
},
{
"code": null,
"e": 3895,
"s": 3878,
"text": "highly efficient"
},
{
"code": null,
"e": 3929,
"s": 3895,
"text": "has Python, Java, Node.js clients"
},
{
"code": null,
"e": 3972,
"s": 3929,
"text": "decently wrapped up as the whole framework"
},
{
"code": null,
"e": 4028,
"s": 3972,
"text": "... i.e. production ready. From the view of development"
},
{
"code": null,
"e": 4057,
"s": 4028,
"text": "queries are highly optimized"
},
{
"code": null,
"e": 4117,
"s": 4057,
"text": "underlying data structure is flexible for semantic modeling"
},
{
"code": null,
"e": 4153,
"s": 4117,
"text": "graph algorithms are also provided."
},
{
"code": null,
"e": 4218,
"s": 4153,
"text": "From the view of semantics, Grakn has more power; the data model"
},
{
"code": null,
"e": 4245,
"s": 4218,
"text": "is easy to update/add onto"
},
{
"code": null,
"e": 4290,
"s": 4245,
"text": "allows abstract types (we will come to this)"
},
{
"code": null,
"e": 4526,
"s": 4290,
"text": "has a huge plus over OWL, it guarantees logical integrity. OWL has an open world assumption, whereas Grakn offers a chic combination of open world and closed world assumptions. You can read more about this at Logical Integrity section."
},
{
"code": null,
"e": 4720,
"s": 4526,
"text": "allows more abstraction details in general. For instance the underlying hypergraph allows n-ary relations. It’s a bit painful to model n-ary relations in OWL, there is a whole description here."
},
{
"code": null,
"e": 4943,
"s": 4720,
"text": "Honestly I don’t know where to start. Neo4j shines in NoSQL world with providing connected data, shines among graph databases with his superior back end and high performance. Unlike many other graph databases, Neo4j offers"
},
{
"code": null,
"e": 4965,
"s": 4943,
"text": "fast reads and writes"
},
{
"code": null,
"e": 4983,
"s": 4965,
"text": "high availability"
},
{
"code": null,
"e": 5117,
"s": 4983,
"text": "horizontal scaling. Horizontal scaling is provided through 2 types of clustering: high availability clustering and causal clustering."
},
{
"code": null,
"e": 5132,
"s": 5117,
"text": "cache sharding"
},
{
"code": null,
"e": 5148,
"s": 5132,
"text": "multiclustering"
},
{
"code": null,
"e": 5253,
"s": 5148,
"text": "no joins. Data is connected via edges, complex joins is not necessary to retrieve connected/related data"
},
{
"code": null,
"e": 5272,
"s": 5253,
"text": "granular security."
},
{
"code": null,
"e": 5449,
"s": 5272,
"text": "Personally I fell from my chair while reading Neo4j’s unmatched scalability skills. I highly recommend visiting the corresponding page. Warning: you may fall in love as well ❤️"
},
{
"code": null,
"e": 5484,
"s": 5449,
"text": "From data perspective Neo4j offers"
},
{
"code": null,
"e": 5506,
"s": 5484,
"text": "temporal data support"
},
{
"code": null,
"e": 5530,
"s": 5506,
"text": "3D spatial data support"
},
{
"code": null,
"e": 5552,
"s": 5530,
"text": "real-time analytics ."
},
{
"code": null,
"e": 5813,
"s": 5552,
"text": "If you want to model a social network, build a recommendation system or model connected data for any other task; you want to manipulate temporal or spatial data, you want a scalable, high performance, secure application the choice is Neo4j. No more words here."
},
{
"code": null,
"e": 5978,
"s": 5813,
"text": "Getting started with Grakn is easy: first one installs the Grakn, then make a grakn server start . After, one either can work with Grakn console or Grakn workbase ."
},
{
"code": null,
"e": 6402,
"s": 5978,
"text": "Same applies to Neo4j, download and install is provided in a very professional way. If you need, Docker configuration and framework configuration manuals are there as well. Afterwards, you can download Neo4j browser and start playing or you can discover the back end more. You can also experiment with Neo4j without downloading via their Sandbox which I really really liked. You can play around without any download hustle."
},
{
"code": null,
"e": 6522,
"s": 6402,
"text": "I must say I totally fell in love with Neo4j documentation as a side note, level of effort and professionalism is huge."
},
{
"code": null,
"e": 6587,
"s": 6522,
"text": "Both Grakn and Neo4j offers IDEs for easy use and visualization."
},
{
"code": null,
"e": 6789,
"s": 6587,
"text": "Grakn workbase offers 2 functionalities: visualization of your knowledge graph and an easy way to interact with your schema. You can perform match-get queries and make path queries within the workbase."
},
{
"code": null,
"e": 6948,
"s": 6789,
"text": "Neo4j offers their browser for 2 purposes as well: easy interaction and visualization. One can also explore patterns, clusters, and traversals in their graph."
},
{
"code": null,
"e": 7145,
"s": 6948,
"text": "Moreover, Neo4j offer much more for visualization Neo4j Bloom and other developer tools for visualization, mainly JS integration. With Neo4j Bloom one can discover the clusters, patterns and more."
},
{
"code": null,
"e": 7336,
"s": 7145,
"text": "It does not end here, Neo4j has even more visualization tools for spatial data and 3D. Neo4j is a master of spatial data in general, but visualization tools carry Neo4j to a different level:"
},
{
"code": null,
"e": 7417,
"s": 7336,
"text": "Both platforms offer great visualization, Neo4j offers more due to being older 😄"
},
{
"code": null,
"e": 7500,
"s": 7417,
"text": "We covered basics of the both platforms, now we can move onto development details."
},
{
"code": null,
"e": 7709,
"s": 7500,
"text": "For short Grakn is a hypergraph, Neo4j is a directed graph. If you are further interested how Neo4j stores his nodes, relations and attributes you can visit their developer manual or Stack overflow questions."
},
{
"code": null,
"e": 7761,
"s": 7709,
"text": "Data modeling is the way we know from good old OWL."
},
{
"code": null,
"e": 7918,
"s": 7761,
"text": "Neo4j works with knowledge graph notions: nodes (instance), labels (class), relationships, relationship types (attributes) and properties (data attributes)."
},
{
"code": null,
"e": 8031,
"s": 7918,
"text": "Grakn style knowledge modeling is closer to ontology ways, declarative and more semantics oriented. Notions are:"
},
{
"code": null,
"e": 8050,
"s": 8031,
"text": "entities (classes)"
},
{
"code": null,
"e": 8060,
"s": 8050,
"text": "instances"
},
{
"code": null,
"e": 8071,
"s": 8060,
"text": "attributes"
},
{
"code": null,
"e": 8077,
"s": 8071,
"text": "roles"
},
{
"code": null,
"e": 8083,
"s": 8077,
"text": "rules"
},
{
"code": null,
"e": 8100,
"s": 8083,
"text": "type hierarchies"
},
{
"code": null,
"e": 8115,
"s": 8100,
"text": "abstract types"
},
{
"code": null,
"e": 8251,
"s": 8115,
"text": "If you are more onto the ontology side, Grakn way of thinking is really similar. Modeling easy, providing semantic power and efficient."
},
{
"code": null,
"e": 8480,
"s": 8251,
"text": "Graql is declarative and more data oriented. Neo4j’s Cypher is also declarative, however flavor is SQL. For me, Graql feels like ontology, Cypher feels like database query. Compare the following simple queries in both languages:"
},
{
"code": null,
"e": 8584,
"s": 8480,
"text": "//CypherMATCH (p:Person { name: \"Duygu\" })RETURN p//Graqlmatch $p isa person, has name \"Duygu\";get $p;"
},
{
"code": null,
"e": 8633,
"s": 8584,
"text": "Personally I find Graql more semantics friendly."
},
{
"code": null,
"e": 8818,
"s": 8633,
"text": "Creating a schema in Grakn is easy, remember Graql is declarative. Basically you open a .gql file and start creating your schema, that’s it 😄. Here is an example from their front page:"
},
{
"code": null,
"e": 9017,
"s": 8818,
"text": "defineperson sub entity, has name, plays employee;company sub entity, has name, plays employer;employment sub relation, relates employee, relates employer;name sub attribute, datatype string;"
},
{
"code": null,
"e": 9260,
"s": 9017,
"text": "Neo4j way of creation of entities and instances is CREATE . Once those ones are created, then one can make a MATCH query to get the corresponding nodes and create a relationship between them. One creates the nodes, edges and their attributes:"
},
{
"code": null,
"e": 9487,
"s": 9260,
"text": "CREATE (d:Person { name:\"Duygu\"})CREATE (g:Company {name: \"German Autolabs\"})MATCH (a:Person),(b:Company)WHERE a.name = 'Duygu' AND b.name = 'German Autolabs'CREATE (a)-[r:Employed { since: '2018' }]->(b)RETURN type(r), r.name"
},
{
"code": null,
"e": 9639,
"s": 9487,
"text": "Graql is declarative, querying is in ontology fashion again. Querying is done by match clauses. Here are some simple queries about customers of a bank:"
},
{
"code": null,
"e": 9826,
"s": 9639,
"text": "match $p isa customer; get;match $p isa customer, has first-name \"Rebecca\"; get;match $p isa customer, has full-name $fn; { $fn contains \"Rebecca\"; } or { $fn contains \"Michell\"; }; get;"
},
{
"code": null,
"e": 9986,
"s": 9826,
"text": "So far so good. Now, we can get some insights from our customers. This is a query for average debt of the Mastercard owner customers, who are younger than 25 :"
},
{
"code": null,
"e": 10169,
"s": 9986,
"text": "match $person isa customer, has age < 25; $card isa credit-card, has type \"Mastercard\"; (customer: $person, credit-card: $card) isa contract, has debt $debt;get $debt; mean $debt;"
},
{
"code": null,
"e": 10405,
"s": 10169,
"text": "Looks clean. How about Neo4j? Cypher querying is done by MATCH clause as well, but with a completely different syntax; rather a database match flavor with a WHERE. When there is a WHERE , you can play some string method games as well😄:"
},
{
"code": null,
"e": 10704,
"s": 10405,
"text": "MATCH (customer:Customer)RETURN customerMATCH (customer:Customer)WHERE customer.first_name = 'Rebecca'RETURN customer//or equivalently with a bit syntactic sugarMATCH (customer:Customer {first_name: \"Rebecca\"})RETURN customer//MATCH (customer:Customer)WHERE p.first_name STARTS WITH 'Steph'RETURN p"
},
{
"code": null,
"e": 10914,
"s": 10704,
"text": "Coming to the relations, one needs to keep an eye on the edge direction via arrows. Here is a query for the bank customers who drives an Audi; notice the DRIVES relation is directed from customer to their car:"
},
{
"code": null,
"e": 10996,
"s": 10914,
"text": "MATCH (car:Car {brand: \"Audi\"})<-[:DRIVES]-(customers)RETURN customers.first_name"
},
{
"code": null,
"e": 11105,
"s": 10996,
"text": "Aggregation is similar to SQL as well, here is the same query for the young Mastercard user customers’ debt:"
},
{
"code": null,
"e": 11224,
"s": 11105,
"text": "MATCH (customer:Customer)-[:OWNS]->(card:CreditCard {type: \"Mastercard\"})WHERE customer.age < 25 RETURN AVG(card.debt)"
},
{
"code": null,
"e": 11403,
"s": 11224,
"text": "SQL syntax applies to Cypher queries in general, if you like to write SQL then definitely you feel at home with Cypher. This is a query for finding the node with most properties:"
},
{
"code": null,
"e": 11490,
"s": 11403,
"text": "MATCH (n)RETURN labels(n), keys(n), size(keys(n)), count(*)ORDER BY size(keys(n)) DESC"
},
{
"code": null,
"e": 11565,
"s": 11490,
"text": "Coming back to semantics, one can query how to entities/instances related:"
},
{
"code": null,
"e": 11645,
"s": 11565,
"text": "MATCH (:Person { name: \"Oliver Stone\" })-[r]->(movie)RETURN type(r) //DIRECTED "
},
{
"code": null,
"e": 11813,
"s": 11645,
"text": "What about “joins” i.e. queries about related nodes? One usually handles such queries just as in Grakn counterpart, just a bit more instances and more relation arrows:"
},
{
"code": null,
"e": 11998,
"s": 11813,
"text": "//Name of the movies that Charlee Sheen acted and their directorsMATCH (charlie { name: 'Charlie Sheen' })-[:ACTED_IN]->(movie)<-[:DIRECTED]-(director)RETURN movie.title, director.name"
},
{
"code": null,
"e": 12174,
"s": 11998,
"text": "Time to time I emphasized Neo4j being a graphie graph, now let’s see it on action ... One can make path queries with Cypher, or usual semantic queries with path restrictions ."
},
{
"code": null,
"e": 12350,
"s": 12174,
"text": "Let’s say you have a social network and you would like to find all persons who is related to Alicia in a distance of 2 and who follows who in which direction is not important:"
},
{
"code": null,
"e": 12433,
"s": 12350,
"text": "MATCH (p1:Person)-[:FOLLOWS*1..2]-(p2:Person)WHERE p1.name = \"Alicia\"RETURN p1, p2"
},
{
"code": null,
"e": 12562,
"s": 12433,
"text": "Of course shortest path is a classic in social networks, you might want to know how close Alicia and Amerie are socially linked:"
},
{
"code": null,
"e": 12669,
"s": 12562,
"text": "MATCH p = shortestPath((p1:Person)-[*]-(p2:Person))WHERE p1.name = \"Alicia\" AND p2.name = 'Amerie'RETURN p"
},
{
"code": null,
"e": 12904,
"s": 12669,
"text": "This way we look for the shortest path via any relation type. If we want we can replace [*] with [:FOLLOWS] to specify we want this relation. (There might be other relation types attending the same college, living in the same city...)"
},
{
"code": null,
"e": 13094,
"s": 12904,
"text": "As you see Cypher offers much more than meets the eye. It is true that the syntax looks like SQL ... but story is very different, graph concepts and semantic concepts meet to fuel up Neo4j."
},
{
"code": null,
"e": 13691,
"s": 13094,
"text": "Semantic reasoners exist since RDF times. Inferring new relations and facts from schema knowledge and already existing data is easy for human brain, but not so straightforward for the knowledge base systems. Are we allowing open-world assumptions(if you do not know sth for sure it does not mean it is wrong, you just do not know); does world consist of what we already know (what happens then an unseen entity comes to our closed-world), how much should we infer, should we allow long paths ... Hermit was a popular choice for OWL (I used it as well) and it can be used as a plugin in Protégé."
},
{
"code": null,
"e": 13783,
"s": 13691,
"text": "Inference in Neo4j does not have built-in tool. Here I will introduce how Grakn tackles it."
},
{
"code": null,
"e": 13868,
"s": 13783,
"text": "Inference in Grakn is handled via rules . Here is how they described what a rule is:"
},
{
"code": null,
"e": 14113,
"s": 13868,
"text": "Grakn is capable of reasoning over data via pre-defined rules. Graql rules look for a given pattern in the dataset and when found, create the given queryable relation.Graql reasoning is performed at query time and is guaranteed to be complete."
},
{
"code": null,
"e": 14288,
"s": 14113,
"text": "Let’s see an example of a sibling rule, if two person has same mother and father; then one can deduce they are siblings. How to express this inference in Grakn is as follows:"
},
{
"code": null,
"e": 14610,
"s": 14288,
"text": "Grakn rule creation is intuitive: when some conditions are met, then we should infer the following fact. I found the syntax refreshing and sweet. Especially in drug discovery and any other sort of discovery tasks one needs reasoning %100. If I was involved in discovery type tasks, I would use Grakn only for this reason."
},
{
"code": null,
"e": 14929,
"s": 14610,
"text": "Once you create your schema and can infer new relations, after that you would like your schema to stay intact and do not allow incorrect data to get into your model. For instance, you would not want to allow a marriage relation between a person and a carpet (though person + tree is legal in some parts of the world😄)."
},
{
"code": null,
"e": 15055,
"s": 14929,
"text": "Though Neo4j has constraints on their documentation, those are just database conventions for data validation and null checks:"
},
{
"code": null,
"e": 15297,
"s": 15055,
"text": "Neo4j helps enforce data integrity with the use of constraints. Constraints can be applied to either nodes or relationships. Unique node property constraints can be created, as well as node and relationship property existence constraints."
},
{
"code": null,
"e": 15447,
"s": 15297,
"text": "Graql ensures the logical integrity via roles , each role comes from a class as you see in above examples. Again, mandatory for discovery type tasks."
},
{
"code": null,
"e": 15684,
"s": 15447,
"text": "Both are super scalable. I spoke a lot about Neo4j scalability above but kept Grakn way of scalability as a secret 😄 Grakn leverages Cassandra under the hood, hence Grakn is enjoys being strongly consistent, scalable and fault tolerant."
},
{
"code": null,
"e": 15755,
"s": 15684,
"text": "is subject of the next-next post. You will have to wait 2 more posts 😉"
},
{
"code": null,
"e": 16062,
"s": 15755,
"text": "... looks very different, but very similar at the same time. Grakn way of things are more knowledge oriented and Neo4j feels the graph taste a bit more. Both frameworks are fascinating, then only one more question left: who is better ? Upcoming next, the great battle of semantics between Grakn and Neo4j 😉"
}
] |
How to write an empty function in Java | Let us see how to write an empty function in Java −
Live Demo
import java.util.Vector;
public class Demo{
public static void my_empty_fun(){
}
public static void main(String[] args){
System.out.println("In the main function");
my_empty_fun();
}
}
In the main function
An empty function is basically creating a function without defining any operations inside it. A class named Demo contains an empty function named ‘my_empty_fun’ which is just completed by placing two flower brackets, without adding any functionality into it. In the main function, a print statement is written after which the empty function is called. Since there is no functionality defined for it, it does nothing. | [
{
"code": null,
"e": 1114,
"s": 1062,
"text": "Let us see how to write an empty function in Java −"
},
{
"code": null,
"e": 1125,
"s": 1114,
"text": " Live Demo"
},
{
"code": null,
"e": 1336,
"s": 1125,
"text": "import java.util.Vector;\npublic class Demo{\n public static void my_empty_fun(){\n }\n public static void main(String[] args){\n System.out.println(\"In the main function\");\n my_empty_fun();\n } \n}"
},
{
"code": null,
"e": 1357,
"s": 1336,
"text": "In the main function"
},
{
"code": null,
"e": 1774,
"s": 1357,
"text": "An empty function is basically creating a function without defining any operations inside it. A class named Demo contains an empty function named ‘my_empty_fun’ which is just completed by placing two flower brackets, without adding any functionality into it. In the main function, a print statement is written after which the empty function is called. Since there is no functionality defined for it, it does nothing."
}
] |
How to create a Expandable listView using Kotlin? | This example demonstrates how to create a Expandable listView using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<ExpandableListView
android:id="@+id/expendableList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/background_light"
android:dividerHeight="0.5dp" />
</RelativeLayout>
Step 3 − Create a new kotlin class CustomExpandableListAdapter.kt and add the following code −
import android.content.Context
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.TextView
import java.util.HashMap
class CustomExpandableListAdapter internal constructor(
private val context: Context,
private val titleList: List<String>,
private val dataList: HashMap<String, List<String>>
) : BaseExpandableListAdapter() {
override fun getChild(listPosition: Int, expandedListPosition: Int): Any {
return this.dataList[this.titleList[listPosition]]!![expandedListPosition]
}
override fun getChildId(listPosition: Int, expandedListPosition: Int): Long {
return expandedListPosition.toLong()
}
override fun getChildView(
listPosition: Int,
expandedListPosition: Int,
isLastChild: Boolean,
convertView: View?,
parent: ViewGroup
): View {
var convertView = convertView
val expandedListText = getChild(listPosition, expandedListPosition) as String
if (convertView == null) {
val layoutInflater =
this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = layoutInflater.inflate(R.layout.list_item, null)
}
val expandedListTextView = convertView!!.findViewById<TextView>(R.id.listView)
expandedListTextView.text = expandedListText
return convertView
}
override fun getChildrenCount(listPosition: Int): Int {
return this.dataList[this.titleList[listPosition]]!!.size
}
override fun getGroup(listPosition: Int): Any {
return this.titleList[listPosition]
}
override fun getGroupCount(): Int {
return this.titleList.size
}
override fun getGroupId(listPosition: Int): Long {
return listPosition.toLong()
}
override fun getGroupView(
listPosition: Int,
isExpanded: Boolean,
convertView: View?,
parent: ViewGroup
): View {
var convertView = convertView
val listTitle = getGroup(listPosition) as String
if (convertView == null) {
val layoutInflater =
this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = layoutInflater.inflate(R.layout.list_item, null)
}
val listTitleTextView = convertView!!.findViewById<TextView>(R.id.listView)
istTitleTextView.setTypeface(null, Typeface.BOLD)
listTitleTextView.text = listTitle
return convertView
}
override fun hasStableIds(): Boolean {
return false
}
override fun isChildSelectable(listPosition: Int, expandedListPosition: Int): Boolean {
return true
}
}
Step 4 − Create a new class ExpandableListData.kt and add the following code −
import java.util.*
internal object ExpandableListData {
val data: HashMap<String, List<String>>
get() {
val expandableListDetail =
HashMap<String, List<String>>()
val myFavCricketPlayers: MutableList<String> =
ArrayList()
myFavCricketPlayers.add("MS.Dhoni")
myFavCricketPlayers.add("Sehwag")
myFavCricketPlayers.add("Shane Watson")
myFavCricketPlayers.add("Ricky Ponting")
myFavCricketPlayers.add("Shahid Afridi")
val myFavFootballPlayers: MutableList<String> = ArrayList()
myFavFootballPlayers.add("Cristiano Ronaldo")
myFavFootballPlayers.add("Lionel Messi")
myFavFootballPlayers.add("Gareth Bale")
myFavFootballPlayers.add("Neymar JR")
myFavFootballPlayers.add("David de Gea")
val myFavTennisPlayers: MutableList<String> = ArrayList()
myFavTennisPlayers.add("Roger Federer")
myFavTennisPlayers.add("Rafael Nadal")
myFavTennisPlayers.add("Andy Murray")
myFavTennisPlayers.add("Novak Jokovic")
myFavTennisPlayers.add("Sania Mirza")
expandableListDetail["CRICKET PLAYERS"] = myFavCricketPlayers
expandableListDetail["FOOTBALL PLAYERS"] = myFavFootballPlayers
expandableListDetail["TENNIS PLAYERS"] = myFavTennisPlayers
return expandableListDetail
}
}
Step 5 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ExpandableListAdapter
import android.widget.ExpandableListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import app.com.q14.ExpandableListData.data
class MainActivity : AppCompatActivity() {
private var expandableListView: ExpandableListView? = null
private var adapter: ExpandableListAdapter? = null
private var titleList: List<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
expandableListView = findViewById(R.id.expendableList)
if (expandableListView != null) {
val listData = data
titleList = ArrayList(listData.keys)
adapter = CustomExpandableListAdapter(this, titleList as ArrayList<String>, listData)
expandableListView!!.setAdapter(adapter)
expandableListView!!.setOnGroupExpandListener { groupPosition ->
Toast.makeText(
applicationContext,
(titleList as ArrayList<String>)[groupPosition] + " List Expanded.",
Toast.LENGTH_SHORT
).show()
}
expandableListView!!.setOnGroupCollapseListener { groupPosition ->
Toast.makeText(
applicationContext,
(titleList as ArrayList<String>)[groupPosition] + " List Collapsed.",
Toast.LENGTH_SHORT
).show()
}
expandableListView!!.setOnChildClickListener { _, _, groupPosition, childPosition, _ ->
Toast.makeText(
applicationContext,
"Clicked: " + (titleList as ArrayList<String>)[groupPosition] + " -> " + listData[(
titleList as
ArrayList<String>
)
[groupPosition]]!!.get(
childPosition
),
Toast.LENGTH_SHORT
).show()
false
}
}
}
}
Step 6 − Create a new Layout resource (list_item.xml) and add the following code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout mlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textColor="@android:color/black" />
</LinearLayout>
Step 7 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q13">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "This example demonstrates how to create a Expandable listView using Kotlin."
},
{
"code": null,
"e": 1266,
"s": 1138,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1331,
"s": 1266,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1851,
"s": 1331,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <ExpandableListView\n android:id=\"@+id/expendableList\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:divider=\"@android:color/background_light\"\n android:dividerHeight=\"0.5dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1946,
"s": 1851,
"text": "Step 3 − Create a new kotlin class CustomExpandableListAdapter.kt and add the following code −"
},
{
"code": null,
"e": 4774,
"s": 1946,
"text": "import android.content.Context\nimport android.graphics.Typeface\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.BaseExpandableListAdapter\nimport android.widget.TextView\nimport java.util.HashMap\nclass CustomExpandableListAdapter internal constructor(\n private val context: Context,\n private val titleList: List<String>,\n private val dataList: HashMap<String, List<String>>\n ) : BaseExpandableListAdapter() {\n override fun getChild(listPosition: Int, expandedListPosition: Int): Any {\n return this.dataList[this.titleList[listPosition]]!![expandedListPosition]\n }\n override fun getChildId(listPosition: Int, expandedListPosition: Int): Long {\n return expandedListPosition.toLong()\n }\n override fun getChildView(\n listPosition: Int,\n expandedListPosition: Int,\n isLastChild: Boolean,\n convertView: View?,\n parent: ViewGroup\n ): View {\n var convertView = convertView\n val expandedListText = getChild(listPosition, expandedListPosition) as String\n if (convertView == null) {\n val layoutInflater =\n this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater\n convertView = layoutInflater.inflate(R.layout.list_item, null)\n }\n val expandedListTextView = convertView!!.findViewById<TextView>(R.id.listView)\n expandedListTextView.text = expandedListText\n return convertView\n }\n override fun getChildrenCount(listPosition: Int): Int {\n return this.dataList[this.titleList[listPosition]]!!.size\n }\n override fun getGroup(listPosition: Int): Any {\n return this.titleList[listPosition]\n }\n override fun getGroupCount(): Int {\n return this.titleList.size\n }\n override fun getGroupId(listPosition: Int): Long {\n return listPosition.toLong()\n }\n override fun getGroupView(\n listPosition: Int,\n isExpanded: Boolean,\n convertView: View?,\n parent: ViewGroup\n ): View {\n var convertView = convertView\n val listTitle = getGroup(listPosition) as String\n if (convertView == null) {\n val layoutInflater =\n this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater\n convertView = layoutInflater.inflate(R.layout.list_item, null)\n }\n val listTitleTextView = convertView!!.findViewById<TextView>(R.id.listView)\n istTitleTextView.setTypeface(null, Typeface.BOLD)\n listTitleTextView.text = listTitle\n return convertView\n }\n override fun hasStableIds(): Boolean {\n return false\n }\n override fun isChildSelectable(listPosition: Int, expandedListPosition: Int): Boolean {\n return true\n }\n}"
},
{
"code": null,
"e": 4853,
"s": 4774,
"text": "Step 4 − Create a new class ExpandableListData.kt and add the following code −"
},
{
"code": null,
"e": 6163,
"s": 4853,
"text": "import java.util.*\ninternal object ExpandableListData {\n val data: HashMap<String, List<String>>\n get() {\n val expandableListDetail =\n HashMap<String, List<String>>()\n val myFavCricketPlayers: MutableList<String> =\n ArrayList()\n myFavCricketPlayers.add(\"MS.Dhoni\")\n myFavCricketPlayers.add(\"Sehwag\")\n myFavCricketPlayers.add(\"Shane Watson\")\n myFavCricketPlayers.add(\"Ricky Ponting\")\n myFavCricketPlayers.add(\"Shahid Afridi\")\n val myFavFootballPlayers: MutableList<String> = ArrayList()\n myFavFootballPlayers.add(\"Cristiano Ronaldo\")\n myFavFootballPlayers.add(\"Lionel Messi\")\n myFavFootballPlayers.add(\"Gareth Bale\")\n myFavFootballPlayers.add(\"Neymar JR\")\n myFavFootballPlayers.add(\"David de Gea\")\n val myFavTennisPlayers: MutableList<String> = ArrayList()\n myFavTennisPlayers.add(\"Roger Federer\")\n myFavTennisPlayers.add(\"Rafael Nadal\")\n myFavTennisPlayers.add(\"Andy Murray\")\n myFavTennisPlayers.add(\"Novak Jokovic\")\n myFavTennisPlayers.add(\"Sania Mirza\")\n expandableListDetail[\"CRICKET PLAYERS\"] = myFavCricketPlayers\n expandableListDetail[\"FOOTBALL PLAYERS\"] = myFavFootballPlayers\n expandableListDetail[\"TENNIS PLAYERS\"] = myFavTennisPlayers\n return expandableListDetail\n }\n}"
},
{
"code": null,
"e": 6218,
"s": 6163,
"text": "Step 5 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 8160,
"s": 6218,
"text": "import android.os.Bundle\nimport android.widget.ExpandableListAdapter\nimport android.widget.ExpandableListView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport app.com.q14.ExpandableListData.data\nclass MainActivity : AppCompatActivity() {\n private var expandableListView: ExpandableListView? = null\n private var adapter: ExpandableListAdapter? = null\n private var titleList: List<String>? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n expandableListView = findViewById(R.id.expendableList)\n if (expandableListView != null) {\n val listData = data\n titleList = ArrayList(listData.keys)\n adapter = CustomExpandableListAdapter(this, titleList as ArrayList<String>, listData)\n expandableListView!!.setAdapter(adapter)\n expandableListView!!.setOnGroupExpandListener { groupPosition ->\n Toast.makeText(\n applicationContext,\n (titleList as ArrayList<String>)[groupPosition] + \" List Expanded.\",\n Toast.LENGTH_SHORT\n ).show()\n }\n expandableListView!!.setOnGroupCollapseListener { groupPosition ->\n Toast.makeText(\n applicationContext,\n (titleList as ArrayList<String>)[groupPosition] + \" List Collapsed.\",\n Toast.LENGTH_SHORT\n ).show()\n }\n expandableListView!!.setOnChildClickListener { _, _, groupPosition, childPosition, _ ->\n Toast.makeText(\n applicationContext,\n \"Clicked: \" + (titleList as ArrayList<String>)[groupPosition] + \" -> \" + listData[(\n titleList as\n ArrayList<String>\n )\n [groupPosition]]!!.get(\n childPosition\n ),\n Toast.LENGTH_SHORT\n ).show()\n false\n }\n }\n }\n}"
},
{
"code": null,
"e": 8242,
"s": 8160,
"text": "Step 6 − Create a new Layout resource (list_item.xml) and add the following code."
},
{
"code": null,
"e": 8813,
"s": 8242,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout mlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:paddingStart=\"?android:attr/expandableListPreferredItemPaddingLeft\"\n android:paddingTop=\"10dp\"\n android:paddingBottom=\"10dp\"\n android:textColor=\"@android:color/black\" />\n</LinearLayout>"
},
{
"code": null,
"e": 8868,
"s": 8813,
"text": "Step 7 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 9535,
"s": 8868,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q13\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9883,
"s": 9535,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Initialization of variable sized arrays in C | Variable sized arrays are data structures whose length is determined at runtime rather than compile time. These arrays are useful in simplifying numerical algorithm programming. The C99 is a C programming standard that allows variable sized arrays.
A program that demonstrates variable sized arrays in C is given as follows −
Live Demo
#include
int main(){
int n;
printf("Enter the size of the array: \n");
scanf("%d", &n);
int arr[n];
for(int i=0; i<n; i++)
arr[i] = i+1;
printf("The array elements are: ");
for(int i=0; i<n; i++)
printf("%d ", arr[i]);
return 0;
}
The output of the above program is as follows −
Enter the size of the array: 10
The array elements are: 1 2 3 4 5 6 7 8 9 10
Now let us understand the above program.
The array arr[ ] is a variable sized array in the above program as its length is determined at run time by the value provided by the user. The code snippet that shows this is as follows:
int n;
printf("Enter the size of the array: \n");
scanf("%d", &n);
int arr[n];
The array elements are initialized using a for loop and then these elements are displayed. The code snippet that shows this is as follows −
for(int i=0; i<n; i++)
arr[i] = i+1;
printf("The array elements are: ");
for(int i=0; i<n; i++)
printf("%d ", arr[i]); | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "Variable sized arrays are data structures whose length is determined at runtime rather than compile time. These arrays are useful in simplifying numerical algorithm programming. The C99 is a C programming standard that allows variable sized arrays."
},
{
"code": null,
"e": 1388,
"s": 1311,
"text": "A program that demonstrates variable sized arrays in C is given as follows −"
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": " Live Demo"
},
{
"code": null,
"e": 1667,
"s": 1399,
"text": "#include\n\nint main(){\n int n;\n\n printf(\"Enter the size of the array: \\n\");\n scanf(\"%d\", &n);\n\n int arr[n];\n\n for(int i=0; i<n; i++)\n arr[i] = i+1;\n\n printf(\"The array elements are: \");\n\n for(int i=0; i<n; i++)\n printf(\"%d \", arr[i]);\n\n return 0;\n}"
},
{
"code": null,
"e": 1715,
"s": 1667,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 1792,
"s": 1715,
"text": "Enter the size of the array: 10\nThe array elements are: 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 1833,
"s": 1792,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2020,
"s": 1833,
"text": "The array arr[ ] is a variable sized array in the above program as its length is determined at run time by the value provided by the user. The code snippet that shows this is as follows:"
},
{
"code": null,
"e": 2101,
"s": 2020,
"text": "int n;\n\nprintf(\"Enter the size of the array: \\n\");\nscanf(\"%d\", &n);\n\nint arr[n];"
},
{
"code": null,
"e": 2241,
"s": 2101,
"text": "The array elements are initialized using a for loop and then these elements are displayed. The code snippet that shows this is as follows −"
},
{
"code": null,
"e": 2362,
"s": 2241,
"text": "for(int i=0; i<n; i++)\narr[i] = i+1;\n\nprintf(\"The array elements are: \");\n\nfor(int i=0; i<n; i++)\nprintf(\"%d \", arr[i]);"
}
] |
Plotly - Dot Plots and Table | Here, we will learn about dot plots and table function in Plotly. Firstly, let us start with dot plots.
A dot plot displays points on a very simple scale. It is only suitable for a small amount of data as a large number of points will make it look very cluttered. Dot plots are also known as Cleveland dot plots. They show changes between two (or more) points in time or between two (or more) conditions.
Dot plots are similar to horizontal bar chart. However, they can be less cluttered and allow an easier comparison between conditions. The figure plots a scatter trace with mode attribute set to markers.
Following example shows comparison of literacy rate amongst men and women as recorded in each census after independence of India. Two traces in the graph represent literacy percentage of men and women in each census after 1951 up to 2011.
from plotly.offline import iplot, init_notebook_mode
init_notebook_mode(connected = True)
census = [1951,1961,1971,1981,1991,2001, 2011]
x1 = [8.86, 15.35, 21.97, 29.76, 39.29, 53.67, 64.63]
x2 = [27.15, 40.40, 45.96, 56.38,64.13, 75.26, 80.88]
traceA = go.Scatter(
x = x1,
y = census,
marker = dict(color = "crimson", size = 12),
mode = "markers",
name = "Women"
)
traceB = go.Scatter(
x = x2,
y = census,
marker = dict(color = "gold", size = 12),
mode = "markers",
name = "Men")
data = [traceA, traceB]
layout = go.Layout(
title = "Trend in Literacy rate in Post independent India",
xaxis_title = "percentage",
yaxis_title = "census"
)
fig = go.Figure(data = data, layout = layout)
iplot(fig)
The output would be as shown below −
Plotly's Table object is returned by go.Table() function. Table trace is a graph object useful for detailed data viewing in a grid of rows and columns. Table is using a column-major order, i.e. the grid is represented as a vector of column vectors.
Two important parameters of go.Table() function are header which is the first row of table and cells which form rest of rows. Both parameters are dictionary objects. The values attribute of headers is a list of column headings, and a list of lists, each corresponding to one row.
Further styling customization is done by linecolor, fill_color, font and other attributes.
Following code displays the points table of round robin stage of recently concluded Cricket World Cup 2019.
trace = go.Table(
header = dict(
values = ['Teams','Mat','Won','Lost','Tied','NR','Pts','NRR'],
line_color = 'gray',
fill_color = 'lightskyblue',
align = 'left'
),
cells = dict(
values =
[
[
'India',
'Australia',
'England',
'New Zealand',
'Pakistan',
'Sri Lanka',
'South Africa',
'Bangladesh',
'West Indies',
'Afghanistan'
],
[9,9,9,9,9,9,9,9,9,9],
[7,7,6,5,5,3,3,3,2,0],
[1,2,3,3,3,4,5,5,6,9],
[0,0,0,0,0,0,0,0,0,0],
[1,0,0,1,1,2,1,1,1,0],
[15,14,12,11,11,8,7,7,5,0],
[0.809,0.868,1.152,0.175,-0.43,-0.919,-0.03,-0.41,-0.225,-1.322]
],
line_color='gray',
fill_color='lightcyan',
align='left'
)
)
data = [trace]
fig = go.Figure(data = data)
iplot(fig)
The output is as mentioned below −
Table data can also be populated from Pandas dataframe. Let us create a comma separated file (points-table.csv) as below −
Teams,Matches,Won,Lost,Tie,NR,Points,NRR
India,9,7,1,0,1,15,0.809
Australia,9,7,2,0,0,14,0.868
England,9,6,3,0,0,12,1.152
New Zealand,9,5,3,0,1,11,0.175
Pakistan,9,5,3,0,1,11,-0.43
Sri Lanka,9,3,4,0,2,8,-0.919
South Africa,9,3,5,0,1,7,-0.03
Bangladesh,9,3,5,0,1,7,-0.41
West Indies,9,2,6,0,1,5,-0.225
Afghanistan,9,0,9,0,0,0,-1.322
We now construct a dataframe object from this csv file and use it to construct table trace as below −
import pandas as pd
df = pd.read_csv('point-table.csv')
trace = go.Table(
header = dict(values = list(df.columns)),
cells = dict(
values = [
df.Teams,
df.Matches,
df.Won,
df.Lost,
df.Tie,
df.NR,
df.Points,
df.NRR
]
)
)
data = [trace]
fig = go.Figure(data = data)
iplot(fig)
12 Lectures
53 mins
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2464,
"s": 2360,
"text": "Here, we will learn about dot plots and table function in Plotly. Firstly, let us start with dot plots."
},
{
"code": null,
"e": 2765,
"s": 2464,
"text": "A dot plot displays points on a very simple scale. It is only suitable for a small amount of data as a large number of points will make it look very cluttered. Dot plots are also known as Cleveland dot plots. They show changes between two (or more) points in time or between two (or more) conditions."
},
{
"code": null,
"e": 2968,
"s": 2765,
"text": "Dot plots are similar to horizontal bar chart. However, they can be less cluttered and allow an easier comparison between conditions. The figure plots a scatter trace with mode attribute set to markers."
},
{
"code": null,
"e": 3207,
"s": 2968,
"text": "Following example shows comparison of literacy rate amongst men and women as recorded in each census after independence of India. Two traces in the graph represent literacy percentage of men and women in each census after 1951 up to 2011."
},
{
"code": null,
"e": 3926,
"s": 3207,
"text": "from plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode(connected = True)\ncensus = [1951,1961,1971,1981,1991,2001, 2011]\nx1 = [8.86, 15.35, 21.97, 29.76, 39.29, 53.67, 64.63]\nx2 = [27.15, 40.40, 45.96, 56.38,64.13, 75.26, 80.88]\ntraceA = go.Scatter(\n x = x1,\n y = census,\n marker = dict(color = \"crimson\", size = 12),\n mode = \"markers\",\n name = \"Women\"\n)\ntraceB = go.Scatter(\nx = x2,\ny = census,\nmarker = dict(color = \"gold\", size = 12),\nmode = \"markers\",\nname = \"Men\")\ndata = [traceA, traceB]\nlayout = go.Layout(\n title = \"Trend in Literacy rate in Post independent India\",\n xaxis_title = \"percentage\",\n yaxis_title = \"census\"\n)\nfig = go.Figure(data = data, layout = layout)\niplot(fig)"
},
{
"code": null,
"e": 3963,
"s": 3926,
"text": "The output would be as shown below −"
},
{
"code": null,
"e": 4212,
"s": 3963,
"text": "Plotly's Table object is returned by go.Table() function. Table trace is a graph object useful for detailed data viewing in a grid of rows and columns. Table is using a column-major order, i.e. the grid is represented as a vector of column vectors."
},
{
"code": null,
"e": 4492,
"s": 4212,
"text": "Two important parameters of go.Table() function are header which is the first row of table and cells which form rest of rows. Both parameters are dictionary objects. The values attribute of headers is a list of column headings, and a list of lists, each corresponding to one row."
},
{
"code": null,
"e": 4583,
"s": 4492,
"text": "Further styling customization is done by linecolor, fill_color, font and other attributes."
},
{
"code": null,
"e": 4691,
"s": 4583,
"text": "Following code displays the points table of round robin stage of recently concluded Cricket World Cup 2019."
},
{
"code": null,
"e": 5617,
"s": 4691,
"text": "trace = go.Table(\n header = dict(\n values = ['Teams','Mat','Won','Lost','Tied','NR','Pts','NRR'],\n line_color = 'gray',\n fill_color = 'lightskyblue',\n align = 'left'\n ),\n cells = dict(\n values = \n [\n [\n 'India',\n 'Australia',\n 'England',\n 'New Zealand',\n 'Pakistan',\n 'Sri Lanka',\n 'South Africa',\n 'Bangladesh',\n 'West Indies',\n 'Afghanistan'\n ],\n [9,9,9,9,9,9,9,9,9,9],\n [7,7,6,5,5,3,3,3,2,0],\n [1,2,3,3,3,4,5,5,6,9],\n [0,0,0,0,0,0,0,0,0,0],\n [1,0,0,1,1,2,1,1,1,0],\n [15,14,12,11,11,8,7,7,5,0],\n [0.809,0.868,1.152,0.175,-0.43,-0.919,-0.03,-0.41,-0.225,-1.322]\n ],\n line_color='gray',\n fill_color='lightcyan',\n align='left'\n )\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)"
},
{
"code": null,
"e": 5652,
"s": 5617,
"text": "The output is as mentioned below −"
},
{
"code": null,
"e": 5775,
"s": 5652,
"text": "Table data can also be populated from Pandas dataframe. Let us create a comma separated file (points-table.csv) as below −"
},
{
"code": null,
"e": 6108,
"s": 5775,
"text": "Teams,Matches,Won,Lost,Tie,NR,Points,NRR\nIndia,9,7,1,0,1,15,0.809\nAustralia,9,7,2,0,0,14,0.868\nEngland,9,6,3,0,0,12,1.152\nNew Zealand,9,5,3,0,1,11,0.175\nPakistan,9,5,3,0,1,11,-0.43\nSri Lanka,9,3,4,0,2,8,-0.919\nSouth Africa,9,3,5,0,1,7,-0.03\nBangladesh,9,3,5,0,1,7,-0.41\nWest Indies,9,2,6,0,1,5,-0.225\nAfghanistan,9,0,9,0,0,0,-1.322\n"
},
{
"code": null,
"e": 6210,
"s": 6108,
"text": "We now construct a dataframe object from this csv file and use it to construct table trace as below −"
},
{
"code": null,
"e": 6584,
"s": 6210,
"text": "import pandas as pd\ndf = pd.read_csv('point-table.csv')\ntrace = go.Table(\n header = dict(values = list(df.columns)),\n cells = dict(\n values = [\n df.Teams, \n df.Matches, \n df.Won, \n df.Lost, \n df.Tie, \n df.NR, \n df.Points, \n df.NRR\n ]\n )\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)"
},
{
"code": null,
"e": 6616,
"s": 6584,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 6636,
"s": 6616,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6643,
"s": 6636,
"text": " Print"
},
{
"code": null,
"e": 6654,
"s": 6643,
"text": " Add Notes"
}
] |
Bool Array in C# | In a bool array, you can store true and false values. To set a bool array, use the new operator −
bool[] arr = new bool[5];
To add elements in the array −
arr[0] = true;
arr[1] = true;
arr[2] = false;
arr[3] = true;
arr[4] = true;
Let us see the complete code −
Live Demo
using System;
public class Demo {
public static void Main() {
bool[] arr = new bool[5];
arr[0] = true;
arr[1] = true;
arr[2] = false;
arr[3] = true;
arr[4] = true;
Console.WriteLine("Displaying values...");
foreach (bool res in arr) {
Console.WriteLine(res);
}
}
}
Displaying values...
True
True
False
True
True | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "In a bool array, you can store true and false values. To set a bool array, use the new operator −"
},
{
"code": null,
"e": 1186,
"s": 1160,
"text": "bool[] arr = new bool[5];"
},
{
"code": null,
"e": 1217,
"s": 1186,
"text": "To add elements in the array −"
},
{
"code": null,
"e": 1293,
"s": 1217,
"text": "arr[0] = true;\narr[1] = true;\narr[2] = false;\narr[3] = true;\narr[4] = true;"
},
{
"code": null,
"e": 1324,
"s": 1293,
"text": "Let us see the complete code −"
},
{
"code": null,
"e": 1335,
"s": 1324,
"text": " Live Demo"
},
{
"code": null,
"e": 1671,
"s": 1335,
"text": "using System;\n\npublic class Demo {\n public static void Main() {\n bool[] arr = new bool[5];\n arr[0] = true;\n arr[1] = true;\n arr[2] = false;\n arr[3] = true;\n arr[4] = true;\n Console.WriteLine(\"Displaying values...\");\n\n foreach (bool res in arr) {\n Console.WriteLine(res);\n }\n }\n}"
},
{
"code": null,
"e": 1718,
"s": 1671,
"text": "Displaying values...\nTrue\nTrue\nFalse\nTrue\nTrue"
}
] |
NativeScript - Angular Application | Let us create a simple bare bone application to understand the work flow of the NativeScript application.
Let us learn how to create simple application using NativeScript CLI, tns. tns provides a command create to used to create a new project in NativeScript.
The basic syntax to create a new application is as below −
tns create <projectname> --template <template_name>
Where,
Projectname is the Name of the project.
Projectname is the Name of the project.
template_name is Project template. NativeScript provides lot of startup template to create different type of application. Use Angular based template.
template_name is Project template. NativeScript provides lot of startup template to create different type of application. Use Angular based template.
Let us create a new directory named NativeScriptSamples to work on our new application. Now, open a new terminal then move to our directory and type the below command −
tns create BlankNgApp --template tns-template-blank-ng
Where, tns-template-blank-ng refers a blank mobile application based on AngularJS.
.....
.....
.....
Project BlankNgApp was successfully created.
Now you can navigate to your project with $ cd BlankNgApp
After that you can preview it on device by executing $ tns preview
Now, our first mobile application, BlankNgApp is created.
Let us understand the structure of the NativeScript application by analyzing our first application BlankNgApp in this chapter. NativeScript application is organized into multiple sections and they are as follows −
Configuration section
Configuration section
Node modules
Node modules
Android sources
Android sources
iOS Sources
iOS Sources
Application source code
Application source code
The general structure of the application is as follows −
│ angular.json
│ LICENSE
│ nsconfig.json
│ package-lock.json
│ package.json
│ tsconfig.json
│ tsconfig.tns.json
│ tsfmt.json
│ webpack.config.js
│
├───App_Resources
│ ├───Android
│ │
│ └───iOS
│
├───hooks
│
├───node_modules
|
└───src
│ app.css
│ main.ts
│ package.json
│
└───app
│ app-routing.module.ts
│ app.component.html
│ app.component.ts
│ app.module.ts
│
└───home
home-routing.module.ts
home.component.html
home.component.ts
home.module.ts
Let us understand each section of the application and how it helps us to create our application.
All the files in the root of the application are configuration files. The format of the configuration files are in JSON format, which helps the developer to easily understand the configuration details. NativeScript application relies on these files to gets all available configuration information. Let us go through all the configuration files in this section.
package.json files sets the identity (id) of the application and all the modules that the application depends on for its proper working. Below is our package.json −
{
"nativescript": {
"id": "org.nativescript.BlankNgApp",
"tns-android": {
"version": "6.3.1"
}, "tns-ios": {
"version": "6.3.0"
}
}, "description": "NativeScript Application",
"license": "SEE LICENSE IN <your-license-filename>",
"repository": "<fill-your-repository-here>",
"dependencies": {
"@angular/animations": "~8.2.0",
"@angular/common": "~8.2.0",
"@angular/compiler": "~8.2.0",
"@angular/core": "~8.2.0",
"@angular/forms": "~8.2.0",
"@angular/platform-browser": "~8.2.0",
"@angular/platform-browser-dynamic": "~8.2.0",
"@angular/router": "~8.2.0",
"@nativescript/theme": "~2.2.1",
"nativescript-angular": "~8.20.3",
"reflect-metadata": "~0.1.12",
"rxjs": "^6.4.0",
"tns-core-modules": "~6.3.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular/compiler-cli": "~8.2.0",
"@ngtools/webpack": "~8.2.0",
"nativescript-dev-webpack": "~1.4.0",
"typescript": "~3.5.3"
},
"gitHead": "fa98f785df3fba482e5e2a0c76f4be1fa6dc7a14",
"readme": "NativeScript Application"
}
Here,
Identity of the application (nativescript/id) − Sets the id of the application as org.nativescript.BlankNgApp. This id is used to publish our app to the Play Store or iTunes. This id will be our Application Identifier or Package Name.
Dependencies (dependencies) − Specifies all our dependent node modules. Since, the default NativeScript implementation depends on Angular Framework, Angular modules are included.
Development dependencies − Specifies all the tools that the application depends on. Since, we are developing our application in TypeScript, it includes typescript as one of the dependent modules.
angular.json − Angular framework configuration information.
nsconfig.json − NativeScript framework configuration information.
tsconfig.json, tsfmt.json & tsconfig.tns.json − TypeScript language configuration information
webpack.config.js − WebPack configuration written in JavaScript.
As NativeScript project are node based project, it stores all its dependencies in the node_modules folder. We can use npm (npm install) or tns to download and install all the application dependency into the node_moduels.
NativeScript auto-generates the android source code and place it in App_Resources\Android folder. It will be used to create android application using Android SDK
NativeScript auto-generates the iOS source code and place it in App_Resources\iOS folder. It will be used to create iOS application using iOS SDK and XCode
The actual application code is placed in src folder. Our application has below files in src folder.
└───src
│ app.css
│ main.ts
│ package.json
│
└───app
│ app-routing.module.ts
│ app.component.html
│ app.component.ts
│ app.module.ts
│
└───home
home-routing.module.ts
home.component.html
home.component.ts
home.module.ts
Let us understand the purpose of all files and how they are organized in this section −
main.ts - Entry point of the application.
// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic } from "nativescript-angular/platform";
import { AppModule } from "./app/app.module";
platformNativeScriptDynamic().bootstrapModule(AppModule);
Here, we have set the AppModule as the bootstrapping module of the application.
app.css - Main style sheet of the application is as shown below −
@import "~@nativescript/theme/css/core.css";
@import "~@nativescript/theme/css/brown.css";
/* Place any CSS rules you want to apply on both iOS and Android here.
This is where the vast majority of your CSS code goes. */
Here,
app.css imports the core style sheet and brown color themes style sheet of the NativeScript framework.
app\app.module.ts - Root module of the application.
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
@NgModule(
{
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule
],
declarations: [
AppComponent
], schemas: [
NO_ERRORS_SCHEMA
]
}
)
export class AppModule { }
Here,
AppModule is created based on NgModule and sets the components and modules of the application. It imports two modules NativeScriptModule and AppRoutingModule and a component, AppComponent. It also set the AppComponent as the root component of the application.
app.component.ts - Root component of the application.
import { Component } from "@angular/core";
@Component(
{
selector: "ns-app",
templateUrl: "app.component.html"
}
)
export class AppComponent { }
Here,
AppComponent sets the template and style sheet of the component. Template is designed in plain HMTL using NativeScript UI components.
app-routing.module.ts - Routing module for the AppModule
import { NgModule } from "@angular/core";
import { Routes } from "@angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: () =>
import("~/app/home/home.module").then((m) => m.HomeModule) }
];
@NgModule(
{
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
}
)
export class AppRoutingModule { }
Here,
AppRoutingModule uses the NativeScriptRouterModule and sets the routes of the AppModule. It basically redirects the empty path to /home and the points the /home to HomeModule.
app\home\home.module.ts - Defines a new module, HomeModule.
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { HomeRoutingModule } from "./home-routing.module";
import { HomeComponent } from "./home.component";
@NgModule(
{
imports: [
NativeScriptCommonModule,
HomeRoutingModule
],
declarations: [
HomeComponent
],
schemas: [
NO_ERRORS_SCHEMA
]
}
)
export class HomeModule { }
Here,
HomeModule imports two modules, HomeRoutingModule and NativeScriptCommonModule and one component HomeComponent
app\home\home.component.ts - Defines the Home component and used as home page of the application.
import { Component, OnInit } from "@angular/core";
@Component(
{
selector: "Home", templateUrl: "./home.component.html"
}
)
export class HomeComponent implements OnInit {
constructor() {
// Use the component constructor to inject providers.
}
ngOnInit(): void {
// Init your component properties here.
}
}
Here,
HomeComponent sets the template and selector of the home component.
app\home\home-routing.module.ts - Routing module for HomeModule and used to define routing for home module.
import { NgModule } from "@angular/core";
import { Routes } from "@angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { HomeComponent } from "./home.component";
const routes: Routes = [
{ path: "", component: HomeComponent }
];
@NgModule(
{
imports: [NativeScriptRouterModule.forChild(routes)],
exports: [NativeScriptRouterModule]
}
)
export class HomeRoutingModule { }
Here,
HomeRoutingModule set the empty path to HomeComponent.
app.component.html and home.component.html - They are used to design the UI of the application using NativeScript UI components.
If you want run your app without using any device, then type the below command −
tns preview
After executing this command, this will generate QR code to scan and connect with your device.
QRCode
Now QR code is generated and connect to PlayGround in next step.
Open NativeScript PlayGround app on your iOS or Android mobile then choose Scan QR code option. It will open the camera. Focus the QR code displayed on the console. This will scan the QR Code. Scanning the QR Code will trigger the application build and then sync the application to the device as given below −
Copying template files...
Platform android successfully added. v6.3.1
Preparing project...
File change detected. Starting incremental webpack compilation...
webpack is watching the files...
Hash: 1f38aaf6fcda4e082b88
Version: webpack 4.27.1
Time: 9333ms
Built at: 01/04/2020 4:22:31 PM
Asset Size Chunks Chunk Names
0.js 8.32 KiB 0 [emitted]
bundle.js 22.9 KiB bundle [emitted] bundle
package.json 112 bytes [emitted]
runtime.js 73 KiB runtime [emitted] runtime
tns-java-classes.js 0 bytes [emitted]
vendor.js 345 KiB vendor [emitted] vendor
Entrypoint bundle = runtime.js vendor.js bundle.js
[../$$_lazy_route_resource lazy recursive] ../$$_lazy_route_resource lazy
namespace object 160 bytes {bundle} [built] [./app.css] 1.18 KiB {bundle} [built] [./app/app-routing.module.ts] 688 bytes {bundle} [built]
[./app/app.component.html] 62 bytes {bundle} [built]
[./app/app.component.ts] 354 bytes {bundle} [built]
[./app/app.module.ts] 3.22 KiB {bundle} [built]
[./app/home/home.module.ts] 710 bytes {0} [built]
[./main.ts] 1.84 KiB {bundle} [built]
[@angular/core] external "@angular/core" 42 bytes {bundle} [built] [nativescript-angular/nativescript.module] external "nativescript-
angular/nativescript.module" 42 bytes {bundle} [built]
[nativescript-angular/platform] external "nativescript-angular/platform" 42
bytes {bundle} [built] [tns-core-modules/application] external "tns-core-
modules/application" 42 bytes {bundle} [built]
[tns-core-modules/bundle-entry-points] external "tns-core-modules/bundle-entry-points" 42
bytes {bundle} [built]
[tns-core-modules/ui/frame] external "tns-core-
modules/ui/frame" 42 bytes {bundle} [built]
[tns-core-modules/ui/frame/activity] external "tns-core-
modules/ui/frame/activity" 42 bytes {bundle} [built]
+ 15 hidden modules Webpack compilation complete. Watching for file changes.
Webpack build done!
Project successfully prepared (android)
Start sending initial files for device Bala Honor Holly (ff5e8622-7a01-4f9c-
b02f-3dc6d4ee0e1f).
Successfully sent initial files for device Bala Honor Holly (ff5e8622-7a01-4f9c-b02f-3dc6d4ee0e1f).
LOG from device Bala Honor Holly: HMR: Hot Module Replacement Enabled. Waiting for signal.
LOG from device Bala Honor Holly: Angular is running in the development mode.
Call enableProdMode() to enable the production mode.
After scanning, you should see your BlankNgApp on your device. It is shown below −
If you want to test the connected device in your application, you can verify it using the below syntax −
'tns device <Platform> --available-devices'
After that, you can execute your app using the below command −
tns run
The above command is used to build your apps locally and install on Andriod or iOS devices. If you want to run your app on an Android simulator, then type the below command −
tns run android
For iOS device, you can follow the below command −
tns run ios
This will initialize the app in an Android/iOS device. We will discuss this more in detail in the upcoming chapters.
NativeScript provides real time syncing of changes in the application to the preview application. Let us open the project using any of your favourite editor (Visual Studio Code would be the ideal choice for better visualization). Let us add some changes in our code and see how that will be detected in LiveSync.
Now open the file app.css and it will have below content −
@import "~@nativescript/theme/css/core.css";
@import "~@nativescript/theme/css/blue.css";
/* Place any CSS rules you want to apply on both iOS and Android here.
This is where the vast majority of your CSS code goes. */
Here, import statement tells the color scheme of our app. Let’s change the blue color scheme to the brown color scheme as specified below −
@import "~@nativescript/theme/css/core.css";
@import "~@nativescript/theme/css/brown.css";
/* Place any CSS rules you want to apply on both iOS and Android here.
This is where the vast majority of your CSS code goes. */
The application in our device refreshes and you should see a brown color ActionBar as shown below −
Below is the BlankNgApp Home Page - Brown Theme.
22 Lectures
1 hours
TELCOMA Global
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2211,
"s": 2105,
"text": "Let us create a simple bare bone application to understand the work flow of the NativeScript application."
},
{
"code": null,
"e": 2365,
"s": 2211,
"text": "Let us learn how to create simple application using NativeScript CLI, tns. tns provides a command create to used to create a new project in NativeScript."
},
{
"code": null,
"e": 2424,
"s": 2365,
"text": "The basic syntax to create a new application is as below −"
},
{
"code": null,
"e": 2477,
"s": 2424,
"text": "tns create <projectname> --template <template_name>\n"
},
{
"code": null,
"e": 2484,
"s": 2477,
"text": "Where,"
},
{
"code": null,
"e": 2524,
"s": 2484,
"text": "Projectname is the Name of the project."
},
{
"code": null,
"e": 2564,
"s": 2524,
"text": "Projectname is the Name of the project."
},
{
"code": null,
"e": 2714,
"s": 2564,
"text": "template_name is Project template. NativeScript provides lot of startup template to create different type of application. Use Angular based template."
},
{
"code": null,
"e": 2864,
"s": 2714,
"text": "template_name is Project template. NativeScript provides lot of startup template to create different type of application. Use Angular based template."
},
{
"code": null,
"e": 3033,
"s": 2864,
"text": "Let us create a new directory named NativeScriptSamples to work on our new application. Now, open a new terminal then move to our directory and type the below command −"
},
{
"code": null,
"e": 3089,
"s": 3033,
"text": "tns create BlankNgApp --template tns-template-blank-ng\n"
},
{
"code": null,
"e": 3172,
"s": 3089,
"text": "Where, tns-template-blank-ng refers a blank mobile application based on AngularJS."
},
{
"code": null,
"e": 3365,
"s": 3172,
"text": "..... \n..... \n..... \nProject BlankNgApp was successfully created. \nNow you can navigate to your project with $ cd BlankNgApp \nAfter that you can preview it on device by executing $ tns preview"
},
{
"code": null,
"e": 3423,
"s": 3365,
"text": "Now, our first mobile application, BlankNgApp is created."
},
{
"code": null,
"e": 3637,
"s": 3423,
"text": "Let us understand the structure of the NativeScript application by analyzing our first application BlankNgApp in this chapter. NativeScript application is organized into multiple sections and they are as follows −"
},
{
"code": null,
"e": 3659,
"s": 3637,
"text": "Configuration section"
},
{
"code": null,
"e": 3681,
"s": 3659,
"text": "Configuration section"
},
{
"code": null,
"e": 3694,
"s": 3681,
"text": "Node modules"
},
{
"code": null,
"e": 3707,
"s": 3694,
"text": "Node modules"
},
{
"code": null,
"e": 3723,
"s": 3707,
"text": "Android sources"
},
{
"code": null,
"e": 3739,
"s": 3723,
"text": "Android sources"
},
{
"code": null,
"e": 3751,
"s": 3739,
"text": "iOS Sources"
},
{
"code": null,
"e": 3763,
"s": 3751,
"text": "iOS Sources"
},
{
"code": null,
"e": 3787,
"s": 3763,
"text": "Application source code"
},
{
"code": null,
"e": 3811,
"s": 3787,
"text": "Application source code"
},
{
"code": null,
"e": 3868,
"s": 3811,
"text": "The general structure of the application is as follows −"
},
{
"code": null,
"e": 4442,
"s": 3868,
"text": "│ angular.json \n│ LICENSE \n│ nsconfig.json \n│ package-lock.json \n│ package.json \n│ tsconfig.json \n│ tsconfig.tns.json \n│ tsfmt.json \n│ webpack.config.js \n│\n├───App_Resources \n│ ├───Android \n│ │ \n│ └───iOS \n│ \n├───hooks \n│ \n├───node_modules \n| \n└───src \n │ app.css \n │ main.ts \n │ package.json \n │ \n └───app \n │ app-routing.module.ts \n │ app.component.html \n │ app.component.ts \n │ app.module.ts \n │ \n └───home \n home-routing.module.ts \n home.component.html \n home.component.ts \n home.module.ts\n"
},
{
"code": null,
"e": 4539,
"s": 4442,
"text": "Let us understand each section of the application and how it helps us to create our application."
},
{
"code": null,
"e": 4900,
"s": 4539,
"text": "All the files in the root of the application are configuration files. The format of the configuration files are in JSON format, which helps the developer to easily understand the configuration details. NativeScript application relies on these files to gets all available configuration information. Let us go through all the configuration files in this section."
},
{
"code": null,
"e": 5065,
"s": 4900,
"text": "package.json files sets the identity (id) of the application and all the modules that the application depends on for its proper working. Below is our package.json −"
},
{
"code": null,
"e": 6243,
"s": 5065,
"text": "{ \n \"nativescript\": {\n \"id\": \"org.nativescript.BlankNgApp\",\n \"tns-android\": {\n \"version\": \"6.3.1\"\n }, \"tns-ios\": {\n \"version\": \"6.3.0\"\n } \n }, \"description\": \"NativeScript Application\", \n \"license\": \"SEE LICENSE IN <your-license-filename>\", \n \"repository\": \"<fill-your-repository-here>\", \n \"dependencies\": { \n \"@angular/animations\": \"~8.2.0\", \n \"@angular/common\": \"~8.2.0\", \n \"@angular/compiler\": \"~8.2.0\", \n \"@angular/core\": \"~8.2.0\", \n \"@angular/forms\": \"~8.2.0\", \n \"@angular/platform-browser\": \"~8.2.0\", \n \"@angular/platform-browser-dynamic\": \"~8.2.0\", \n \"@angular/router\": \"~8.2.0\", \n \"@nativescript/theme\": \"~2.2.1\", \n \"nativescript-angular\": \"~8.20.3\", \n \"reflect-metadata\": \"~0.1.12\", \n \"rxjs\": \"^6.4.0\", \n \"tns-core-modules\": \"~6.3.0\", \n \"zone.js\": \"~0.9.1\" \n }, \n \"devDependencies\": { \n \"@angular/compiler-cli\": \"~8.2.0\", \n \"@ngtools/webpack\": \"~8.2.0\", \n \"nativescript-dev-webpack\": \"~1.4.0\", \n \"typescript\": \"~3.5.3\" \n }, \n \"gitHead\": \"fa98f785df3fba482e5e2a0c76f4be1fa6dc7a14\", \n \"readme\": \"NativeScript Application\" \n}"
},
{
"code": null,
"e": 6249,
"s": 6243,
"text": "Here,"
},
{
"code": null,
"e": 6484,
"s": 6249,
"text": "Identity of the application (nativescript/id) − Sets the id of the application as org.nativescript.BlankNgApp. This id is used to publish our app to the Play Store or iTunes. This id will be our Application Identifier or Package Name."
},
{
"code": null,
"e": 6663,
"s": 6484,
"text": "Dependencies (dependencies) − Specifies all our dependent node modules. Since, the default NativeScript implementation depends on Angular Framework, Angular modules are included."
},
{
"code": null,
"e": 6859,
"s": 6663,
"text": "Development dependencies − Specifies all the tools that the application depends on. Since, we are developing our application in TypeScript, it includes typescript as one of the dependent modules."
},
{
"code": null,
"e": 6919,
"s": 6859,
"text": "angular.json − Angular framework configuration information."
},
{
"code": null,
"e": 6985,
"s": 6919,
"text": "nsconfig.json − NativeScript framework configuration information."
},
{
"code": null,
"e": 7080,
"s": 6985,
"text": "tsconfig.json, tsfmt.json & tsconfig.tns.json − TypeScript language configuration information"
},
{
"code": null,
"e": 7145,
"s": 7080,
"text": "webpack.config.js − WebPack configuration written in JavaScript."
},
{
"code": null,
"e": 7366,
"s": 7145,
"text": "As NativeScript project are node based project, it stores all its dependencies in the node_modules folder. We can use npm (npm install) or tns to download and install all the application dependency into the node_moduels."
},
{
"code": null,
"e": 7528,
"s": 7366,
"text": "NativeScript auto-generates the android source code and place it in App_Resources\\Android folder. It will be used to create android application using Android SDK"
},
{
"code": null,
"e": 7684,
"s": 7528,
"text": "NativeScript auto-generates the iOS source code and place it in App_Resources\\iOS folder. It will be used to create iOS application using iOS SDK and XCode"
},
{
"code": null,
"e": 7784,
"s": 7684,
"text": "The actual application code is placed in src folder. Our application has below files in src folder."
},
{
"code": null,
"e": 8090,
"s": 7784,
"text": "└───src \n │ app.css \n │ main.ts \n │ package.json \n │ \n └───app \n │ app-routing.module.ts \n │ app.component.html \n │ app.component.ts \n │ app.module.ts \n │ \n └───home \n home-routing.module.ts \n home.component.html \n home.component.ts \n home.module.ts\n\n"
},
{
"code": null,
"e": 8178,
"s": 8090,
"text": "Let us understand the purpose of all files and how they are organized in this section −"
},
{
"code": null,
"e": 8220,
"s": 8178,
"text": "main.ts - Entry point of the application."
},
{
"code": null,
"e": 8510,
"s": 8220,
"text": "// this import should be first in order to load some required settings (like globals and reflect-metadata) \nimport { platformNativeScriptDynamic } from \"nativescript-angular/platform\";\nimport { AppModule } from \"./app/app.module\"; \nplatformNativeScriptDynamic().bootstrapModule(AppModule);"
},
{
"code": null,
"e": 8590,
"s": 8510,
"text": "Here, we have set the AppModule as the bootstrapping module of the application."
},
{
"code": null,
"e": 8656,
"s": 8590,
"text": "app.css - Main style sheet of the application is as shown below −"
},
{
"code": null,
"e": 8879,
"s": 8656,
"text": "@import \"~@nativescript/theme/css/core.css\"; \n@import \"~@nativescript/theme/css/brown.css\"; \n/* Place any CSS rules you want to apply on both iOS and Android here. \nThis is where the vast majority of your CSS code goes. */"
},
{
"code": null,
"e": 8885,
"s": 8879,
"text": "Here,"
},
{
"code": null,
"e": 8988,
"s": 8885,
"text": "app.css imports the core style sheet and brown color themes style sheet of the NativeScript framework."
},
{
"code": null,
"e": 9040,
"s": 8988,
"text": "app\\app.module.ts - Root module of the application."
},
{
"code": null,
"e": 9565,
"s": 9040,
"text": "import { NgModule, NO_ERRORS_SCHEMA } from \"@angular/core\";\nimport { NativeScriptModule } from \"nativescript-angular/nativescript.module\";\nimport { AppRoutingModule } from \"./app-routing.module\";\nimport { AppComponent } from \"./app.component\";\n@NgModule(\n {\n bootstrap: [\n AppComponent\n ], \n imports: [\n NativeScriptModule,\n AppRoutingModule\n ], \n declarations: [\n AppComponent\n ], schemas: [\n NO_ERRORS_SCHEMA\n ]\n }\n)\nexport class AppModule { }"
},
{
"code": null,
"e": 9571,
"s": 9565,
"text": "Here,"
},
{
"code": null,
"e": 9831,
"s": 9571,
"text": "AppModule is created based on NgModule and sets the components and modules of the application. It imports two modules NativeScriptModule and AppRoutingModule and a component, AppComponent. It also set the AppComponent as the root component of the application."
},
{
"code": null,
"e": 9885,
"s": 9831,
"text": "app.component.ts - Root component of the application."
},
{
"code": null,
"e": 10053,
"s": 9885,
"text": "import { Component } from \"@angular/core\"; \n@Component(\n { \n selector: \"ns-app\", \n templateUrl: \"app.component.html\" \n }\n) \nexport class AppComponent { }"
},
{
"code": null,
"e": 10059,
"s": 10053,
"text": "Here,"
},
{
"code": null,
"e": 10193,
"s": 10059,
"text": "AppComponent sets the template and style sheet of the component. Template is designed in plain HMTL using NativeScript UI components."
},
{
"code": null,
"e": 10250,
"s": 10193,
"text": "app-routing.module.ts - Routing module for the AppModule"
},
{
"code": null,
"e": 10758,
"s": 10250,
"text": "import { NgModule } from \"@angular/core\"; \nimport { Routes } from \"@angular/router\"; \nimport { NativeScriptRouterModule } from \"nativescript-angular/router\"; \nconst routes: Routes = [\n { path: \"\", redirectTo: \"/home\", pathMatch: \"full\" },\n { path: \"home\", loadChildren: () =>\n import(\"~/app/home/home.module\").then((m) => m.HomeModule) } \n];\n@NgModule(\n {\n imports: [NativeScriptRouterModule.forRoot(routes)], \n exports: [NativeScriptRouterModule] \n }\n)\nexport class AppRoutingModule { }"
},
{
"code": null,
"e": 10764,
"s": 10758,
"text": "Here,"
},
{
"code": null,
"e": 10940,
"s": 10764,
"text": "AppRoutingModule uses the NativeScriptRouterModule and sets the routes of the AppModule. It basically redirects the empty path to /home and the points the /home to HomeModule."
},
{
"code": null,
"e": 11000,
"s": 10940,
"text": "app\\home\\home.module.ts - Defines a new module, HomeModule."
},
{
"code": null,
"e": 11485,
"s": 11000,
"text": "import { NgModule, NO_ERRORS_SCHEMA } from \"@angular/core\";\nimport { NativeScriptCommonModule } from \"nativescript-angular/common\";\nimport { HomeRoutingModule } from \"./home-routing.module\";\nimport { HomeComponent } from \"./home.component\";\n@NgModule(\n {\n imports: [\n NativeScriptCommonModule,\n HomeRoutingModule\n ],\n declarations: [\n HomeComponent\n ],\n schemas: [\n NO_ERRORS_SCHEMA\n ]\n }\n)\nexport class HomeModule { }"
},
{
"code": null,
"e": 11491,
"s": 11485,
"text": "Here,"
},
{
"code": null,
"e": 11602,
"s": 11491,
"text": "HomeModule imports two modules, HomeRoutingModule and NativeScriptCommonModule and one component HomeComponent"
},
{
"code": null,
"e": 11700,
"s": 11602,
"text": "app\\home\\home.component.ts - Defines the Home component and used as home page of the application."
},
{
"code": null,
"e": 12051,
"s": 11700,
"text": "import { Component, OnInit } from \"@angular/core\";\n@Component(\n {\n selector: \"Home\", templateUrl: \"./home.component.html\" \n }\n) \nexport class HomeComponent implements OnInit { \n constructor() { \n // Use the component constructor to inject providers. \n } \n ngOnInit(): void { \n // Init your component properties here. \n } \n}"
},
{
"code": null,
"e": 12057,
"s": 12051,
"text": "Here,"
},
{
"code": null,
"e": 12125,
"s": 12057,
"text": "HomeComponent sets the template and selector of the home component."
},
{
"code": null,
"e": 12233,
"s": 12125,
"text": "app\\home\\home-routing.module.ts - Routing module for HomeModule and used to define routing for home module."
},
{
"code": null,
"e": 12679,
"s": 12233,
"text": "import { NgModule } from \"@angular/core\"; \nimport { Routes } from \"@angular/router\"; \nimport { NativeScriptRouterModule } from \"nativescript-angular/router\"; \nimport { HomeComponent } from \"./home.component\"; \nconst routes: Routes = [\n { path: \"\", component: HomeComponent } \n]; \n@NgModule(\n { \n imports: [NativeScriptRouterModule.forChild(routes)], \n exports: [NativeScriptRouterModule] \n }\n) \nexport class HomeRoutingModule { }"
},
{
"code": null,
"e": 12685,
"s": 12679,
"text": "Here,"
},
{
"code": null,
"e": 12740,
"s": 12685,
"text": "HomeRoutingModule set the empty path to HomeComponent."
},
{
"code": null,
"e": 12869,
"s": 12740,
"text": "app.component.html and home.component.html - They are used to design the UI of the application using NativeScript UI components."
},
{
"code": null,
"e": 12950,
"s": 12869,
"text": "If you want run your app without using any device, then type the below command −"
},
{
"code": null,
"e": 12963,
"s": 12950,
"text": "tns preview\n"
},
{
"code": null,
"e": 13058,
"s": 12963,
"text": "After executing this command, this will generate QR code to scan and connect with your device."
},
{
"code": null,
"e": 13065,
"s": 13058,
"text": "QRCode"
},
{
"code": null,
"e": 13130,
"s": 13065,
"text": "Now QR code is generated and connect to PlayGround in next step."
},
{
"code": null,
"e": 13440,
"s": 13130,
"text": "Open NativeScript PlayGround app on your iOS or Android mobile then choose Scan QR code option. It will open the camera. Focus the QR code displayed on the console. This will scan the QR Code. Scanning the QR Code will trigger the application build and then sync the application to the device as given below −"
},
{
"code": null,
"e": 15965,
"s": 13440,
"text": "Copying template files... \nPlatform android successfully added. v6.3.1 \nPreparing project... \nFile change detected. Starting incremental webpack compilation... \nwebpack is watching the files... \nHash: 1f38aaf6fcda4e082b88 \nVersion: webpack 4.27.1 \nTime: 9333ms \nBuilt at: 01/04/2020 4:22:31 PM\n Asset Size Chunks Chunk Names \n 0.js 8.32 KiB 0 [emitted] \n bundle.js 22.9 KiB bundle [emitted] bundle \n package.json 112 bytes [emitted] \n runtime.js 73 KiB runtime [emitted] runtime \ntns-java-classes.js 0 bytes [emitted] \n vendor.js 345 KiB vendor [emitted] vendor \nEntrypoint bundle = runtime.js vendor.js bundle.js \n[../$$_lazy_route_resource lazy recursive] ../$$_lazy_route_resource lazy \nnamespace object 160 bytes {bundle} [built] [./app.css] 1.18 KiB {bundle} [built] [./app/app-routing.module.ts] 688 bytes {bundle} [built] \n[./app/app.component.html] 62 bytes {bundle} [built] \n[./app/app.component.ts] 354 bytes {bundle} [built] \n[./app/app.module.ts] 3.22 KiB {bundle} [built] \n[./app/home/home.module.ts] 710 bytes {0} [built] \n[./main.ts] 1.84 KiB {bundle} [built] \n[@angular/core] external \"@angular/core\" 42 bytes {bundle} [built] [nativescript-angular/nativescript.module] external \"nativescript-\nangular/nativescript.module\" 42 bytes {bundle} [built] \n[nativescript-angular/platform] external \"nativescript-angular/platform\" 42 \nbytes {bundle} [built] [tns-core-modules/application] external \"tns-core-\nmodules/application\" 42 bytes {bundle} [built] \n[tns-core-modules/bundle-entry-points] external \"tns-core-modules/bundle-entry-points\" 42 \nbytes {bundle} [built] \n[tns-core-modules/ui/frame] external \"tns-core-\nmodules/ui/frame\" 42 bytes {bundle} [built] \n[tns-core-modules/ui/frame/activity] external \"tns-core-\nmodules/ui/frame/activity\" 42 bytes {bundle} [built] \n + 15 hidden modules Webpack compilation complete. Watching for file changes. \nWebpack build done! \nProject successfully prepared (android) \nStart sending initial files for device Bala Honor Holly (ff5e8622-7a01-4f9c-\nb02f-3dc6d4ee0e1f). \nSuccessfully sent initial files for device Bala Honor Holly (ff5e8622-7a01-4f9c-b02f-3dc6d4ee0e1f). \nLOG from device Bala Honor Holly: HMR: Hot Module Replacement Enabled. Waiting for signal. \nLOG from device Bala Honor Holly: Angular is running in the development mode. \nCall enableProdMode() to enable the production mode.\n"
},
{
"code": null,
"e": 16048,
"s": 15965,
"text": "After scanning, you should see your BlankNgApp on your device. It is shown below −"
},
{
"code": null,
"e": 16153,
"s": 16048,
"text": "If you want to test the connected device in your application, you can verify it using the below syntax −"
},
{
"code": null,
"e": 16198,
"s": 16153,
"text": "'tns device <Platform> --available-devices'\n"
},
{
"code": null,
"e": 16261,
"s": 16198,
"text": "After that, you can execute your app using the below command −"
},
{
"code": null,
"e": 16270,
"s": 16261,
"text": "tns run\n"
},
{
"code": null,
"e": 16445,
"s": 16270,
"text": "The above command is used to build your apps locally and install on Andriod or iOS devices. If you want to run your app on an Android simulator, then type the below command −"
},
{
"code": null,
"e": 16462,
"s": 16445,
"text": "tns run android\n"
},
{
"code": null,
"e": 16513,
"s": 16462,
"text": "For iOS device, you can follow the below command −"
},
{
"code": null,
"e": 16526,
"s": 16513,
"text": "tns run ios\n"
},
{
"code": null,
"e": 16643,
"s": 16526,
"text": "This will initialize the app in an Android/iOS device. We will discuss this more in detail in the upcoming chapters."
},
{
"code": null,
"e": 16956,
"s": 16643,
"text": "NativeScript provides real time syncing of changes in the application to the preview application. Let us open the project using any of your favourite editor (Visual Studio Code would be the ideal choice for better visualization). Let us add some changes in our code and see how that will be detected in LiveSync."
},
{
"code": null,
"e": 17015,
"s": 16956,
"text": "Now open the file app.css and it will have below content −"
},
{
"code": null,
"e": 17237,
"s": 17015,
"text": "@import \"~@nativescript/theme/css/core.css\"; \n@import \"~@nativescript/theme/css/blue.css\"; \n/* Place any CSS rules you want to apply on both iOS and Android here. \nThis is where the vast majority of your CSS code goes. */"
},
{
"code": null,
"e": 17377,
"s": 17237,
"text": "Here, import statement tells the color scheme of our app. Let’s change the blue color scheme to the brown color scheme as specified below −"
},
{
"code": null,
"e": 17601,
"s": 17377,
"text": "@import \"~@nativescript/theme/css/core.css\"; \n@import \"~@nativescript/theme/css/brown.css\"; \n/* Place any CSS rules you want to apply on both iOS and Android here. \nThis is where the vast majority of your CSS code goes. */\n"
},
{
"code": null,
"e": 17701,
"s": 17601,
"text": "The application in our device refreshes and you should see a brown color ActionBar as shown below −"
},
{
"code": null,
"e": 17750,
"s": 17701,
"text": "Below is the BlankNgApp Home Page - Brown Theme."
},
{
"code": null,
"e": 17783,
"s": 17750,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17799,
"s": 17783,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 17806,
"s": 17799,
"text": " Print"
},
{
"code": null,
"e": 17817,
"s": 17806,
"text": " Add Notes"
}
] |
Convert dataframe to list of vectors in R - GeeksforGeeks | 25 Aug, 2021
In this article, we will learn how to convert a dataframe into a list of vectors, such that we can use columns of the dataframes as vectors in the R Programming language.
as.list() function in R Language is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames.
Syntax: as.list( object )
Parameter: Dataframe object in our case
Simply pass our sample dataframe object as an argument in as.list(), which will return a list of vectors.
Example 1:
R
df<-data.frame(c1=c(1:5), c2=c(6:10), c3=c(11:15), c4=c(16:20)) print("Sample Dataframe")print (df) list=as.list(df) print("After Conversion of Dataframe into list of Vectors")print(list)
Output:
[1] "Sample Dataframe"
c1 c2 c3 c4
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 4 9 14 19
5 5 10 15 20
[1] "After Conversion of Dataframe into list of Vectors"
$c1
[1] 1 2 3 4 5
$c2
[1] 6 7 8 9 10
$c3
[1] 11 12 13 14 15
$c4
[1] 16 17 18 19 20
Example 2:
R
df <- data.frame(name = c("Geeks", "for", "Geeks"), roll_no = c(10, 20, 30), age=c(20,21,22) ) print("Sample Dataframe")print (df) print("Our list after being converted from a dataframe: ") list=as.list(df)list
Output:
[1] "Sample Dataframe"
name roll_no age
1 Geeks 10 20
2 for 20 21
3 Geeks 30 22
[1] "Our list after being converted from a dataframe: "
$name
[1] Geeks for Geeks
Levels: for Geeks
$roll_no
[1] 10 20 30
$age
[1] 20 21 22
split() function in R Language is used to divide a data vector into groups as defined by the factor provided.
Syntax: split(x, f)
Parameters:
x: represents data vector or data frame
f: represents factor to divide the data
Example:
R
df<-data.frame(c1=c(1:5), c2=c(6:10), c3=c(11:15), c4=c(16:20)) print("Sample Dataframe")print (df) print("Result after conversion") split(df, 1:nrow(df))
Output:
[1] "Sample Dataframe"
c1 c2 c3 c4
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 4 9 14 19
5 5 10 15 20
[1] "Result after conversion"
$`1`
c1 c2 c3 c4
1 1 6 11 16
$`2`
c1 c2 c3 c4
2 2 7 12 17
$`3`
c1 c2 c3 c4
3 3 8 13 18
$`4`
c1 c2 c3 c4
4 4 9 14 19
$`5`
c1 c2 c3 c4
5 5 10 15 20
sagartomar9927
Picked
R DataFrame-Programs
R List-Programs
R-DataFrame
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24732,
"s": 24561,
"text": "In this article, we will learn how to convert a dataframe into a list of vectors, such that we can use columns of the dataframes as vectors in the R Programming language."
},
{
"code": null,
"e": 24871,
"s": 24732,
"text": "as.list() function in R Language is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames."
},
{
"code": null,
"e": 24898,
"s": 24871,
"text": "Syntax: as.list( object )"
},
{
"code": null,
"e": 24938,
"s": 24898,
"text": "Parameter: Dataframe object in our case"
},
{
"code": null,
"e": 25045,
"s": 24938,
"text": "Simply pass our sample dataframe object as an argument in as.list(), which will return a list of vectors. "
},
{
"code": null,
"e": 25056,
"s": 25045,
"text": "Example 1:"
},
{
"code": null,
"e": 25058,
"s": 25056,
"text": "R"
},
{
"code": "df<-data.frame(c1=c(1:5), c2=c(6:10), c3=c(11:15), c4=c(16:20)) print(\"Sample Dataframe\")print (df) list=as.list(df) print(\"After Conversion of Dataframe into list of Vectors\")print(list)",
"e": 25288,
"s": 25058,
"text": null
},
{
"code": null,
"e": 25296,
"s": 25288,
"text": "Output:"
},
{
"code": null,
"e": 25547,
"s": 25296,
"text": "[1] \"Sample Dataframe\"\n c1 c2 c3 c4\n1 1 6 11 16\n2 2 7 12 17\n3 3 8 13 18\n4 4 9 14 19\n5 5 10 15 20\n[1] \"After Conversion of Dataframe into list of Vectors\"\n$c1\n[1] 1 2 3 4 5\n$c2\n[1] 6 7 8 9 10\n$c3\n[1] 11 12 13 14 15\n$c4\n[1] 16 17 18 19 20"
},
{
"code": null,
"e": 25558,
"s": 25547,
"text": "Example 2:"
},
{
"code": null,
"e": 25560,
"s": 25558,
"text": "R"
},
{
"code": "df <- data.frame(name = c(\"Geeks\", \"for\", \"Geeks\"), roll_no = c(10, 20, 30), age=c(20,21,22) ) print(\"Sample Dataframe\")print (df) print(\"Our list after being converted from a dataframe: \") list=as.list(df)list",
"e": 25816,
"s": 25560,
"text": null
},
{
"code": null,
"e": 25824,
"s": 25816,
"text": "Output:"
},
{
"code": null,
"e": 26068,
"s": 25824,
"text": "[1] \"Sample Dataframe\"\n name roll_no age\n1 Geeks 10 20\n2 for 20 21\n3 Geeks 30 22\n[1] \"Our list after being converted from a dataframe: \"\n$name\n[1] Geeks for Geeks\nLevels: for Geeks\n$roll_no\n[1] 10 20 30\n$age\n[1] 20 21 22"
},
{
"code": null,
"e": 26179,
"s": 26068,
"text": " split() function in R Language is used to divide a data vector into groups as defined by the factor provided."
},
{
"code": null,
"e": 26199,
"s": 26179,
"text": "Syntax: split(x, f)"
},
{
"code": null,
"e": 26211,
"s": 26199,
"text": "Parameters:"
},
{
"code": null,
"e": 26251,
"s": 26211,
"text": "x: represents data vector or data frame"
},
{
"code": null,
"e": 26291,
"s": 26251,
"text": "f: represents factor to divide the data"
},
{
"code": null,
"e": 26300,
"s": 26291,
"text": "Example:"
},
{
"code": null,
"e": 26302,
"s": 26300,
"text": "R"
},
{
"code": "df<-data.frame(c1=c(1:5), c2=c(6:10), c3=c(11:15), c4=c(16:20)) print(\"Sample Dataframe\")print (df) print(\"Result after conversion\") split(df, 1:nrow(df))",
"e": 26499,
"s": 26302,
"text": null
},
{
"code": null,
"e": 26507,
"s": 26499,
"text": "Output:"
},
{
"code": null,
"e": 26809,
"s": 26507,
"text": "[1] \"Sample Dataframe\"\n c1 c2 c3 c4\n1 1 6 11 16\n2 2 7 12 17\n3 3 8 13 18\n4 4 9 14 19\n5 5 10 15 20\n[1] \"Result after conversion\"\n$`1`\n c1 c2 c3 c4\n1 1 6 11 16\n$`2`\n c1 c2 c3 c4\n2 2 7 12 17\n$`3`\n c1 c2 c3 c4\n3 3 8 13 18\n$`4`\n c1 c2 c3 c4\n4 4 9 14 19\n$`5`\n c1 c2 c3 c4\n5 5 10 15 20"
},
{
"code": null,
"e": 26824,
"s": 26809,
"text": "sagartomar9927"
},
{
"code": null,
"e": 26831,
"s": 26824,
"text": "Picked"
},
{
"code": null,
"e": 26852,
"s": 26831,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 26868,
"s": 26852,
"text": "R List-Programs"
},
{
"code": null,
"e": 26880,
"s": 26868,
"text": "R-DataFrame"
},
{
"code": null,
"e": 26887,
"s": 26880,
"text": "R-List"
},
{
"code": null,
"e": 26898,
"s": 26887,
"text": "R Language"
},
{
"code": null,
"e": 26909,
"s": 26898,
"text": "R Programs"
},
{
"code": null,
"e": 27007,
"s": 26909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27016,
"s": 27007,
"text": "Comments"
},
{
"code": null,
"e": 27029,
"s": 27016,
"text": "Old Comments"
},
{
"code": null,
"e": 27087,
"s": 27029,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27139,
"s": 27087,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27183,
"s": 27139,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27235,
"s": 27183,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27267,
"s": 27235,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 27325,
"s": 27267,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27369,
"s": 27325,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27418,
"s": 27369,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 27476,
"s": 27418,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Python | Decimal is_zero() method - GeeksforGeeks | 05 Sep, 2019
Decimal#is_zero() : is_zero() is a Decimal class method which checks whether the Decimal value is zero value.
Syntax:
Decimal.is_zero()
Parameter:
Decimal values
Return:
true - if the Decimal value is zero value; otherwise false
Code #1 : Example for is_zero() method
# Python Program explaining # is_zero() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal(0) # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.is_zero() methodprint ("\n\nDecimal a with is_zero() method : ", a.is_zero()) print ("Decimal b with is_zero() method : ", b.is_zero())
Output :
Decimal value a : -1
Decimal value b : 0
Decimal a with is_zero() method : False
Decimal b with is_zero() method : True
Code #2 : Example for is_zero() method
# Python Program explaining # is_zero() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-0) b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.is_zero() methodprint ("\n\nDecimal a with is_zero() method : ", a.is_zero()) print ("Decimal b with is_zero() method : ", b.is_zero())
Output :
Decimal value a : 0
Decimal value b : 3.21E+7
Decimal a with is_zero() method : True
Decimal b with is_zero() method : False
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24290,
"s": 24262,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 24400,
"s": 24290,
"text": "Decimal#is_zero() : is_zero() is a Decimal class method which checks whether the Decimal value is zero value."
},
{
"code": null,
"e": 24526,
"s": 24400,
"text": "Syntax: \nDecimal.is_zero()\n\nParameter: \nDecimal values\n\nReturn: \ntrue - if the Decimal value is zero value; otherwise false\n\n"
},
{
"code": null,
"e": 24565,
"s": 24526,
"text": "Code #1 : Example for is_zero() method"
},
{
"code": "# Python Program explaining # is_zero() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal(0) # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.is_zero() methodprint (\"\\n\\nDecimal a with is_zero() method : \", a.is_zero()) print (\"Decimal b with is_zero() method : \", b.is_zero())",
"e": 24970,
"s": 24565,
"text": null
},
{
"code": null,
"e": 24979,
"s": 24970,
"text": "Output :"
},
{
"code": null,
"e": 25107,
"s": 24979,
"text": "Decimal value a : -1\nDecimal value b : 0\n\n\nDecimal a with is_zero() method : False\nDecimal b with is_zero() method : True\n\n"
},
{
"code": null,
"e": 25146,
"s": 25107,
"text": "Code #2 : Example for is_zero() method"
},
{
"code": "# Python Program explaining # is_zero() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-0) b = Decimal('321e + 5') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.is_zero() methodprint (\"\\n\\nDecimal a with is_zero() method : \", a.is_zero()) print (\"Decimal b with is_zero() method : \", b.is_zero())",
"e": 25560,
"s": 25146,
"text": null
},
{
"code": null,
"e": 25569,
"s": 25560,
"text": "Output :"
},
{
"code": null,
"e": 25701,
"s": 25569,
"text": "Decimal value a : 0\nDecimal value b : 3.21E+7\n\n\nDecimal a with is_zero() method : True\nDecimal b with is_zero() method : False\n"
},
{
"code": null,
"e": 25708,
"s": 25701,
"text": "Python"
},
{
"code": null,
"e": 25806,
"s": 25708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25824,
"s": 25806,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25859,
"s": 25824,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25881,
"s": 25859,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25913,
"s": 25881,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25943,
"s": 25913,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25985,
"s": 25943,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26011,
"s": 25985,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26048,
"s": 26011,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26091,
"s": 26048,
"text": "Python program to convert a list to string"
}
] |
Tryit Editor v3.7 | HTML Form elements
Tryit: HTML output element | [
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML Form elements"
}
] |
Create and write on excel file using xlsxwriter module in Python | Python’s wide availability of libraries enables it to interact with Microsoft excel which is a very widely used data processing tool. In this article we will see how we can use the module named xlsxwriter to create and write into a excel file. It cannot write into existing excel file.
We can write to each cell of an excel sheet by writing to the name of the cell. In the below example we create a workbook and then ass a worksheet to it. Finally write to the cells of the worksheet using the write() method.
import xlsxwriter
# Cretae a xlsx file
xlsx_File = xlsxwriter.Workbook('Schedule.xlsx')
# Add new worksheet
sheet_schedule = xlsx_File.add_worksheet()
# write into the worksheet
sheet_schedule.write('A1', 'Day')
sheet_schedule.write('A2', 'Mon')
sheet_schedule.write('A3', 'Tue')
sheet_schedule.write('B1', 'Schedule')
sheet_schedule.write('B2', 'Final Exam')
sheet_schedule.write('B3', 'party')
# Close the Excel file
xlsx_File.close()
Running the above code gives us the following result −
In this approach we can initialize the row and column number from where we want to start writing. Then use a for loop to add required values to the rows and cells by dynamically increasing their values. In the below example we only add more rows. But by designing a loop within a loop we can also create both columns and rows dynamically.
import xlsxwriter
# Cretae a xlsx file
xlsx_File = xlsxwriter.Workbook('Days.xlsx')
# Add new worksheet
sheet_days = xlsx_File.add_worksheet()
row = 1
column = 1
days = ['Mon','Tue','wed','Thu','Fri','Sat']
# Iterating through days list
for day in days:
sheet_days.write(row, column, day)
row += 1
# Close the Excel file
xlsx_File.close()
Running the above code gives us the following result − | [
{
"code": null,
"e": 1348,
"s": 1062,
"text": "Python’s wide availability of libraries enables it to interact with Microsoft excel which is a very widely used data processing tool. In this article we will see how we can use the module named xlsxwriter to create and write into a excel file. It cannot write into existing excel file."
},
{
"code": null,
"e": 1572,
"s": 1348,
"text": "We can write to each cell of an excel sheet by writing to the name of the cell. In the below example we create a workbook and then ass a worksheet to it. Finally write to the cells of the worksheet using the write() method."
},
{
"code": null,
"e": 2014,
"s": 1572,
"text": "import xlsxwriter\n\n# Cretae a xlsx file\nxlsx_File = xlsxwriter.Workbook('Schedule.xlsx')\n\n# Add new worksheet\nsheet_schedule = xlsx_File.add_worksheet()\n\n# write into the worksheet\nsheet_schedule.write('A1', 'Day')\nsheet_schedule.write('A2', 'Mon')\nsheet_schedule.write('A3', 'Tue')\n\nsheet_schedule.write('B1', 'Schedule')\nsheet_schedule.write('B2', 'Final Exam')\nsheet_schedule.write('B3', 'party')\n\n# Close the Excel file\nxlsx_File.close()"
},
{
"code": null,
"e": 2069,
"s": 2014,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2408,
"s": 2069,
"text": "In this approach we can initialize the row and column number from where we want to start writing. Then use a for loop to add required values to the rows and cells by dynamically increasing their values. In the below example we only add more rows. But by designing a loop within a loop we can also create both columns and rows dynamically."
},
{
"code": null,
"e": 2753,
"s": 2408,
"text": "import xlsxwriter\n\n# Cretae a xlsx file\nxlsx_File = xlsxwriter.Workbook('Days.xlsx')\n\n# Add new worksheet\nsheet_days = xlsx_File.add_worksheet()\n\nrow = 1\ncolumn = 1\n\ndays = ['Mon','Tue','wed','Thu','Fri','Sat']\n\n# Iterating through days list\nfor day in days:\nsheet_days.write(row, column, day)\nrow += 1\n\n# Close the Excel file\nxlsx_File.close()"
},
{
"code": null,
"e": 2808,
"s": 2753,
"text": "Running the above code gives us the following result −"
}
] |
Data Slicing using PyQtGraph - GeeksforGeeks | 13 Jan, 2022
In this article, we will see how we can perform data slicing using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).
In order to install the PyQtGraph we use the command given below
pip install pyqtgraph
A slice in a multidimensional array is a column of data corresponding to a single value for one or more members of the dimension. Slicing is the act of divvying up the cube to extract this information for a given slice. It is important because it helps the user visualize and gather information specific to a dimension. When you think of slicing, think of it as a specialized filter for a particular value in a dimension. A simple data-slicing task would be for given 3D data selecting a 2D plane and interpolate data along that plane to generate a slice image.
In order to do this, we have to do the following
Import the required libraries like pyqtgraph, pyqt5 and numpy
Create a main window class using pyqt5
Create a graph window to add the widgets required to show the slicing
Create two image view object in the layout, first to show the whole 3d data and second to show the slice
Create a roi object and add it to the first image view to select the slice
Create a 3d data and add it to the image view
Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second image view
Add this graph window to the main window layout with any additional widgets.
Below is the implementation.
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 700, 550) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # text text = "Data Slicing" # creating a label label = QLabel(text) # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # creating a window for graphs win = QMainWindow() # creating a widget object cwid = QWidget() # setting central widget to the graph window win.setCentralWidget(cwid) # creating a grid layout lay = QGridLayout() # setting grid layout to central widget of graphs cwid.setLayout(lay) # creating a image view objects imv1 = pg.ImageView() imv2 = pg.ImageView() # adding image view objects to the layout lay.addWidget(imv1, 0, 0) lay.addWidget(imv2, 1, 0) # creating a ROI object for selecting slice roi = pg.LineSegmentROI([[30, 64], [100, 64]], pen='r') # add roi to image view 1 imv1.addItem(roi) # creating 3d data # x value using numpy x1 = np.linspace(-30, 10, 128)[:, np.newaxis, np.newaxis] x2 = np.linspace(-20, 20, 128)[:, np.newaxis, np.newaxis] # y value using numpy y = np.linspace(-30, 10, 128)[np.newaxis, :, np.newaxis] z = np.linspace(-20, 20, 128)[np.newaxis, np.newaxis, :] # dimension 1 values d1 = np.sqrt(x1 ** 2 + y ** 2 + z ** 2) # dimension 2 values d2 = 2 * np.sqrt(x1[::-1] ** 2 + y ** 2 + z ** 2) # dimension 3 value d3 = 4 * np.sqrt(x2 ** 2 + y[:, ::-1] ** 2 + z ** 2) # whole data ie all 3 dimensions data = (np.sin(d1) / d1 ** 2) + \ (np.sin(d2) / d2 ** 2) + (np.sin(d3) / d3 ** 2) # method to update the image view 2 def update(): # get the roi selected data from image view 1 d2 = roi.getArrayRegion(data, imv1.imageItem, axes=(1, 2)) # update the image view 2 data imv2.setImage(d2) # adding update method to the roi # when region is changed this method get called roi.sigRegionChanged.connect(update) # Display the data in both image view imv1.setImage(data) # setting the range of image view imv1.setHistogramRange(-0.01, 0.01) # setting levels of the image view imv1.setLevels(-0.003, 0.003) # call the update method update() # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(win, 0, 1, 3, 1) # setting this widget as central widget of the main widow self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
sweetyty
Python-gui
Python-PyQtGraph
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 24685,
"s": 24212,
"text": "In this article, we will see how we can perform data slicing using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer)."
},
{
"code": null,
"e": 24750,
"s": 24685,
"text": "In order to install the PyQtGraph we use the command given below"
},
{
"code": null,
"e": 24772,
"s": 24750,
"text": "pip install pyqtgraph"
},
{
"code": null,
"e": 25335,
"s": 24772,
"text": "A slice in a multidimensional array is a column of data corresponding to a single value for one or more members of the dimension. Slicing is the act of divvying up the cube to extract this information for a given slice. It is important because it helps the user visualize and gather information specific to a dimension. When you think of slicing, think of it as a specialized filter for a particular value in a dimension. A simple data-slicing task would be for given 3D data selecting a 2D plane and interpolate data along that plane to generate a slice image. "
},
{
"code": null,
"e": 25385,
"s": 25335,
"text": "In order to do this, we have to do the following "
},
{
"code": null,
"e": 25447,
"s": 25385,
"text": "Import the required libraries like pyqtgraph, pyqt5 and numpy"
},
{
"code": null,
"e": 25486,
"s": 25447,
"text": "Create a main window class using pyqt5"
},
{
"code": null,
"e": 25556,
"s": 25486,
"text": "Create a graph window to add the widgets required to show the slicing"
},
{
"code": null,
"e": 25661,
"s": 25556,
"text": "Create two image view object in the layout, first to show the whole 3d data and second to show the slice"
},
{
"code": null,
"e": 25736,
"s": 25661,
"text": "Create a roi object and add it to the first image view to select the slice"
},
{
"code": null,
"e": 25782,
"s": 25736,
"text": "Create a 3d data and add it to the image view"
},
{
"code": null,
"e": 25928,
"s": 25782,
"text": "Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second image view"
},
{
"code": null,
"e": 26005,
"s": 25928,
"text": "Add this graph window to the main window layout with any additional widgets."
},
{
"code": null,
"e": 26034,
"s": 26005,
"text": "Below is the implementation."
},
{
"code": null,
"e": 26042,
"s": 26034,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 700, 550) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # text text = \"Data Slicing\" # creating a label label = QLabel(text) # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # creating a window for graphs win = QMainWindow() # creating a widget object cwid = QWidget() # setting central widget to the graph window win.setCentralWidget(cwid) # creating a grid layout lay = QGridLayout() # setting grid layout to central widget of graphs cwid.setLayout(lay) # creating a image view objects imv1 = pg.ImageView() imv2 = pg.ImageView() # adding image view objects to the layout lay.addWidget(imv1, 0, 0) lay.addWidget(imv2, 1, 0) # creating a ROI object for selecting slice roi = pg.LineSegmentROI([[30, 64], [100, 64]], pen='r') # add roi to image view 1 imv1.addItem(roi) # creating 3d data # x value using numpy x1 = np.linspace(-30, 10, 128)[:, np.newaxis, np.newaxis] x2 = np.linspace(-20, 20, 128)[:, np.newaxis, np.newaxis] # y value using numpy y = np.linspace(-30, 10, 128)[np.newaxis, :, np.newaxis] z = np.linspace(-20, 20, 128)[np.newaxis, np.newaxis, :] # dimension 1 values d1 = np.sqrt(x1 ** 2 + y ** 2 + z ** 2) # dimension 2 values d2 = 2 * np.sqrt(x1[::-1] ** 2 + y ** 2 + z ** 2) # dimension 3 value d3 = 4 * np.sqrt(x2 ** 2 + y[:, ::-1] ** 2 + z ** 2) # whole data ie all 3 dimensions data = (np.sin(d1) / d1 ** 2) + \\ (np.sin(d2) / d2 ** 2) + (np.sin(d3) / d3 ** 2) # method to update the image view 2 def update(): # get the roi selected data from image view 1 d2 = roi.getArrayRegion(data, imv1.imageItem, axes=(1, 2)) # update the image view 2 data imv2.setImage(d2) # adding update method to the roi # when region is changed this method get called roi.sigRegionChanged.connect(update) # Display the data in both image view imv1.setImage(data) # setting the range of image view imv1.setHistogramRange(-0.01, 0.01) # setting levels of the image view imv1.setLevels(-0.003, 0.003) # call the update method update() # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(win, 0, 1, 3, 1) # setting this widget as central widget of the main widow self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 29850,
"s": 26042,
"text": null
},
{
"code": null,
"e": 29861,
"s": 29850,
"text": "Output : "
},
{
"code": null,
"e": 29872,
"s": 29863,
"text": "sweetyty"
},
{
"code": null,
"e": 29883,
"s": 29872,
"text": "Python-gui"
},
{
"code": null,
"e": 29900,
"s": 29883,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 29907,
"s": 29900,
"text": "Python"
},
{
"code": null,
"e": 30005,
"s": 29907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30014,
"s": 30005,
"text": "Comments"
},
{
"code": null,
"e": 30027,
"s": 30014,
"text": "Old Comments"
},
{
"code": null,
"e": 30059,
"s": 30027,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30115,
"s": 30059,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30136,
"s": 30115,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 30175,
"s": 30136,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30217,
"s": 30175,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30244,
"s": 30217,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30275,
"s": 30244,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30317,
"s": 30275,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30353,
"s": 30317,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Chrono library in C++ | In this section we will see what is the Chrono library in C++. This Chrono library is used for date and time. Timers and clocks are different in different systems. So if we want to improve time over precision we can use this library.
In this library, it provides precision-neutral concept, by separating the durations and point of time.
The duration objects are used to express time span by means of a count like minute, two hours or ten minutes. For example, 30 seconds is represented by a duration consisting of 30 ticks of unit of 1 seconds.
#include <iostream>
#include <chrono>
using namespace std;
int main () {
using namespace std::chrono;
// chrono::milliseconds is an instantiation of std::chrono::duration milliseconds mili(1000);
mili = mili*60;
cout << "Duration : ";
cout << mili.count() << " milliseconds.\n";
cout << "Duration : ";
cout << (mili.count() * milliseconds::period::num / milliseconds::period::den);
cout << " seconds.\n";
}
Duration : 60000 milliseconds.
Duration : 60 seconds. | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "In this section we will see what is the Chrono library in C++. This Chrono library is used for date and time. Timers and clocks are different in different systems. So if we want to improve time over precision we can use this library."
},
{
"code": null,
"e": 1399,
"s": 1296,
"text": "In this library, it provides precision-neutral concept, by separating the durations and point of time."
},
{
"code": null,
"e": 1607,
"s": 1399,
"text": "The duration objects are used to express time span by means of a count like minute, two hours or ten minutes. For example, 30 seconds is represented by a duration consisting of 30 ticks of unit of 1 seconds."
},
{
"code": null,
"e": 2038,
"s": 1607,
"text": "#include <iostream>\n#include <chrono>\nusing namespace std;\nint main () {\n using namespace std::chrono;\n // chrono::milliseconds is an instantiation of std::chrono::duration milliseconds mili(1000);\n mili = mili*60;\n cout << \"Duration : \";\n cout << mili.count() << \" milliseconds.\\n\";\n cout << \"Duration : \";\n cout << (mili.count() * milliseconds::period::num / milliseconds::period::den);\n cout << \" seconds.\\n\";\n}"
},
{
"code": null,
"e": 2092,
"s": 2038,
"text": "Duration : 60000 milliseconds.\nDuration : 60 seconds."
}
] |
jQuery | change() with Examples - GeeksforGeeks | 03 Aug, 2021
The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements.
Syntax :
$(selector).change(function)
Parameter: It accepts an optional parameter “function”.Return Value: It returns the element with the modification.jQuery code to show the working of change() method:Code #1:In the below code, no function is passed to the change method.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <!--Demo of change method without passing function--> <script> $(document).ready(function() { $("button").click(function() { $("input").change(); }); }); </script></head> <body> <p>Click the button to see the changed value !!!</p> <!--click on this button and see the change --> <button>Click Me!</button> <p>Enter value: <input value="Donald" onchange="alert(this.value)" type="text"></p></body> </html>
Output:Before clicking the “Click Me” button-
After clicking the “Click Me” button-
Code #2:In the below code, function is passed to the change method.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <!--Here function is passed to the change method--> <script> $(document).ready(function() { $(".field").change(function() { $(this).css("background-color", "#7FFF00"); }); }); </script> <style> .field { padding: 5px; } </style></head> <body> <!--write something and click outside --> Enter Value: <input class="field" type="text"> <p>Write something in the input field, and then press enter or click outside the field.</p></body> </html>
Output:Before entering any values to the “Enter Value:” box-
After entering a values of “GeeksforGeeks” to the “Enter Value:” box and clicking outside of the box-
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.
destinierkunal34
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to change the background color after clicking the button in JavaScript ? | [
{
"code": null,
"e": 40643,
"s": 40615,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 40822,
"s": 40643,
"text": "The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements."
},
{
"code": null,
"e": 40831,
"s": 40822,
"text": "Syntax :"
},
{
"code": null,
"e": 40861,
"s": 40831,
"text": "$(selector).change(function)\n"
},
{
"code": null,
"e": 41097,
"s": 40861,
"text": "Parameter: It accepts an optional parameter “function”.Return Value: It returns the element with the modification.jQuery code to show the working of change() method:Code #1:In the below code, no function is passed to the change method."
},
{
"code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <!--Demo of change method without passing function--> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"input\").change(); }); }); </script></head> <body> <p>Click the button to see the changed value !!!</p> <!--click on this button and see the change --> <button>Click Me!</button> <p>Enter value: <input value=\"Donald\" onchange=\"alert(this.value)\" type=\"text\"></p></body> </html>",
"e": 41712,
"s": 41097,
"text": null
},
{
"code": null,
"e": 41758,
"s": 41712,
"text": "Output:Before clicking the “Click Me” button-"
},
{
"code": null,
"e": 41796,
"s": 41758,
"text": "After clicking the “Click Me” button-"
},
{
"code": null,
"e": 41864,
"s": 41796,
"text": "Code #2:In the below code, function is passed to the change method."
},
{
"code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <!--Here function is passed to the change method--> <script> $(document).ready(function() { $(\".field\").change(function() { $(this).css(\"background-color\", \"#7FFF00\"); }); }); </script> <style> .field { padding: 5px; } </style></head> <body> <!--write something and click outside --> Enter Value: <input class=\"field\" type=\"text\"> <p>Write something in the input field, and then press enter or click outside the field.</p></body> </html>",
"e": 42540,
"s": 41864,
"text": null
},
{
"code": null,
"e": 42601,
"s": 42540,
"text": "Output:Before entering any values to the “Enter Value:” box-"
},
{
"code": null,
"e": 42703,
"s": 42601,
"text": "After entering a values of “GeeksforGeeks” to the “Enter Value:” box and clicking outside of the box-"
},
{
"code": null,
"e": 42971,
"s": 42703,
"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": 42988,
"s": 42971,
"text": "destinierkunal34"
},
{
"code": null,
"e": 43002,
"s": 42988,
"text": "jQuery-Events"
},
{
"code": null,
"e": 43013,
"s": 43002,
"text": "JavaScript"
},
{
"code": null,
"e": 43020,
"s": 43013,
"text": "JQuery"
},
{
"code": null,
"e": 43118,
"s": 43020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43127,
"s": 43118,
"text": "Comments"
},
{
"code": null,
"e": 43140,
"s": 43127,
"text": "Old Comments"
},
{
"code": null,
"e": 43185,
"s": 43140,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 43254,
"s": 43185,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 43315,
"s": 43254,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 43387,
"s": 43315,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 43414,
"s": 43387,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 43460,
"s": 43414,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 43523,
"s": 43460,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 43552,
"s": 43523,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 43608,
"s": 43552,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
}
] |
C# program to return an array from methods | Call a method under Join method to join words −
string.Join(" ", display())
Now set a string array −
string[] str = new string[5];
Add individual elements −
str[0] = "My";
str[1] = "name";
str[2] = "is";
str[3] = "Brad";
str[4] = "Pitt";
And return the same string array from method −
return str;
The following is the complete code −
Live Demo
using System;
public class Demo {
public static void Main() {
Console.WriteLine(string.Join(" ", display()));
}
static string[] display() {
string[] str = new string[5];
// string array elements
str[0] = "My";
str[1] = "name";
str[2] = "is";
str[3] = "Brad";
str[4] = "Pitt";
return str;
}
}
My name is Brad Pitt | [
{
"code": null,
"e": 1110,
"s": 1062,
"text": "Call a method under Join method to join words −"
},
{
"code": null,
"e": 1138,
"s": 1110,
"text": "string.Join(\" \", display())"
},
{
"code": null,
"e": 1163,
"s": 1138,
"text": "Now set a string array −"
},
{
"code": null,
"e": 1193,
"s": 1163,
"text": "string[] str = new string[5];"
},
{
"code": null,
"e": 1219,
"s": 1193,
"text": "Add individual elements −"
},
{
"code": null,
"e": 1300,
"s": 1219,
"text": "str[0] = \"My\";\nstr[1] = \"name\";\nstr[2] = \"is\";\nstr[3] = \"Brad\";\nstr[4] = \"Pitt\";"
},
{
"code": null,
"e": 1347,
"s": 1300,
"text": "And return the same string array from method −"
},
{
"code": null,
"e": 1359,
"s": 1347,
"text": "return str;"
},
{
"code": null,
"e": 1396,
"s": 1359,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1407,
"s": 1396,
"text": " Live Demo"
},
{
"code": null,
"e": 1767,
"s": 1407,
"text": "using System;\n\npublic class Demo {\n public static void Main() {\n Console.WriteLine(string.Join(\" \", display()));\n }\n static string[] display() {\n string[] str = new string[5];\n\n // string array elements\n str[0] = \"My\";\n str[1] = \"name\";\n str[2] = \"is\";\n str[3] = \"Brad\";\n str[4] = \"Pitt\";\n return str;\n }\n}"
},
{
"code": null,
"e": 1788,
"s": 1767,
"text": "My name is Brad Pitt"
}
] |
2D Transformation in Computer Graphics | Set 1 (Scaling of Objects) - GeeksforGeeks | 09 Feb, 2018
A scaling transformation alters size of an object. In the scaling process, we either compress or expand the dimension of the object.Scaling operation can be achieved by multiplying each vertex coordinate (x, y) of the polygon by scaling factor sx and sy to produce the transformed coordinates as (x’, y’).So, x’ = x * sx and y’ = y * sy.The scaling factor sx, sy scales the object in X and Y direction respectively. So, the above equation can be represented in matrix form:Or P’ = S . PScaling process:Note: If the scaling factor S is less than 1, then we reduce the size of the object. If the scaling factor S is greater than 1, then we increase size of the object.
Algorithm:
1. Make a 2x2 scaling matrix S as:
Sx 0
0 Sy
2. For each point of the polygon.
(i) Make a 2x1 matrix P, where P[0][0] equals
to x coordinate of the point and P[1][0]
equals to y coordinate of the point.
(ii) Multiply scaling matrix S with point
matrix P to get the new coordinate.
3. Draw the polygon using new coordinates.
Below is C implementation:
// C program to demonstrate scaling of abjects#include<stdio.h>#include<graphics.h> // Matrix Multiplication to find new Coordinates.// s[][] is scaling matrix. p[][] is to store// points that needs to be scaled.// p[0][0] is x coordinate of point.// p[1][0] is y coordinate of given point.void findNewCoordinate(int s[][2], int p[][1]){ int temp[2][1] = { 0 }; for (int i = 0; i < 2; i++) for (int j = 0; j < 1; j++) for (int k = 0; k < 2; k++) temp[i][j] += (s[i][k] * p[k][j]); p[0][0] = temp[0][0]; p[1][0] = temp[1][0];} // Scaling the Polygonvoid scale(int x[], int y[], int sx, int sy){ // Triangle before Scaling line(x[0], y[0], x[1], y[1]); line(x[1], y[1], x[2], y[2]); line(x[2], y[2], x[0], y[0]); // Initializing the Scaling Matrix. int s[2][2] = { sx, 0, 0, sy }; int p[2][1]; // Scaling the triangle for (int i = 0; i < 3; i++) { p[0][0] = x[i]; p[1][0] = y[i]; findNewCoordinate(s, p); x[i] = p[0][0]; y[i] = p[1][0]; } // Triangle after Scaling line(x[0], y[0], x[1], y[1]); line(x[1], y[1], x[2], y[2]); line(x[2], y[2], x[0], y[0]);} // Driven Programint main(){ int x[] = { 100, 200, 300 }; int y[] = { 200, 100, 200 }; int sx = 2, sy = 2; int gd, gm; detectgraph(&gd, &gm); initgraph(&gd, &gm," "); scale(x, y, sx,sy); getch(); return 0;}
Output:
This article is contributed by Anuj Chauhan. 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.
computer-graphics
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Recursive Practice Problems with Solutions
Playfair Cipher with Examples
How to write a Pseudo Code?
Quadratic Probing in Hashing
Uniform-Cost Search (Dijkstra for large Graphs)
K means Clustering - Introduction
Quick Sort vs Merge Sort | [
{
"code": null,
"e": 24234,
"s": 24206,
"text": "\n09 Feb, 2018"
},
{
"code": null,
"e": 24901,
"s": 24234,
"text": "A scaling transformation alters size of an object. In the scaling process, we either compress or expand the dimension of the object.Scaling operation can be achieved by multiplying each vertex coordinate (x, y) of the polygon by scaling factor sx and sy to produce the transformed coordinates as (x’, y’).So, x’ = x * sx and y’ = y * sy.The scaling factor sx, sy scales the object in X and Y direction respectively. So, the above equation can be represented in matrix form:Or P’ = S . PScaling process:Note: If the scaling factor S is less than 1, then we reduce the size of the object. If the scaling factor S is greater than 1, then we increase size of the object."
},
{
"code": null,
"e": 24912,
"s": 24901,
"text": "Algorithm:"
},
{
"code": null,
"e": 25275,
"s": 24912,
"text": "1. Make a 2x2 scaling matrix S as:\n Sx 0\n 0 Sy\n2. For each point of the polygon.\n (i) Make a 2x1 matrix P, where P[0][0] equals \n to x coordinate of the point and P[1][0] \n equals to y coordinate of the point.\n (ii) Multiply scaling matrix S with point \n matrix P to get the new coordinate.\n3. Draw the polygon using new coordinates.\n"
},
{
"code": null,
"e": 25302,
"s": 25275,
"text": "Below is C implementation:"
},
{
"code": "// C program to demonstrate scaling of abjects#include<stdio.h>#include<graphics.h> // Matrix Multiplication to find new Coordinates.// s[][] is scaling matrix. p[][] is to store// points that needs to be scaled.// p[0][0] is x coordinate of point.// p[1][0] is y coordinate of given point.void findNewCoordinate(int s[][2], int p[][1]){ int temp[2][1] = { 0 }; for (int i = 0; i < 2; i++) for (int j = 0; j < 1; j++) for (int k = 0; k < 2; k++) temp[i][j] += (s[i][k] * p[k][j]); p[0][0] = temp[0][0]; p[1][0] = temp[1][0];} // Scaling the Polygonvoid scale(int x[], int y[], int sx, int sy){ // Triangle before Scaling line(x[0], y[0], x[1], y[1]); line(x[1], y[1], x[2], y[2]); line(x[2], y[2], x[0], y[0]); // Initializing the Scaling Matrix. int s[2][2] = { sx, 0, 0, sy }; int p[2][1]; // Scaling the triangle for (int i = 0; i < 3; i++) { p[0][0] = x[i]; p[1][0] = y[i]; findNewCoordinate(s, p); x[i] = p[0][0]; y[i] = p[1][0]; } // Triangle after Scaling line(x[0], y[0], x[1], y[1]); line(x[1], y[1], x[2], y[2]); line(x[2], y[2], x[0], y[0]);} // Driven Programint main(){ int x[] = { 100, 200, 300 }; int y[] = { 200, 100, 200 }; int sx = 2, sy = 2; int gd, gm; detectgraph(&gd, &gm); initgraph(&gd, &gm,\" \"); scale(x, y, sx,sy); getch(); return 0;}",
"e": 26738,
"s": 25302,
"text": null
},
{
"code": null,
"e": 26746,
"s": 26738,
"text": "Output:"
},
{
"code": null,
"e": 27046,
"s": 26746,
"text": "This article is contributed by Anuj Chauhan. 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": 27171,
"s": 27046,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27189,
"s": 27171,
"text": "computer-graphics"
},
{
"code": null,
"e": 27200,
"s": 27189,
"text": "Algorithms"
},
{
"code": null,
"e": 27211,
"s": 27200,
"text": "Algorithms"
},
{
"code": null,
"e": 27309,
"s": 27211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27318,
"s": 27309,
"text": "Comments"
},
{
"code": null,
"e": 27331,
"s": 27318,
"text": "Old Comments"
},
{
"code": null,
"e": 27380,
"s": 27331,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 27405,
"s": 27380,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 27432,
"s": 27405,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 27475,
"s": 27432,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 27505,
"s": 27475,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 27533,
"s": 27505,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 27562,
"s": 27533,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 27610,
"s": 27562,
"text": "Uniform-Cost Search (Dijkstra for large Graphs)"
},
{
"code": null,
"e": 27644,
"s": 27610,
"text": "K means Clustering - Introduction"
}
] |
Snake case of a given sentence - GeeksforGeeks | 27 Dec, 2021
Given a sentence, task is to remove spaces from the sentence and rewrite in Snake case. It is a style of writing where we replace spaces with underscore and all words begin with small letters.Examples :
Input : I got intern at geeksforgeeks
Output : i_got_intern_at_geeksforgeeks
Input : Here comes the garden
Output : here_comes_the_garden
Simple solution : First method is to traverse sentence and one by one replace spaces by underscores and changing case of first character to small letter. It takes O(n*n) time.Efficient solution : We traverse given string, while traversing we replace space character with underscore and whenever we encounter non-space letter, we change that letter to small.Below is the code implementation :
C++
Java
Python3
C#
PHP
Javascript
// CPP program to convert given sentence/// to snake case#include <bits/stdc++.h>using namespace std; // Function to replace spaces and convert// into snake casevoid convert(string str){ int n = str.length(); for (int i = 0; i < n; i++) { // Converting space to underscore if (str.at(i) == ' ') str.at(i) = '_'; else // If not space, convert into lower character str.at(i) = tolower(str.at(i)); } cout << str;} // Driver programint main(){ string str = "I got intern at geeksforgeeks"; // Calling function convert(str); return 0;}
// Java program to convert// given sentence to// snake caseimport java.io.*; class GFG{ // Function to replace// spaces and convert// into snake casestatic void convert(String str){ int n = str.length(); String str1 = ""; for (int i = 0; i < n; i++) { // Converting space // to underscore if (str.charAt(i) == ' ') str1 = str1 + '_'; else // If not space, convert // into lower character str1 = str1 + Character.toLowerCase(str.charAt(i)); } System.out.print(str1);} // Driver Codepublic static void main(String args[]){ String str = "I got intern at geeksforgeeks"; // Calling function convert(str);}} // This code is contributed by// Manish Shaw(manishshaw1)
# Python3 program to convert given sentence# to snake case # Function to replace spaces and convert# into snake casedef convert(string) : n = len(string); string = list(string); for i in range(n) : # Converting space to underscore if (string[i] == ' ') : string[i] = '_'; else : # If not space, convert # into lower character string[i] = string[i].lower(); string = "".join(string) print(string); # Driver programif __name__ == "__main__" : string = "I got intern at geeksforgeeks"; # Calling function convert(string); # This code is contributed by AnkitRai01
// C# program to convert// given sentence to// snake caseusing System; class GFG{ // Function to replace // spaces and convert // into snake case static void convert(string str) { int n = str.Length; string str1 = ""; for (int i = 0; i < n; i++) { // Converting space // to underscore if (str[i] == ' ') str1 = str1 + '_'; else // If not space, convert // into lower character str1 = str1 + Char.ToLower(str[i]); } Console.Write(str1); } // Driver Code static void Main() { string str = "I got intern at geeksforgeeks"; // Calling function convert(str); }} // This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program to convert given// sentence to snake case // Function to replace spaces// and convert into snake casefunction convert($str){ $n = strlen($str); for ($i = 0; $i < $n; $i++) { // Converting space // to underscore if ($str[$i] == ' ') $str[$i] = '_'; else // If not space, convert // into lower character $str[$i] = strtolower($str[$i]); } echo $str;} // Driver Code$str = "I got intern at geeksforgeeks"; // Calling functionconvert($str); // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script>// Javascript program to convert// given sentence to// snake case // Function to replace // spaces and convert // into snake case function convert (str) { let n = str.length; let str1 = ""; for ( i = 0; i < n; i++) { // Converting space // to underscore if (str[i] == ' ') str1 = str1 + '_'; else // If not space, convert // into lower letacter str1 = str1 + (str[i]).toLowerCase(); } document.write(str1); } // Driver Code let str = "I got letern at geeksforgeeks"; // Calling function convert(str); // This code is contributed by gauravrajput1</script>
Output :
i_got_intern_at_geeksforgeeks
YouTubeGeeksforGeeks500K subscribersSnake case of a given sentence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=DB1Cj72963Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
manishshaw1
Akanksha_Rai
ankthon
GauravRajput1
khushboogoyal499
varshagumber28
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Vigenère Cipher
Naive algorithm for Pattern Searching
Convert character array to string in C++
Reverse words in a given String in Python
How to Append a Character to a String in C
sprintf() in C
String class in Java | Set 1
Print all the duplicates in the input string | [
{
"code": null,
"e": 24772,
"s": 24744,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 24977,
"s": 24772,
"text": "Given a sentence, task is to remove spaces from the sentence and rewrite in Snake case. It is a style of writing where we replace spaces with underscore and all words begin with small letters.Examples : "
},
{
"code": null,
"e": 25117,
"s": 24977,
"text": "Input : I got intern at geeksforgeeks\nOutput : i_got_intern_at_geeksforgeeks\n\nInput : Here comes the garden\nOutput : here_comes_the_garden"
},
{
"code": null,
"e": 25513,
"s": 25119,
"text": "Simple solution : First method is to traverse sentence and one by one replace spaces by underscores and changing case of first character to small letter. It takes O(n*n) time.Efficient solution : We traverse given string, while traversing we replace space character with underscore and whenever we encounter non-space letter, we change that letter to small.Below is the code implementation : "
},
{
"code": null,
"e": 25517,
"s": 25513,
"text": "C++"
},
{
"code": null,
"e": 25522,
"s": 25517,
"text": "Java"
},
{
"code": null,
"e": 25530,
"s": 25522,
"text": "Python3"
},
{
"code": null,
"e": 25533,
"s": 25530,
"text": "C#"
},
{
"code": null,
"e": 25537,
"s": 25533,
"text": "PHP"
},
{
"code": null,
"e": 25548,
"s": 25537,
"text": "Javascript"
},
{
"code": "// CPP program to convert given sentence/// to snake case#include <bits/stdc++.h>using namespace std; // Function to replace spaces and convert// into snake casevoid convert(string str){ int n = str.length(); for (int i = 0; i < n; i++) { // Converting space to underscore if (str.at(i) == ' ') str.at(i) = '_'; else // If not space, convert into lower character str.at(i) = tolower(str.at(i)); } cout << str;} // Driver programint main(){ string str = \"I got intern at geeksforgeeks\"; // Calling function convert(str); return 0;}",
"e": 26166,
"s": 25548,
"text": null
},
{
"code": "// Java program to convert// given sentence to// snake caseimport java.io.*; class GFG{ // Function to replace// spaces and convert// into snake casestatic void convert(String str){ int n = str.length(); String str1 = \"\"; for (int i = 0; i < n; i++) { // Converting space // to underscore if (str.charAt(i) == ' ') str1 = str1 + '_'; else // If not space, convert // into lower character str1 = str1 + Character.toLowerCase(str.charAt(i)); } System.out.print(str1);} // Driver Codepublic static void main(String args[]){ String str = \"I got intern at geeksforgeeks\"; // Calling function convert(str);}} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 26972,
"s": 26166,
"text": null
},
{
"code": "# Python3 program to convert given sentence# to snake case # Function to replace spaces and convert# into snake casedef convert(string) : n = len(string); string = list(string); for i in range(n) : # Converting space to underscore if (string[i] == ' ') : string[i] = '_'; else : # If not space, convert # into lower character string[i] = string[i].lower(); string = \"\".join(string) print(string); # Driver programif __name__ == \"__main__\" : string = \"I got intern at geeksforgeeks\"; # Calling function convert(string); # This code is contributed by AnkitRai01",
"e": 27643,
"s": 26972,
"text": null
},
{
"code": "// C# program to convert// given sentence to// snake caseusing System; class GFG{ // Function to replace // spaces and convert // into snake case static void convert(string str) { int n = str.Length; string str1 = \"\"; for (int i = 0; i < n; i++) { // Converting space // to underscore if (str[i] == ' ') str1 = str1 + '_'; else // If not space, convert // into lower character str1 = str1 + Char.ToLower(str[i]); } Console.Write(str1); } // Driver Code static void Main() { string str = \"I got intern at geeksforgeeks\"; // Calling function convert(str); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 28521,
"s": 27643,
"text": null
},
{
"code": "<?php// PHP program to convert given// sentence to snake case // Function to replace spaces// and convert into snake casefunction convert($str){ $n = strlen($str); for ($i = 0; $i < $n; $i++) { // Converting space // to underscore if ($str[$i] == ' ') $str[$i] = '_'; else // If not space, convert // into lower character $str[$i] = strtolower($str[$i]); } echo $str;} // Driver Code$str = \"I got intern at geeksforgeeks\"; // Calling functionconvert($str); // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 29125,
"s": 28521,
"text": null
},
{
"code": "<script>// Javascript program to convert// given sentence to// snake case // Function to replace // spaces and convert // into snake case function convert (str) { let n = str.length; let str1 = \"\"; for ( i = 0; i < n; i++) { // Converting space // to underscore if (str[i] == ' ') str1 = str1 + '_'; else // If not space, convert // into lower letacter str1 = str1 + (str[i]).toLowerCase(); } document.write(str1); } // Driver Code let str = \"I got letern at geeksforgeeks\"; // Calling function convert(str); // This code is contributed by gauravrajput1</script>",
"e": 29876,
"s": 29125,
"text": null
},
{
"code": null,
"e": 29887,
"s": 29876,
"text": "Output : "
},
{
"code": null,
"e": 29917,
"s": 29887,
"text": "i_got_intern_at_geeksforgeeks"
},
{
"code": null,
"e": 30748,
"s": 29919,
"text": "YouTubeGeeksforGeeks500K subscribersSnake case of a given sentence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=DB1Cj72963Q\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 30762,
"s": 30750,
"text": "manishshaw1"
},
{
"code": null,
"e": 30775,
"s": 30762,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30783,
"s": 30775,
"text": "ankthon"
},
{
"code": null,
"e": 30797,
"s": 30783,
"text": "GauravRajput1"
},
{
"code": null,
"e": 30814,
"s": 30797,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 30829,
"s": 30814,
"text": "varshagumber28"
},
{
"code": null,
"e": 30837,
"s": 30829,
"text": "Strings"
},
{
"code": null,
"e": 30845,
"s": 30837,
"text": "Strings"
},
{
"code": null,
"e": 30943,
"s": 30845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30952,
"s": 30943,
"text": "Comments"
},
{
"code": null,
"e": 30965,
"s": 30952,
"text": "Old Comments"
},
{
"code": null,
"e": 31010,
"s": 30965,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31022,
"s": 31010,
"text": "Hill Cipher"
},
{
"code": null,
"e": 31039,
"s": 31022,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 31077,
"s": 31039,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 31118,
"s": 31077,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 31160,
"s": 31118,
"text": "Reverse words in a given String in Python"
},
{
"code": null,
"e": 31203,
"s": 31160,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 31218,
"s": 31203,
"text": "sprintf() in C"
},
{
"code": null,
"e": 31247,
"s": 31218,
"text": "String class in Java | Set 1"
}
] |
Get Current Time in different Timezone using Python - GeeksforGeeks | 29 Dec, 2020
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.In order to get the current time of different time zones, we will be using the pytz python library.
In order to get the local time, we can use the time module. Some important functions of the time module
localtime() – it helps to get the current local time
strftime(“%H:%M:%S”, t) – it helps to decide the format of the time to be used to display the time
In order to get the current time of a particular timezone there is a need to use the pytz Python library. Some of the important commands of pytz library are
utc – it helps to get the standard UTC time zone
timezone() – it helps to get the time zone of a particular location
now() – it helps to get the date, time, utc standard in default format
astimezone() – it helps to convert the time of a particular time zone into another time zone
Examples:
import time curr_time = time.localtime()curr_clock = time.strftime("%H:%M:%S", curr_time) print(curr_clock)
Output:
11:58:19
We will get the local current time of the region and the standard UTC timeExamples:
from datetime import datetimeimport pytz # get the standard UTC time UTC = pytz.utc # it will get the time zone # of the specified locationIST = pytz.timezone('Asia/Kolkata') # print the date and time in# standard formatprint("UTC in Default Format : ", datetime.now(UTC)) print("IST in Default Format : ", datetime.now(IST)) # print the date and time in # specified formatdatetime_utc = datetime.now(UTC)print("Date & Time in UTC : ", datetime_utc.strftime('%Y:%m:%d %H:%M:%S %Z %z')) datetime_ist = datetime.now(IST)print("Date & Time in IST : ", datetime_ist.strftime('%Y:%m:%d %H:%M:%S %Z %z'))
Output:
UTC in Default Format : 2020-03-31 07:15:59.640418+00:00
IST in Default Format : 2020-03-31 12:45:59.692642+05:30
Date & Time in UTC : 2020:03:31 07:15:59 UTC+0000
Date & Time in IST : 2020:03:31 12:45:59 IST+0530
Comparing the UTC and IST format of time zones of different regionsExamples:
from datetime import datetimeimport pytz UTC = pytz.utc timeZ_Kl = pytz.timezone('Asia/Kolkata') timeZ_Ny = pytz.timezone('America/New_York')timeZ_Ma = pytz.timezone('Africa/Maseru')timeZ_Ce = pytz.timezone('US/Central')timeZ_At = pytz.timezone('Europe/Athens') dt_Kl = datetime.now(timeZ_Kl)dt_Ny = datetime.now(timeZ_Ny)dt_Ma = datetime.now(timeZ_Ma)dt_Ce = datetime.now(timeZ_Ce)dt_At = datetime.now(timeZ_At) utc_Kl = dt_Kl.astimezone(UTC)utc_Ny = dt_Ny.astimezone(UTC)utc_Ma = dt_Ma.astimezone(UTC)utc_Ce = dt_Ce.astimezone(UTC)utc_At = dt_At.astimezone(UTC) print("UTC Format \t\t\t IST Format") print(utc_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z'), "\t ", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_Ny.strftime('%Y-%m-%d %H:%M:%S %Z %z'), "\t ", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_Ma.strftime('%Y-%m-%d %H:%M:%S %Z %z'), "\t ", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_Ce.strftime('%Y-%m-%d %H:%M:%S %Z %z'), "\t ", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_At.strftime('%Y-%m-%d %H:%M:%S %Z %z'), "\t ", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z'))
Output:
UTC Format IST Format
2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530
2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530
2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530
2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530
2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530
Thus we can conclude that although different regions have different regional time zones but when converted to the UTC time zone all of them gave same value. Thus we can say that
IST is +0530 hrs ahead of UTC
EDT is -0400 hrs before of UTC
SAST is +0200 hrs ahead of UTC
CDT is -0500 hrs before of UTC
EEST is +0300 hrs ahead of UTC
Python datetime-program
Python time-module
Python-datetime
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 24774,
"s": 24746,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 25141,
"s": 24774,
"text": "Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.In order to get the current time of different time zones, we will be using the pytz python library."
},
{
"code": null,
"e": 25245,
"s": 25141,
"text": "In order to get the local time, we can use the time module. Some important functions of the time module"
},
{
"code": null,
"e": 25298,
"s": 25245,
"text": "localtime() – it helps to get the current local time"
},
{
"code": null,
"e": 25397,
"s": 25298,
"text": "strftime(“%H:%M:%S”, t) – it helps to decide the format of the time to be used to display the time"
},
{
"code": null,
"e": 25554,
"s": 25397,
"text": "In order to get the current time of a particular timezone there is a need to use the pytz Python library. Some of the important commands of pytz library are"
},
{
"code": null,
"e": 25603,
"s": 25554,
"text": "utc – it helps to get the standard UTC time zone"
},
{
"code": null,
"e": 25671,
"s": 25603,
"text": "timezone() – it helps to get the time zone of a particular location"
},
{
"code": null,
"e": 25742,
"s": 25671,
"text": "now() – it helps to get the date, time, utc standard in default format"
},
{
"code": null,
"e": 25835,
"s": 25742,
"text": "astimezone() – it helps to convert the time of a particular time zone into another time zone"
},
{
"code": null,
"e": 25845,
"s": 25835,
"text": "Examples:"
},
{
"code": "import time curr_time = time.localtime()curr_clock = time.strftime(\"%H:%M:%S\", curr_time) print(curr_clock)",
"e": 25957,
"s": 25845,
"text": null
},
{
"code": null,
"e": 25965,
"s": 25957,
"text": "Output:"
},
{
"code": null,
"e": 25975,
"s": 25965,
"text": "11:58:19\n"
},
{
"code": null,
"e": 26059,
"s": 25975,
"text": "We will get the local current time of the region and the standard UTC timeExamples:"
},
{
"code": "from datetime import datetimeimport pytz # get the standard UTC time UTC = pytz.utc # it will get the time zone # of the specified locationIST = pytz.timezone('Asia/Kolkata') # print the date and time in# standard formatprint(\"UTC in Default Format : \", datetime.now(UTC)) print(\"IST in Default Format : \", datetime.now(IST)) # print the date and time in # specified formatdatetime_utc = datetime.now(UTC)print(\"Date & Time in UTC : \", datetime_utc.strftime('%Y:%m:%d %H:%M:%S %Z %z')) datetime_ist = datetime.now(IST)print(\"Date & Time in IST : \", datetime_ist.strftime('%Y:%m:%d %H:%M:%S %Z %z'))",
"e": 26687,
"s": 26059,
"text": null
},
{
"code": null,
"e": 26914,
"s": 26687,
"text": "Output:\nUTC in Default Format : 2020-03-31 07:15:59.640418+00:00\nIST in Default Format : 2020-03-31 12:45:59.692642+05:30\nDate & Time in UTC : 2020:03:31 07:15:59 UTC+0000\nDate & Time in IST : 2020:03:31 12:45:59 IST+0530\n"
},
{
"code": null,
"e": 26991,
"s": 26914,
"text": "Comparing the UTC and IST format of time zones of different regionsExamples:"
},
{
"code": "from datetime import datetimeimport pytz UTC = pytz.utc timeZ_Kl = pytz.timezone('Asia/Kolkata') timeZ_Ny = pytz.timezone('America/New_York')timeZ_Ma = pytz.timezone('Africa/Maseru')timeZ_Ce = pytz.timezone('US/Central')timeZ_At = pytz.timezone('Europe/Athens') dt_Kl = datetime.now(timeZ_Kl)dt_Ny = datetime.now(timeZ_Ny)dt_Ma = datetime.now(timeZ_Ma)dt_Ce = datetime.now(timeZ_Ce)dt_At = datetime.now(timeZ_At) utc_Kl = dt_Kl.astimezone(UTC)utc_Ny = dt_Ny.astimezone(UTC)utc_Ma = dt_Ma.astimezone(UTC)utc_Ce = dt_Ce.astimezone(UTC)utc_At = dt_At.astimezone(UTC) print(\"UTC Format \\t\\t\\t IST Format\") print(utc_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z'), \"\\t \", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_Ny.strftime('%Y-%m-%d %H:%M:%S %Z %z'), \"\\t \", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_Ma.strftime('%Y-%m-%d %H:%M:%S %Z %z'), \"\\t \", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_Ce.strftime('%Y-%m-%d %H:%M:%S %Z %z'), \"\\t \", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z')) print(utc_At.strftime('%Y-%m-%d %H:%M:%S %Z %z'), \"\\t \", dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z %z'))",
"e": 28154,
"s": 26991,
"text": null
},
{
"code": null,
"e": 28529,
"s": 28154,
"text": "Output:\nUTC Format IST Format\n2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530\n2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530\n2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530\n2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530\n2020-03-31 11:21:13 UTC +0000 2020-03-31 16:51:13 IST +0530\n"
},
{
"code": null,
"e": 28707,
"s": 28529,
"text": "Thus we can conclude that although different regions have different regional time zones but when converted to the UTC time zone all of them gave same value. Thus we can say that"
},
{
"code": null,
"e": 28737,
"s": 28707,
"text": "IST is +0530 hrs ahead of UTC"
},
{
"code": null,
"e": 28768,
"s": 28737,
"text": "EDT is -0400 hrs before of UTC"
},
{
"code": null,
"e": 28799,
"s": 28768,
"text": "SAST is +0200 hrs ahead of UTC"
},
{
"code": null,
"e": 28830,
"s": 28799,
"text": "CDT is -0500 hrs before of UTC"
},
{
"code": null,
"e": 28861,
"s": 28830,
"text": "EEST is +0300 hrs ahead of UTC"
},
{
"code": null,
"e": 28885,
"s": 28861,
"text": "Python datetime-program"
},
{
"code": null,
"e": 28904,
"s": 28885,
"text": "Python time-module"
},
{
"code": null,
"e": 28920,
"s": 28904,
"text": "Python-datetime"
},
{
"code": null,
"e": 28927,
"s": 28920,
"text": "Python"
},
{
"code": null,
"e": 28943,
"s": 28927,
"text": "Write From Home"
},
{
"code": null,
"e": 29041,
"s": 28943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29050,
"s": 29041,
"text": "Comments"
},
{
"code": null,
"e": 29063,
"s": 29050,
"text": "Old Comments"
},
{
"code": null,
"e": 29081,
"s": 29063,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29103,
"s": 29081,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29133,
"s": 29103,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29168,
"s": 29133,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29189,
"s": 29168,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 29225,
"s": 29189,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29261,
"s": 29225,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 29277,
"s": 29261,
"text": "Python infinity"
},
{
"code": null,
"e": 29338,
"s": 29277,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
HTML Window innerWidth Property | The HTML Window innerWidth property returns the width of the content area of a window in an HTML document.
Following is the syntax −
window.innerWidth
Let us see an example of HTML Window innerWidth Property −
Live Demo
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background-color: #8BC6EC;
background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);
text-align: center;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
.show {
font-size: 1.2rem;
}
</style>
<body>
<h1>HTML Window innerWidth Property</h1>
<button onclick="display()" class="btn">Show window inner width</button>
<div class="show"></div>
<script>
function display() {
document.querySelector('.show').innerHTML = 'Window inner width is: ' + window.innerWidth + "px";
}
</script>
</body>
</html>
Click on “Show window inner width” button to display the inner width of the content area: | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The HTML Window innerWidth property returns the width of the content area of a window in an HTML document."
},
{
"code": null,
"e": 1195,
"s": 1169,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1213,
"s": 1195,
"text": "window.innerWidth"
},
{
"code": null,
"e": 1272,
"s": 1213,
"text": "Let us see an example of HTML Window innerWidth Property −"
},
{
"code": null,
"e": 1283,
"s": 1272,
"text": " Live Demo"
},
{
"code": null,
"e": 2103,
"s": 1283,
"text": "<!DOCTYPE html>\n<html>\n<style>\n body {\n color: #000;\n height: 100vh;\n background-color: #8BC6EC;\n background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);\n text-align: center;\n }\n .btn {\n background: #db133a;\n border: none;\n height: 2rem;\n border-radius: 2px;\n width: 40%;\n display: block;\n color: #fff;\n outline: none;\n cursor: pointer;\n margin: 1rem auto;\n }\n .show {\n font-size: 1.2rem;\n }\n</style>\n<body>\n<h1>HTML Window innerWidth Property</h1>\n<button onclick=\"display()\" class=\"btn\">Show window inner width</button>\n<div class=\"show\"></div>\n<script>\n function display() {\n document.querySelector('.show').innerHTML = 'Window inner width is: ' + window.innerWidth + \"px\";\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2193,
"s": 2103,
"text": "Click on “Show window inner width” button to display the inner width of the content area:"
}
] |
How to set border width, border style, and border color in one declaration with JavaScript? | To set the border width, style, and color in a single declaration, use the border property in JavaScript.
You can try to run the following code to learn how to set border in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Set border</button>
<div id="box">
<p>Demo Text</p>
<p>Demo Text</p>
</div>
<script>
function display() {
document.getElementById("box").style.border = "thick dashed #000000";
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1168,
"s": 1062,
"text": "To set the border width, style, and color in a single declaration, use the border property in JavaScript."
},
{
"code": null,
"e": 1249,
"s": 1168,
"text": "You can try to run the following code to learn how to set border in JavaScript −"
},
{
"code": null,
"e": 1259,
"s": 1249,
"text": "Live Demo"
},
{
"code": null,
"e": 1605,
"s": 1259,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Set border</button>\n <div id=\"box\">\n <p>Demo Text</p>\n <p>Demo Text</p>\n </div>\n <script>\n function display() {\n document.getElementById(\"box\").style.border = \"thick dashed #000000\";\n }\n </script>\n </body>\n</html>"
}
] |
Difference between Runnable and Callable interface in java | Runnable and Callable both functional interface. Classes which are implementing these interfaces are designed to be executed by another thread.
Thread can be started with Ruunable and they are two ways to start a new thread: one is by subclassing Thread class and another is implementing Runnable interface.
Thread class does not have constructor for callable so we should use ExecutorService class for executing thread.
public class RunnableExample implements Runnable {
public void run() {
System.out.println("Hello from a Runnable!");
}
public static void main(String args[]) {
(new Thread(new RunnableExample())).start();
}
}
public class Main {
public static void main(String args[]) throws InterruptedException, ExecutionException {
ExecutorService services = Executors.newSingleThreadExecutor();
Future<?> future = services.submit(new Task());
System.out.println("In Future Object" + future.get());
}
}
import java.util.concurrent.Callable;
public class Task implements Callable {
@Override
public String call() throws Exception {
System.out.println("In call");
String name = "test";
return name;
}
} | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Runnable and Callable both functional interface. Classes which are implementing these interfaces are designed to be executed by another thread."
},
{
"code": null,
"e": 1370,
"s": 1206,
"text": "Thread can be started with Ruunable and they are two ways to start a new thread: one is by subclassing Thread class and another is implementing Runnable interface."
},
{
"code": null,
"e": 1484,
"s": 1370,
"text": "Thread class does not have constructor for callable so we should use ExecutorService class for executing thread."
},
{
"code": null,
"e": 1717,
"s": 1484,
"text": "public class RunnableExample implements Runnable {\n public void run() {\n System.out.println(\"Hello from a Runnable!\");\n }\n public static void main(String args[]) {\n (new Thread(new RunnableExample())).start();\n }\n}"
},
{
"code": null,
"e": 2248,
"s": 1717,
"text": "public class Main {\n public static void main(String args[]) throws InterruptedException, ExecutionException {\n ExecutorService services = Executors.newSingleThreadExecutor();\n Future<?> future = services.submit(new Task());\n System.out.println(\"In Future Object\" + future.get());\n }\n}\nimport java.util.concurrent.Callable;\n\npublic class Task implements Callable {\n\n @Override\n public String call() throws Exception {\n System.out.println(\"In call\");\n String name = \"test\";\n return name;\n }\n}"
}
] |
Unity - Introduction to Audio | There is a reason games put emphasis on audio; it is quite crucial to add aesthetic value to the game. From the very first Pong, one can hear beeps and boops from the ball hitting the paddles alternatingly. It was a really simple short square wave sample at the time, but what more could you want from the grandfather of all video games?
In real life, many things affect the way you perceive sound; the speed of the object, what type of scenario it is in, and what direction it is coming from.
There are a number of factors that can create unnecessary load on our engine. Instead, we try to create an idea of how our sound would work in our game, and build around that. This becomes especially prominent in 3D games, where there are 3 axes to deal with.
In Unity, we have dedicated components for audio perception and playback. These components work together to create a believable sound system that feels natural to the game.
Unity provides us with an array of useful tools and effects like reverb, the Doppler effect, real-time mixing and effects, etc. We will learn about these in our subsequent chapters.
In this section, we will learn about the 3 primary components related to audio in Unity.
The AudioSource component is the primary component that you will attach to a GameObject to make it play sound. It will play back an AudioClip when triggered through the mixer, through code or by default, when it awakes.
An AudioClip is simply a sound file that is loaded into an AudioSource. It can be any standard audio file, such as .mp3, .wav and so on. An AudioClip is a component within itself as well.
An AudioListener is the component that listens to all audio playing in the scene, and transfers it to the computer’s speakers. It acts like the ears of the game. All audio you hear is in perspective of the positioning of this AudioListener. Only one AudioListener should be in a scene for it to function properly. By default, the main camera has the Listener attached to it. The Listener doesn’t have any exposed properties that the designer would want to care about.
The output of an AudioSource or intake of an AudioListener can be modified with the help of Audio Filters. These are specific components that can change the reverb, chorus, filtering, and so on. Each specific filter comes as its own component with exposed values to tweak how it sounds.
Let us try making a button that plays a sound when it is clicked. To get started, we will Create a Circle sprite, and make it red.
Now, let us attach an Audio Source to this sprite.
For the object to play a sound, we have to give it one. Let us use this sound effect for our purpose.
http://www.orangefreesounds.com/ding-sfx/
Download the sound effect, and drag it into the Assets.
When Unity imports this asset as a sound file, it automatically is converted into an AudioClip. Therefore, you can drag this sound clip from the Assets directly onto the Audio Clip slot in our sprite’s Audio Source.
After you drag the sound clip from the Assets directly onto the Audio Clip slot in our sprite’s Audio Source, remember to unselect “Play on Awake” in the Audio Source properties; not doing so will make the sound play the moment the game starts.
Now, let us jump into our code. Create a new script called “BellSound” and open it up.
Since our Audio Source is controlled through code, we want to first get a reference to it. We will use the GetComponent method like before.
public class BellSound : MonoBehaviour {
AudioSource mySource;
// Use this for initialization
void Start () {
mySource = GetComponent<AudioSource>();
}
Now, let us set up the method to detect the object being clicked. MonoBehaviour gives us just the method we need for it, named OnMouseDown. The method is called whenever the mouse clicks in the range of a collider of that gameObject.
Since we have not attached a collider to our button yet, let us do so now.
We will not need a Rigidbody for this one; neither do we need to access this collider by code. It just has to be there for the method to work.
Let us test the method and see if it is working. Write the following code in your script, and attach it to the button.
void OnMouseDown() {
Debug.Log(“Clicked!”);
}
Once you save the script and attach it, play the game. Clicking on the button should spawn a message in the Console.
You are now one step away from playing the sound. All you have to do now is call the Play method in the Audio Source instance.
void OnMouseDown() {
mySource.Play();
}
Save your script, and run it in the game. Click on the button, and you should hear the sound play!
Note − Consider making a button that goes up in pitch every time you click on it. Use mySource.pitch and a counter and see if you can figure it out.)
119 Lectures
23.5 hours
Raja Biswas
58 Lectures
10 hours
Three Millennials
16 Lectures
1 hours
Peter Jepson
23 Lectures
2.5 hours
Zenva
21 Lectures
2 hours
Zenva
43 Lectures
9.5 hours
Raja Biswas
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2553,
"s": 2215,
"text": "There is a reason games put emphasis on audio; it is quite crucial to add aesthetic value to the game. From the very first Pong, one can hear beeps and boops from the ball hitting the paddles alternatingly. It was a really simple short square wave sample at the time, but what more could you want from the grandfather of all video games?"
},
{
"code": null,
"e": 2709,
"s": 2553,
"text": "In real life, many things affect the way you perceive sound; the speed of the object, what type of scenario it is in, and what direction it is coming from."
},
{
"code": null,
"e": 2969,
"s": 2709,
"text": "There are a number of factors that can create unnecessary load on our engine. Instead, we try to create an idea of how our sound would work in our game, and build around that. This becomes especially prominent in 3D games, where there are 3 axes to deal with."
},
{
"code": null,
"e": 3142,
"s": 2969,
"text": "In Unity, we have dedicated components for audio perception and playback. These components work together to create a believable sound system that feels natural to the game."
},
{
"code": null,
"e": 3324,
"s": 3142,
"text": "Unity provides us with an array of useful tools and effects like reverb, the Doppler effect, real-time mixing and effects, etc. We will learn about these in our subsequent chapters."
},
{
"code": null,
"e": 3413,
"s": 3324,
"text": "In this section, we will learn about the 3 primary components related to audio in Unity."
},
{
"code": null,
"e": 3633,
"s": 3413,
"text": "The AudioSource component is the primary component that you will attach to a GameObject to make it play sound. It will play back an AudioClip when triggered through the mixer, through code or by default, when it awakes."
},
{
"code": null,
"e": 3821,
"s": 3633,
"text": "An AudioClip is simply a sound file that is loaded into an AudioSource. It can be any standard audio file, such as .mp3, .wav and so on. An AudioClip is a component within itself as well."
},
{
"code": null,
"e": 4289,
"s": 3821,
"text": "An AudioListener is the component that listens to all audio playing in the scene, and transfers it to the computer’s speakers. It acts like the ears of the game. All audio you hear is in perspective of the positioning of this AudioListener. Only one AudioListener should be in a scene for it to function properly. By default, the main camera has the Listener attached to it. The Listener doesn’t have any exposed properties that the designer would want to care about."
},
{
"code": null,
"e": 4576,
"s": 4289,
"text": "The output of an AudioSource or intake of an AudioListener can be modified with the help of Audio Filters. These are specific components that can change the reverb, chorus, filtering, and so on. Each specific filter comes as its own component with exposed values to tweak how it sounds."
},
{
"code": null,
"e": 4707,
"s": 4576,
"text": "Let us try making a button that plays a sound when it is clicked. To get started, we will Create a Circle sprite, and make it red."
},
{
"code": null,
"e": 4758,
"s": 4707,
"text": "Now, let us attach an Audio Source to this sprite."
},
{
"code": null,
"e": 4860,
"s": 4758,
"text": "For the object to play a sound, we have to give it one. Let us use this sound effect for our purpose."
},
{
"code": null,
"e": 4902,
"s": 4860,
"text": "http://www.orangefreesounds.com/ding-sfx/"
},
{
"code": null,
"e": 4958,
"s": 4902,
"text": "Download the sound effect, and drag it into the Assets."
},
{
"code": null,
"e": 5174,
"s": 4958,
"text": "When Unity imports this asset as a sound file, it automatically is converted into an AudioClip. Therefore, you can drag this sound clip from the Assets directly onto the Audio Clip slot in our sprite’s Audio Source."
},
{
"code": null,
"e": 5419,
"s": 5174,
"text": "After you drag the sound clip from the Assets directly onto the Audio Clip slot in our sprite’s Audio Source, remember to unselect “Play on Awake” in the Audio Source properties; not doing so will make the sound play the moment the game starts."
},
{
"code": null,
"e": 5506,
"s": 5419,
"text": "Now, let us jump into our code. Create a new script called “BellSound” and open it up."
},
{
"code": null,
"e": 5646,
"s": 5506,
"text": "Since our Audio Source is controlled through code, we want to first get a reference to it. We will use the GetComponent method like before."
},
{
"code": null,
"e": 5813,
"s": 5646,
"text": "public class BellSound : MonoBehaviour {\n AudioSource mySource;\n // Use this for initialization\n void Start () {\n mySource = GetComponent<AudioSource>();\n}"
},
{
"code": null,
"e": 6047,
"s": 5813,
"text": "Now, let us set up the method to detect the object being clicked. MonoBehaviour gives us just the method we need for it, named OnMouseDown. The method is called whenever the mouse clicks in the range of a collider of that gameObject."
},
{
"code": null,
"e": 6122,
"s": 6047,
"text": "Since we have not attached a collider to our button yet, let us do so now."
},
{
"code": null,
"e": 6265,
"s": 6122,
"text": "We will not need a Rigidbody for this one; neither do we need to access this collider by code. It just has to be there for the method to work."
},
{
"code": null,
"e": 6384,
"s": 6265,
"text": "Let us test the method and see if it is working. Write the following code in your script, and attach it to the button."
},
{
"code": null,
"e": 6434,
"s": 6384,
"text": "void OnMouseDown() {\n Debug.Log(“Clicked!”);\n}\n"
},
{
"code": null,
"e": 6551,
"s": 6434,
"text": "Once you save the script and attach it, play the game. Clicking on the button should spawn a message in the Console."
},
{
"code": null,
"e": 6678,
"s": 6551,
"text": "You are now one step away from playing the sound. All you have to do now is call the Play method in the Audio Source instance."
},
{
"code": null,
"e": 6722,
"s": 6678,
"text": "void OnMouseDown() {\n mySource.Play();\n}\n"
},
{
"code": null,
"e": 6821,
"s": 6722,
"text": "Save your script, and run it in the game. Click on the button, and you should hear the sound play!"
},
{
"code": null,
"e": 6971,
"s": 6821,
"text": "Note − Consider making a button that goes up in pitch every time you click on it. Use mySource.pitch and a counter and see if you can figure it out.)"
},
{
"code": null,
"e": 7008,
"s": 6971,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 7021,
"s": 7008,
"text": " Raja Biswas"
},
{
"code": null,
"e": 7055,
"s": 7021,
"text": "\n 58 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7074,
"s": 7055,
"text": " Three Millennials"
},
{
"code": null,
"e": 7107,
"s": 7074,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7121,
"s": 7107,
"text": " Peter Jepson"
},
{
"code": null,
"e": 7156,
"s": 7121,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7163,
"s": 7156,
"text": " Zenva"
},
{
"code": null,
"e": 7196,
"s": 7163,
"text": "\n 21 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7203,
"s": 7196,
"text": " Zenva"
},
{
"code": null,
"e": 7238,
"s": 7203,
"text": "\n 43 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 7251,
"s": 7238,
"text": " Raja Biswas"
},
{
"code": null,
"e": 7258,
"s": 7251,
"text": " Print"
},
{
"code": null,
"e": 7269,
"s": 7258,
"text": " Add Notes"
}
] |
Find the smallest window in a string containing all characters of another string - GeeksforGeeks | 12 Oct, 2021
Given two strings, string1 and string2, the task is to find the smallest substring in string1 containing all characters of string2 efficiently.
Examples:
Input: string = “this is a test string”, pattern = “tist” Output: Minimum window is “t stri” Explanation: “t stri” contains all the characters of pattern.
Input: string = “geeksforgeeks”, pattern = “ork” Output: Minimum window is “ksfor”
Method 1 ( Brute force solution ) 1- Generate all substrings of string1 (“this is a test string”) 2- For each substring, check whether the substring contains all characters of string2 (“tist”) 3- Finally, print the smallest substring containing all characters of string2. Method 2 ( Efficient Solution )
First check if the length of the string is less than the length of the given pattern, if yes then “no such window can exist “.Store the occurrence of characters of the given pattern in a hash_pat[].we will be using two pointer technique basicallyStart matching the characters of pattern with the characters of string i.e. increment count if a character matches.Check if (count == length of pattern ) this means a window is found.If such a window found, try to minimize it by removing extra characters from the beginning of the current window.delete one character from first and again find this deleted key at right, once found apply step 5 .Update min_length.Print the minimum length window.
First check if the length of the string is less than the length of the given pattern, if yes then “no such window can exist “.
Store the occurrence of characters of the given pattern in a hash_pat[].
we will be using two pointer technique basically
Start matching the characters of pattern with the characters of string i.e. increment count if a character matches.
Check if (count == length of pattern ) this means a window is found.
If such a window found, try to minimize it by removing extra characters from the beginning of the current window.
delete one character from first and again find this deleted key at right, once found apply step 5 .
Update min_length.
Print the minimum length window.
A diagram to explain the stated algorithm:
after the second image(array) our left pointer should be at s and then find I at right and then apply step5 (basically one step has not been shown)
Below is the program to implement the above algorithm:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find// smallest window containing// all characters of a pattern.#include <bits/stdc++.h>using namespace std; const int no_of_chars = 256; // Function to find smallest// window containing// all characters of 'pat'string findSubString(string str, string pat){ int len1 = str.length(); int len2 = pat.length(); // Check if string's length // is less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { cout << "No such window exists"; return ""; } int hash_pat[no_of_chars] = { 0 }; int hash_str[no_of_chars] = { 0 }; // Store occurrence ofs characters // of pattern for (int i = 0; i < len2; i++) hash_pat[pat[i]]++; int start = 0, start_index = -1, min_len = INT_MAX; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str[j]]++; // If string's char matches with // pattern's char // then increment count if (hash_str[str[j]] <= hash_pat[str[j]]) count++; // if all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str[start]] > hash_pat[str[start]] || hash_pat[str[start]] == 0) { if (hash_str[str[start]] > hash_pat[str[start]]) hash_str[str[start]]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { cout << "No such window exists"; return ""; } // Return substring starting from start_index // and length min_len return str.substr(start_index, min_len);} // Driver codeint main(){ string str = "this is a test string"; string pat = "tist"; cout << "Smallest window is : \n" << findSubString(str, pat); return 0;}
// Java program to find smallest// window containing// all characters of a pattern. public class GFG { static final int no_of_chars = 256; // Function to find smallest // window containing // all characters of 'pat' static String findSubString(String str, String pat) { int len1 = str.length(); int len2 = pat.length(); // Check if string's length is // less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { System.out.println("No such window exists"); return ""; } int hash_pat[] = new int[no_of_chars]; int hash_str[] = new int[no_of_chars]; // Store occurrence ofs // characters of pattern for (int i = 0; i < len2; i++) hash_pat[pat.charAt(i)]++; int start = 0, start_index = -1, min_len = Integer.MAX_VALUE; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str.charAt(j)]++; // If string's char matches // with pattern's char // then increment count if (hash_str[str.charAt(j)] <= hash_pat[str.charAt(j)]) count++; // If all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str.charAt(start)] > hash_pat[str.charAt(start)] || hash_pat[str.charAt(start)] == 0) { if (hash_str[str.charAt(start)] > hash_pat[str.charAt(start)]) hash_str[str.charAt(start)]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { System.out.println("No such window exists"); return ""; } // Return substring starting // from start_index // and length min_len return str.substring(start_index, start_index + min_len); } // Driver Method public static void main(String[] args) { String str = "this is a test string"; String pat = "tist"; System.out.print("Smallest window is :\n " + findSubString(str, pat)); }}
# Python3 program to find the smallest window# containing all characters of a pattern.no_of_chars = 256 # Function to find smallest window# containing all characters of 'pat'def findSubString(string, pat): len1 = len(string) len2 = len(pat) # Check if string's length is # less than pattern's # length. If yes then no such # window can exist if len1 < len2: print("No such window exists") return "" hash_pat = [0] * no_of_chars hash_str = [0] * no_of_chars # Store occurrence ofs characters of pattern for i in range(0, len2): hash_pat[ord(pat[i])] += 1 start, start_index, min_len = 0, -1, float('inf') # Start traversing the string count = 0 # count of characters for j in range(0, len1): # count occurrence of characters of string hash_str[ord(string[j])] += 1 # If string's char matches with # pattern's char then increment count if (hash_str[ord(string[j])] <= hash_pat[ord(string[j])]): count += 1 # if all the characters are matched if count == len2: # Try to minimize the window while (hash_str[ord(string[start])] > hash_pat[ord(string[start])] or hash_pat[ord(string[start])] == 0): if (hash_str[ord(string[start])] > hash_pat[ord(string[start])]): hash_str[ord(string[start])] -= 1 start += 1 # update window size len_window = j - start + 1 if min_len > len_window: min_len = len_window start_index = start # If no window found if start_index == -1: print("No such window exists") return "" # Return substring starting from # start_index and length min_len return string[start_index: start_index + min_len] # Driver codeif __name__ == "__main__": string = "this is a test string" pat = "tist" print("Smallest window is : ") print(findSubString(string, pat)) # This code is contributed by Rituraj Jain
// C# program to find smallest// window containing// all characters of a pattern.using System; class GFG { static int no_of_chars = 256; // Function to find smallest // window containing // all characters of 'pat' static String findSubString(String str, String pat) { int len1 = str.Length; int len2 = pat.Length; // Check if string's length is // less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { Console.WriteLine("No such window exists"); return ""; } int[] hash_pat = new int[no_of_chars]; int[] hash_str = new int[no_of_chars]; // Store occurrence ofs characters // of pattern for (int i = 0; i < len2; i++) hash_pat[pat[i]]++; int start = 0, start_index = -1, min_len = int.MaxValue; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str[j]]++; // If string's char matches // with pattern's char // then increment count if (hash_str[str[j]] <= hash_pat[str[j]]) count++; // if all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str[start]] > hash_pat[str[start]] || hash_pat[str[start]] == 0) { if (hash_str[str[start]] > hash_pat[str[start]]) hash_str[str[start]]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { Console.WriteLine("No such window exists"); return ""; } // Return substring starting from start_index // and length min_len return str.Substring(start_index, min_len); } // Driver Method public static void Main(String[] args) { String str = "this is a test string"; String pat = "tist"; Console.WriteLine("Smallest window is :\n " + findSubString(str, pat)); }} /* This code contributed by PrinciRaj1992 */
<?php// PHP program to find smallest window// containing all characters of a pattern. define("no_of_chars", 256); // Function to find smallest window// containing all characters of 'pat'function findSubString(&$str, &$pat){ $len1 = strlen($str); $len2 = strlen($pat); // check if string's length is less // than pattern's length. If yes // then no such window can exist if ($len1 < $len2) { echo "No such window exists"; return ""; } $hash_pat = array_fill(0, no_of_chars, 0); $hash_str = array_fill(0, no_of_chars, 0); // store occurrence ofs characters // of pattern for ($i = 0; $i < $len2; $i++) $hash_pat[ord($pat[$i])]++; $start = 0; $start_index = -1; $min_len = PHP_INT_MAX; // start traversing the string $count = 0; // count of characters for ($j = 0; $j < $len1 ; $j++) { // count occurrence of characters // of string $hash_str[ord($str[$j])]++; // If string's char matches with // pattern's char then increment count if ($hash_str[ord($str[$j])] <= $hash_pat[ord($str[$j])]) $count++; // if all the characters are matched if ($count == $len2) { // Try to minimize the window i.e., // check if any character is occurring // more no. of times than its occurrence // in pattern, if yes then remove it from // starting and also remove the useless // characters. while ($hash_str[ord($str[$start])] > $hash_pat[ord($str[$start])] || $hash_pat[ord($str[$start])] == 0) { if ($hash_str[ord($str[$start])] > $hash_pat[ord($str[$start])]) $hash_str[ord($str[$start])]--; $start++; } // update window size $len_window = $j - $start + 1; if ($min_len > $len_window) { $min_len = $len_window; $start_index = $start; } } } // If no window found if ($start_index == -1) { echo "No such window exists"; return ""; } // Return substring starting from // start_index and length min_len return substr($str, $start_index, $min_len);} // Driver code$str = "this is a test string";$pat = "tist"; echo "Smallest window is : \n" . findSubString($str, $pat); // This code is contributed by// rathbhupendra?>
<script>// javascript program to find smallest// window containing// all characters of a pattern. var no_of_chars = 256; // Function to find smallest// window containing// all characters of 'pat'function findSubString(str, pat){ var len1 = str.length; var len2 = pat.length; // Check if string's length is // less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { document.write("No such window exists"); return ""; } var hash_pat = Array.from({length: no_of_chars}, (_, i) => 0); var hash_str = Array.from({length: no_of_chars}, (_, i) => 0); // Store occurrence ofs // characters of pattern for (var i = 0; i < len2; i++) hash_pat[pat.charAt(i).charCodeAt(0)]++; var start = 0, start_index = -1, min_len = Number.MAX_VALUE; // Start traversing the string // Count of characters var count = 0; for (var j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str.charAt(j).charCodeAt(0)]++; // If string's char matches // with pattern's char // then increment count if (hash_str[str.charAt(j).charCodeAt(0)] <= hash_pat[str.charAt(j).charCodeAt(0)]) count++; // If all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str.charAt(start).charCodeAt(0)] > hash_pat[str.charAt(start).charCodeAt(0)] || hash_pat[str.charAt(start).charCodeAt(0)] == 0) { if (hash_str[str.charAt(start).charCodeAt(0)] > hash_pat[str.charAt(start).charCodeAt(0)]) hash_str[str.charAt(start).charCodeAt(0)]--; start++; } // update window size var len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { document.write("No such window exists"); return ""; } // Return substring starting // from start_index // and length min_len return str.substring(start_index, start_index + min_len);} // Driver Methodvar str = "this is a test string";var pat = "tist"; document.write("Smallest window is :\n " + findSubString(str, pat));// This code is contributed by 29AjayKumar</script>
Smallest window is :
t stri
Method 3 (Efficient Solution)
(Using sliding window Technique )
C++14
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Functionstring Minimum_Window(string s, string t){ int m[256] = { 0 }; // Answer int ans = INT_MAX; // length of ans int start = 0; // starting index of ans int count = 0; // creating map for (int i = 0; i < t.length(); i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window int i = 0; int j = 0; // Traversing the window while (j < s.length()) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != INT_MAX) return s.substr(start, ans); else return "-1";} main(){ string s = "ADOBECODEBANC"; string t = "ABC"; cout<<"-->Smallest window that contain all character : "<<endl; cout << Minimum_Window(s, t);}
import java.util.*; class GFG{ // Functionstatic String Minimum_Window(char []s, char []t){ int m[] = new int[256]; // Answer int ans = Integer.MAX_VALUE; // length of ans int start = 0; // starting index of ans int count = 0; // creating map for (int i = 0; i < t.length; i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window int i = 0; int j = 0; // Traversing the window while (j < s.length) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = Math.min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != Integer.MAX_VALUE) return String.valueOf(s).substring(start, ans+start); else return "-1";} public static void main(String[] args){ String s = "ADOBECODEBANC"; String t = "ABC"; System.out.print("-->Smallest window that contain all character : "); System.out.print(Minimum_Window(s.toCharArray(), t.toCharArray())); }} // This code is contributed by 29AjayKumar
''' Python solution ''' def smallestWindow(s, p): n = len(s) if n < len(p): return -1 mp = [0]*256 # Starting index of ans start = 0 # Answer # Length of ans ans = n + 1 cnt = 0 # creating map for i in p: mp[ord(i)] += 1 if mp[ord(i)] == 1: cnt += 1 # References of Window j = 0 i = 0 # Traversing the window while(j < n): # Calculating mp[ord(s[j])] -= 1 if mp[ord(s[j])] == 0: cnt -= 1 # Condition matching while cnt == 0: if ans > j - i + 1: # calculating answer. ans = j - i + 1 start = i # Sliding I # Calculation for removing I mp[ord(s[i])] += 1 if mp[ord(s[i])] > 0: cnt += 1 i += 1 j += 1 if ans > n: return "-1" return s[start:start+ans] # Driver codeif __name__ == "__main__": s = "ADOBECODEBANC" p = "ABC" result = smallestWindow(s, p) print("-->Smallest window that contain all character :", result) # This code is contributed by cyclades.
using System; class GFG{ // Functionstatic String Minimum_Window(char []s, char []t){ int []m = new int[256]; // Answer // Length of ans int ans = int.MaxValue; // Starting index of ans int start = 0; int count = 0, i = 0; // Creating map for(i = 0; i < t.Length; i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window i = 0; int j = 0; // Traversing the window while (j < s.Length) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = Math.Min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != int.MaxValue) return String.Join("", s).Substring(start, ans); else return "-1";} // Driver codepublic static void Main(String[] args){ String s = "ADOBECODEBANC"; String t = "ABC"; Console.Write( "-->Smallest window that contain all character : "); Console.Write(Minimum_Window(s.ToCharArray(), t.ToCharArray()));}} // This code is contributed by 29AjayKumar
<script> // Functionfunction Minimum_Window(s,t){ let m = new Array(256); for(let i = 0; i < 256; i++) { m[i] = 0; } // Length of ans let ans = Number.MAX_VALUE; // Starting index of ans let start = 0; let count = 0; // Creating map for(let i = 0; i < t.length; i++) { if (m[t[i].charCodeAt(0)] == 0) count++; m[t[i].charCodeAt(0)]++; } // References of Window let i = 0; let j = 0; // Traversing the window while (j < s.length) { // Calculations m[s[j].charCodeAt(0)]--; if (m[s[j].charCodeAt(0)] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = Math.min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i].charCodeAt(0)]++; if (m[s[i].charCodeAt(0)] > 0) count++; i++; } } j++; } if (ans != Number.MAX_VALUE) return (s).join("").substring( start, (start + ans)); else return "-1";} // Driver codelet s = "ADOBECODEBANC";let t = "ABC";document.write("-->Smallest window that " + "contain all character : <br>");document.write(Minimum_Window( s.split(""), t.split(""))); // This code is contributed by rag2127 </script>
Output:
-->Smallest window that contain all character :
BANC
Time Complexity : O(|s|) , where |s| is the length of string s.
Space Complexity : O(1)
Explanation – Array m of length 256 is used ,which is constant space, so the Space Complexity is O(1).
This article is contributed by Sahil Chhabra. 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.
kamikaze101
Satyendra Kumar
rathbhupendra
princiraj1992
rituraj_jain
mazharalibaig
roshankumar9
divyeshvyas562
simmytarika5
29AjayKumar
rag2127
kapoorsagar226
cyclades
iramkhalid24
abhishekkumarsingh31
Amazon
Codenation
FactSet
MakeMyTrip
sliding-window
Streamoid Technologies
Hash
Strings
Amazon
FactSet
MakeMyTrip
Codenation
Streamoid Technologies
sliding-window
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Sort string of characters
Most frequent element in an array
Counting frequencies of array elements
Sorting a Map by value in C++ STL
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types | [
{
"code": null,
"e": 25140,
"s": 25112,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 25285,
"s": 25140,
"text": "Given two strings, string1 and string2, the task is to find the smallest substring in string1 containing all characters of string2 efficiently. "
},
{
"code": null,
"e": 25296,
"s": 25285,
"text": "Examples: "
},
{
"code": null,
"e": 25451,
"s": 25296,
"text": "Input: string = “this is a test string”, pattern = “tist” Output: Minimum window is “t stri” Explanation: “t stri” contains all the characters of pattern."
},
{
"code": null,
"e": 25534,
"s": 25451,
"text": "Input: string = “geeksforgeeks”, pattern = “ork” Output: Minimum window is “ksfor”"
},
{
"code": null,
"e": 25840,
"s": 25534,
"text": "Method 1 ( Brute force solution ) 1- Generate all substrings of string1 (“this is a test string”) 2- For each substring, check whether the substring contains all characters of string2 (“tist”) 3- Finally, print the smallest substring containing all characters of string2. Method 2 ( Efficient Solution ) "
},
{
"code": null,
"e": 26532,
"s": 25840,
"text": "First check if the length of the string is less than the length of the given pattern, if yes then “no such window can exist “.Store the occurrence of characters of the given pattern in a hash_pat[].we will be using two pointer technique basicallyStart matching the characters of pattern with the characters of string i.e. increment count if a character matches.Check if (count == length of pattern ) this means a window is found.If such a window found, try to minimize it by removing extra characters from the beginning of the current window.delete one character from first and again find this deleted key at right, once found apply step 5 .Update min_length.Print the minimum length window."
},
{
"code": null,
"e": 26659,
"s": 26532,
"text": "First check if the length of the string is less than the length of the given pattern, if yes then “no such window can exist “."
},
{
"code": null,
"e": 26732,
"s": 26659,
"text": "Store the occurrence of characters of the given pattern in a hash_pat[]."
},
{
"code": null,
"e": 26781,
"s": 26732,
"text": "we will be using two pointer technique basically"
},
{
"code": null,
"e": 26897,
"s": 26781,
"text": "Start matching the characters of pattern with the characters of string i.e. increment count if a character matches."
},
{
"code": null,
"e": 26966,
"s": 26897,
"text": "Check if (count == length of pattern ) this means a window is found."
},
{
"code": null,
"e": 27080,
"s": 26966,
"text": "If such a window found, try to minimize it by removing extra characters from the beginning of the current window."
},
{
"code": null,
"e": 27180,
"s": 27080,
"text": "delete one character from first and again find this deleted key at right, once found apply step 5 ."
},
{
"code": null,
"e": 27199,
"s": 27180,
"text": "Update min_length."
},
{
"code": null,
"e": 27232,
"s": 27199,
"text": "Print the minimum length window."
},
{
"code": null,
"e": 27275,
"s": 27232,
"text": "A diagram to explain the stated algorithm:"
},
{
"code": null,
"e": 27423,
"s": 27275,
"text": "after the second image(array) our left pointer should be at s and then find I at right and then apply step5 (basically one step has not been shown)"
},
{
"code": null,
"e": 27478,
"s": 27423,
"text": "Below is the program to implement the above algorithm:"
},
{
"code": null,
"e": 27482,
"s": 27478,
"text": "C++"
},
{
"code": null,
"e": 27487,
"s": 27482,
"text": "Java"
},
{
"code": null,
"e": 27495,
"s": 27487,
"text": "Python3"
},
{
"code": null,
"e": 27498,
"s": 27495,
"text": "C#"
},
{
"code": null,
"e": 27502,
"s": 27498,
"text": "PHP"
},
{
"code": null,
"e": 27513,
"s": 27502,
"text": "Javascript"
},
{
"code": "// C++ program to find// smallest window containing// all characters of a pattern.#include <bits/stdc++.h>using namespace std; const int no_of_chars = 256; // Function to find smallest// window containing// all characters of 'pat'string findSubString(string str, string pat){ int len1 = str.length(); int len2 = pat.length(); // Check if string's length // is less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { cout << \"No such window exists\"; return \"\"; } int hash_pat[no_of_chars] = { 0 }; int hash_str[no_of_chars] = { 0 }; // Store occurrence ofs characters // of pattern for (int i = 0; i < len2; i++) hash_pat[pat[i]]++; int start = 0, start_index = -1, min_len = INT_MAX; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str[j]]++; // If string's char matches with // pattern's char // then increment count if (hash_str[str[j]] <= hash_pat[str[j]]) count++; // if all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str[start]] > hash_pat[str[start]] || hash_pat[str[start]] == 0) { if (hash_str[str[start]] > hash_pat[str[start]]) hash_str[str[start]]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { cout << \"No such window exists\"; return \"\"; } // Return substring starting from start_index // and length min_len return str.substr(start_index, min_len);} // Driver codeint main(){ string str = \"this is a test string\"; string pat = \"tist\"; cout << \"Smallest window is : \\n\" << findSubString(str, pat); return 0;}",
"e": 29729,
"s": 27513,
"text": null
},
{
"code": "// Java program to find smallest// window containing// all characters of a pattern. public class GFG { static final int no_of_chars = 256; // Function to find smallest // window containing // all characters of 'pat' static String findSubString(String str, String pat) { int len1 = str.length(); int len2 = pat.length(); // Check if string's length is // less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { System.out.println(\"No such window exists\"); return \"\"; } int hash_pat[] = new int[no_of_chars]; int hash_str[] = new int[no_of_chars]; // Store occurrence ofs // characters of pattern for (int i = 0; i < len2; i++) hash_pat[pat.charAt(i)]++; int start = 0, start_index = -1, min_len = Integer.MAX_VALUE; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str.charAt(j)]++; // If string's char matches // with pattern's char // then increment count if (hash_str[str.charAt(j)] <= hash_pat[str.charAt(j)]) count++; // If all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str.charAt(start)] > hash_pat[str.charAt(start)] || hash_pat[str.charAt(start)] == 0) { if (hash_str[str.charAt(start)] > hash_pat[str.charAt(start)]) hash_str[str.charAt(start)]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { System.out.println(\"No such window exists\"); return \"\"; } // Return substring starting // from start_index // and length min_len return str.substring(start_index, start_index + min_len); } // Driver Method public static void main(String[] args) { String str = \"this is a test string\"; String pat = \"tist\"; System.out.print(\"Smallest window is :\\n \" + findSubString(str, pat)); }}",
"e": 32487,
"s": 29729,
"text": null
},
{
"code": "# Python3 program to find the smallest window# containing all characters of a pattern.no_of_chars = 256 # Function to find smallest window# containing all characters of 'pat'def findSubString(string, pat): len1 = len(string) len2 = len(pat) # Check if string's length is # less than pattern's # length. If yes then no such # window can exist if len1 < len2: print(\"No such window exists\") return \"\" hash_pat = [0] * no_of_chars hash_str = [0] * no_of_chars # Store occurrence ofs characters of pattern for i in range(0, len2): hash_pat[ord(pat[i])] += 1 start, start_index, min_len = 0, -1, float('inf') # Start traversing the string count = 0 # count of characters for j in range(0, len1): # count occurrence of characters of string hash_str[ord(string[j])] += 1 # If string's char matches with # pattern's char then increment count if (hash_str[ord(string[j])] <= hash_pat[ord(string[j])]): count += 1 # if all the characters are matched if count == len2: # Try to minimize the window while (hash_str[ord(string[start])] > hash_pat[ord(string[start])] or hash_pat[ord(string[start])] == 0): if (hash_str[ord(string[start])] > hash_pat[ord(string[start])]): hash_str[ord(string[start])] -= 1 start += 1 # update window size len_window = j - start + 1 if min_len > len_window: min_len = len_window start_index = start # If no window found if start_index == -1: print(\"No such window exists\") return \"\" # Return substring starting from # start_index and length min_len return string[start_index: start_index + min_len] # Driver codeif __name__ == \"__main__\": string = \"this is a test string\" pat = \"tist\" print(\"Smallest window is : \") print(findSubString(string, pat)) # This code is contributed by Rituraj Jain",
"e": 34594,
"s": 32487,
"text": null
},
{
"code": "// C# program to find smallest// window containing// all characters of a pattern.using System; class GFG { static int no_of_chars = 256; // Function to find smallest // window containing // all characters of 'pat' static String findSubString(String str, String pat) { int len1 = str.Length; int len2 = pat.Length; // Check if string's length is // less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { Console.WriteLine(\"No such window exists\"); return \"\"; } int[] hash_pat = new int[no_of_chars]; int[] hash_str = new int[no_of_chars]; // Store occurrence ofs characters // of pattern for (int i = 0; i < len2; i++) hash_pat[pat[i]]++; int start = 0, start_index = -1, min_len = int.MaxValue; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str[j]]++; // If string's char matches // with pattern's char // then increment count if (hash_str[str[j]] <= hash_pat[str[j]]) count++; // if all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str[start]] > hash_pat[str[start]] || hash_pat[str[start]] == 0) { if (hash_str[str[start]] > hash_pat[str[start]]) hash_str[str[start]]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { Console.WriteLine(\"No such window exists\"); return \"\"; } // Return substring starting from start_index // and length min_len return str.Substring(start_index, min_len); } // Driver Method public static void Main(String[] args) { String str = \"this is a test string\"; String pat = \"tist\"; Console.WriteLine(\"Smallest window is :\\n \" + findSubString(str, pat)); }} /* This code contributed by PrinciRaj1992 */",
"e": 37251,
"s": 34594,
"text": null
},
{
"code": "<?php// PHP program to find smallest window// containing all characters of a pattern. define(\"no_of_chars\", 256); // Function to find smallest window// containing all characters of 'pat'function findSubString(&$str, &$pat){ $len1 = strlen($str); $len2 = strlen($pat); // check if string's length is less // than pattern's length. If yes // then no such window can exist if ($len1 < $len2) { echo \"No such window exists\"; return \"\"; } $hash_pat = array_fill(0, no_of_chars, 0); $hash_str = array_fill(0, no_of_chars, 0); // store occurrence ofs characters // of pattern for ($i = 0; $i < $len2; $i++) $hash_pat[ord($pat[$i])]++; $start = 0; $start_index = -1; $min_len = PHP_INT_MAX; // start traversing the string $count = 0; // count of characters for ($j = 0; $j < $len1 ; $j++) { // count occurrence of characters // of string $hash_str[ord($str[$j])]++; // If string's char matches with // pattern's char then increment count if ($hash_str[ord($str[$j])] <= $hash_pat[ord($str[$j])]) $count++; // if all the characters are matched if ($count == $len2) { // Try to minimize the window i.e., // check if any character is occurring // more no. of times than its occurrence // in pattern, if yes then remove it from // starting and also remove the useless // characters. while ($hash_str[ord($str[$start])] > $hash_pat[ord($str[$start])] || $hash_pat[ord($str[$start])] == 0) { if ($hash_str[ord($str[$start])] > $hash_pat[ord($str[$start])]) $hash_str[ord($str[$start])]--; $start++; } // update window size $len_window = $j - $start + 1; if ($min_len > $len_window) { $min_len = $len_window; $start_index = $start; } } } // If no window found if ($start_index == -1) { echo \"No such window exists\"; return \"\"; } // Return substring starting from // start_index and length min_len return substr($str, $start_index, $min_len);} // Driver code$str = \"this is a test string\";$pat = \"tist\"; echo \"Smallest window is : \\n\" . findSubString($str, $pat); // This code is contributed by// rathbhupendra?>",
"e": 39769,
"s": 37251,
"text": null
},
{
"code": "<script>// javascript program to find smallest// window containing// all characters of a pattern. var no_of_chars = 256; // Function to find smallest// window containing// all characters of 'pat'function findSubString(str, pat){ var len1 = str.length; var len2 = pat.length; // Check if string's length is // less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { document.write(\"No such window exists\"); return \"\"; } var hash_pat = Array.from({length: no_of_chars}, (_, i) => 0); var hash_str = Array.from({length: no_of_chars}, (_, i) => 0); // Store occurrence ofs // characters of pattern for (var i = 0; i < len2; i++) hash_pat[pat.charAt(i).charCodeAt(0)]++; var start = 0, start_index = -1, min_len = Number.MAX_VALUE; // Start traversing the string // Count of characters var count = 0; for (var j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str.charAt(j).charCodeAt(0)]++; // If string's char matches // with pattern's char // then increment count if (hash_str[str.charAt(j).charCodeAt(0)] <= hash_pat[str.charAt(j).charCodeAt(0)]) count++; // If all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str.charAt(start).charCodeAt(0)] > hash_pat[str.charAt(start).charCodeAt(0)] || hash_pat[str.charAt(start).charCodeAt(0)] == 0) { if (hash_str[str.charAt(start).charCodeAt(0)] > hash_pat[str.charAt(start).charCodeAt(0)]) hash_str[str.charAt(start).charCodeAt(0)]--; start++; } // update window size var len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { document.write(\"No such window exists\"); return \"\"; } // Return substring starting // from start_index // and length min_len return str.substring(start_index, start_index + min_len);} // Driver Methodvar str = \"this is a test string\";var pat = \"tist\"; document.write(\"Smallest window is :\\n \" + findSubString(str, pat));// This code is contributed by 29AjayKumar</script>",
"e": 42340,
"s": 39769,
"text": null
},
{
"code": null,
"e": 42369,
"s": 42340,
"text": "Smallest window is : \nt stri"
},
{
"code": null,
"e": 42399,
"s": 42369,
"text": "Method 3 (Efficient Solution)"
},
{
"code": null,
"e": 42434,
"s": 42399,
"text": "(Using sliding window Technique )"
},
{
"code": null,
"e": 42440,
"s": 42434,
"text": "C++14"
},
{
"code": null,
"e": 42445,
"s": 42440,
"text": "Java"
},
{
"code": null,
"e": 42453,
"s": 42445,
"text": "Python3"
},
{
"code": null,
"e": 42456,
"s": 42453,
"text": "C#"
},
{
"code": null,
"e": 42467,
"s": 42456,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Functionstring Minimum_Window(string s, string t){ int m[256] = { 0 }; // Answer int ans = INT_MAX; // length of ans int start = 0; // starting index of ans int count = 0; // creating map for (int i = 0; i < t.length(); i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window int i = 0; int j = 0; // Traversing the window while (j < s.length()) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != INT_MAX) return s.substr(start, ans); else return \"-1\";} main(){ string s = \"ADOBECODEBANC\"; string t = \"ABC\"; cout<<\"-->Smallest window that contain all character : \"<<endl; cout << Minimum_Window(s, t);}",
"e": 43760,
"s": 42467,
"text": null
},
{
"code": "import java.util.*; class GFG{ // Functionstatic String Minimum_Window(char []s, char []t){ int m[] = new int[256]; // Answer int ans = Integer.MAX_VALUE; // length of ans int start = 0; // starting index of ans int count = 0; // creating map for (int i = 0; i < t.length; i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window int i = 0; int j = 0; // Traversing the window while (j < s.length) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = Math.min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != Integer.MAX_VALUE) return String.valueOf(s).substring(start, ans+start); else return \"-1\";} public static void main(String[] args){ String s = \"ADOBECODEBANC\"; String t = \"ABC\"; System.out.print(\"-->Smallest window that contain all character : \"); System.out.print(Minimum_Window(s.toCharArray(), t.toCharArray())); }} // This code is contributed by 29AjayKumar",
"e": 45286,
"s": 43760,
"text": null
},
{
"code": "''' Python solution ''' def smallestWindow(s, p): n = len(s) if n < len(p): return -1 mp = [0]*256 # Starting index of ans start = 0 # Answer # Length of ans ans = n + 1 cnt = 0 # creating map for i in p: mp[ord(i)] += 1 if mp[ord(i)] == 1: cnt += 1 # References of Window j = 0 i = 0 # Traversing the window while(j < n): # Calculating mp[ord(s[j])] -= 1 if mp[ord(s[j])] == 0: cnt -= 1 # Condition matching while cnt == 0: if ans > j - i + 1: # calculating answer. ans = j - i + 1 start = i # Sliding I # Calculation for removing I mp[ord(s[i])] += 1 if mp[ord(s[i])] > 0: cnt += 1 i += 1 j += 1 if ans > n: return \"-1\" return s[start:start+ans] # Driver codeif __name__ == \"__main__\": s = \"ADOBECODEBANC\" p = \"ABC\" result = smallestWindow(s, p) print(\"-->Smallest window that contain all character :\", result) # This code is contributed by cyclades.",
"e": 46577,
"s": 45286,
"text": null
},
{
"code": "using System; class GFG{ // Functionstatic String Minimum_Window(char []s, char []t){ int []m = new int[256]; // Answer // Length of ans int ans = int.MaxValue; // Starting index of ans int start = 0; int count = 0, i = 0; // Creating map for(i = 0; i < t.Length; i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window i = 0; int j = 0; // Traversing the window while (j < s.Length) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = Math.Min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != int.MaxValue) return String.Join(\"\", s).Substring(start, ans); else return \"-1\";} // Driver codepublic static void Main(String[] args){ String s = \"ADOBECODEBANC\"; String t = \"ABC\"; Console.Write( \"-->Smallest window that contain all character : \"); Console.Write(Minimum_Window(s.ToCharArray(), t.ToCharArray()));}} // This code is contributed by 29AjayKumar",
"e": 48184,
"s": 46577,
"text": null
},
{
"code": "<script> // Functionfunction Minimum_Window(s,t){ let m = new Array(256); for(let i = 0; i < 256; i++) { m[i] = 0; } // Length of ans let ans = Number.MAX_VALUE; // Starting index of ans let start = 0; let count = 0; // Creating map for(let i = 0; i < t.length; i++) { if (m[t[i].charCodeAt(0)] == 0) count++; m[t[i].charCodeAt(0)]++; } // References of Window let i = 0; let j = 0; // Traversing the window while (j < s.length) { // Calculations m[s[j].charCodeAt(0)]--; if (m[s[j].charCodeAt(0)] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = Math.min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i].charCodeAt(0)]++; if (m[s[i].charCodeAt(0)] > 0) count++; i++; } } j++; } if (ans != Number.MAX_VALUE) return (s).join(\"\").substring( start, (start + ans)); else return \"-1\";} // Driver codelet s = \"ADOBECODEBANC\";let t = \"ABC\";document.write(\"-->Smallest window that \" + \"contain all character : <br>\");document.write(Minimum_Window( s.split(\"\"), t.split(\"\"))); // This code is contributed by rag2127 </script>",
"e": 49838,
"s": 48184,
"text": null
},
{
"code": null,
"e": 49846,
"s": 49838,
"text": "Output:"
},
{
"code": null,
"e": 49900,
"s": 49846,
"text": "-->Smallest window that contain all character : \nBANC"
},
{
"code": null,
"e": 49967,
"s": 49900,
"text": "Time Complexity : O(|s|) , where |s| is the length of string s. "
},
{
"code": null,
"e": 49993,
"s": 49967,
"text": "Space Complexity : O(1) "
},
{
"code": null,
"e": 50100,
"s": 49993,
"text": "Explanation – Array m of length 256 is used ,which is constant space, so the Space Complexity is O(1). "
},
{
"code": null,
"e": 50522,
"s": 50100,
"text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 50534,
"s": 50522,
"text": "kamikaze101"
},
{
"code": null,
"e": 50550,
"s": 50534,
"text": "Satyendra Kumar"
},
{
"code": null,
"e": 50564,
"s": 50550,
"text": "rathbhupendra"
},
{
"code": null,
"e": 50578,
"s": 50564,
"text": "princiraj1992"
},
{
"code": null,
"e": 50591,
"s": 50578,
"text": "rituraj_jain"
},
{
"code": null,
"e": 50605,
"s": 50591,
"text": "mazharalibaig"
},
{
"code": null,
"e": 50618,
"s": 50605,
"text": "roshankumar9"
},
{
"code": null,
"e": 50633,
"s": 50618,
"text": "divyeshvyas562"
},
{
"code": null,
"e": 50646,
"s": 50633,
"text": "simmytarika5"
},
{
"code": null,
"e": 50658,
"s": 50646,
"text": "29AjayKumar"
},
{
"code": null,
"e": 50666,
"s": 50658,
"text": "rag2127"
},
{
"code": null,
"e": 50681,
"s": 50666,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 50690,
"s": 50681,
"text": "cyclades"
},
{
"code": null,
"e": 50703,
"s": 50690,
"text": "iramkhalid24"
},
{
"code": null,
"e": 50724,
"s": 50703,
"text": "abhishekkumarsingh31"
},
{
"code": null,
"e": 50731,
"s": 50724,
"text": "Amazon"
},
{
"code": null,
"e": 50742,
"s": 50731,
"text": "Codenation"
},
{
"code": null,
"e": 50750,
"s": 50742,
"text": "FactSet"
},
{
"code": null,
"e": 50761,
"s": 50750,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 50776,
"s": 50761,
"text": "sliding-window"
},
{
"code": null,
"e": 50799,
"s": 50776,
"text": "Streamoid Technologies"
},
{
"code": null,
"e": 50804,
"s": 50799,
"text": "Hash"
},
{
"code": null,
"e": 50812,
"s": 50804,
"text": "Strings"
},
{
"code": null,
"e": 50819,
"s": 50812,
"text": "Amazon"
},
{
"code": null,
"e": 50827,
"s": 50819,
"text": "FactSet"
},
{
"code": null,
"e": 50838,
"s": 50827,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 50849,
"s": 50838,
"text": "Codenation"
},
{
"code": null,
"e": 50872,
"s": 50849,
"text": "Streamoid Technologies"
},
{
"code": null,
"e": 50887,
"s": 50872,
"text": "sliding-window"
},
{
"code": null,
"e": 50892,
"s": 50887,
"text": "Hash"
},
{
"code": null,
"e": 50900,
"s": 50892,
"text": "Strings"
},
{
"code": null,
"e": 50998,
"s": 50900,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51034,
"s": 50998,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 51060,
"s": 51034,
"text": "Sort string of characters"
},
{
"code": null,
"e": 51094,
"s": 51060,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 51133,
"s": 51094,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 51167,
"s": 51133,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 51192,
"s": 51167,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 51238,
"s": 51192,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 51272,
"s": 51238,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 51332,
"s": 51272,
"text": "Write a program to print all permutations of a given string"
}
] |
Count of elements that are Kth powers of their indices in given Array - GeeksforGeeks | 02 Feb, 2022
Given an array arr[] with N non-negative integers, the task is to find the number of elements that are Kth powers of their indices, where K is a non-negative number.
arr[i] = iK
Example:
Input: arr = [1, 1, 4, 3, 16, 125, 1], K = 0Output: 3Explanation: 3 elements are Kth powers of their indices:00 is 1, 10 is 1, and 60 is 1
Input: arr = [0, 1, 4, 3], K = 2Output: 2Explanation: 02 is 0, 12 is 1, and 22 is 4
Approach: Given problem can be solved by finding the Kth powers of every index and checking if they are equal to the element present at that index. Follow the steps below to solve the problem:
Initialize a variable res to 0 for storing the answer
If the value of K is 0:If the first element in the array arr exists and is equal to 1 then increment res by 1
If the first element in the array arr exists and is equal to 1 then increment res by 1
Else if the value of K is greater than 0:If the first element in the array arr exists and is equal to 0 then increment res by 1
If the first element in the array arr exists and is equal to 0 then increment res by 1
If the second element in the array arr exists and is equal to 1 then increment res by 1
Iterate the array arr from index 2 till the end and at every index:Initialize a variable indPow to the current index i and multiply it by i, k-1 timesIf the value of indPow becomes equal to the current element arr[i] then increment res by 1
Initialize a variable indPow to the current index i and multiply it by i, k-1 times
If the value of indPow becomes equal to the current element arr[i] then increment res by 1
Return res as our answer
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find count of elements which// are a non-negative power of their indicesint indPowEqualsEle(vector<int> arr, int K){ // Length of the array int len = arr.size(); // Initialize variable res for // calculating the answer int res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (int i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times long indPow = i; for (int j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res;} // Driver functionint main(){ // Initialize an array vector<int> arr = {1, 1, 4, 3, 16, 125, 1}; // Initialize power int K = 0; // Call the function // and print the answer cout << (indPowEqualsEle(arr, K)); return 0;} // This code is contributed by Potta Lokesh
// Java implementation for the above approach import java.io.*;import java.util.*; class GFG { // Function to find count of elements which // are a non-negative power of their indices public static int indPowEqualsEle(int[] arr, int K) { // Length of the array int len = arr.length; // Initialize variable res for // calculating the answer int res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (int i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times long indPow = i; for (int j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res; } // Driver function public static void main(String[] args) { // Initialize an array int[] arr = { 1, 1, 4, 3, 16, 125, 1 }; // Initialize power int K = 0; // Call the function // and print the answer System.out.println( indPowEqualsEle(arr, K)); }}
# python code for the above approach # Function to find count of elements which# are a non-negative power of their indicesdef indPowEqualsEle(arr, K): # Length of the array le = len(arr) # Initialize variable res for # calculating the answer res = 0 # If the value of K is 0 if (K == 0): # If the first element is 1 # then the condition is satisfied if (le > 0 and arr[0] == 1): res += 1 # If the value of K > 0 if (K > 0): # If the first is 0 increment res if (le > 0 and arr[0] == 1): res += 1 # If the second element is 1 # then increment res if (le > 1 and arr[1] == 1): res += 1 # Iterate the array arr from index 2 for i in range(2, le): # Initialize a variable # to index which is to be # multiplied K-1 times indPow = i for j in range(2, K): # Multiply current value # with index K - 1 times indPow *= i # If index power K is equal to # the element then increment res if (indPow == arr[i]): res += 1 # return the result return res # Driver functionif __name__ == "__main__": # Initialize an array arr = [1, 1, 4, 3, 16, 125, 1] # Initialize power K = 0 # Call the function # and print the answer print(indPowEqualsEle(arr, K)) # This code is contributed by rakeshsahni
// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to find count of elements which// are a non-negative power of their indicesstatic int indPowEqualsEle(int []arr, int K){ // Length of the array int len = arr.Length; // Initialize variable res for // calculating the answer int res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (int i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times long indPow = i; for (int j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res;} // Driver Codepublic static void Main(){ // Initialize an array int []arr = {1, 1, 4, 3, 16, 125, 1}; // Initialize power int K = 0; // Call the function // and print the answer Console.Write(indPowEqualsEle(arr, K));}} // This code is contributed by Samim Hossain Mondal
//<script>// Javascript program for the above approach // Function to find count of elements which// are a non-negative power of their indicesfunction indPowEqualsEle(arr, K){ // Length of the array let len = arr.length; // Initialize variable res for // calculating the answer let res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (let i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times let indPow = i; for (let j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res;} // Driver Code// Initialize an arraylet arr = [ 1, 1, 4, 3, 16, 125, 1 ]; // Initialize powerlet K = 0; // Call the function// and print the answerdocument.write(indPowEqualsEle(arr, K)); // This code is contributed by Samim Hossain Mondal</script>
3
Time Complexity: O(N * K)Auxiliary Space: O(1)
lokeshpotta20
rakeshsahni
samim2000
sumitgumber28
maths-power
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Trapping Rain Water
Building Heap from Array
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 24962,
"s": 24796,
"text": "Given an array arr[] with N non-negative integers, the task is to find the number of elements that are Kth powers of their indices, where K is a non-negative number."
},
{
"code": null,
"e": 24975,
"s": 24962,
"text": "arr[i] = iK "
},
{
"code": null,
"e": 24984,
"s": 24975,
"text": "Example:"
},
{
"code": null,
"e": 25123,
"s": 24984,
"text": "Input: arr = [1, 1, 4, 3, 16, 125, 1], K = 0Output: 3Explanation: 3 elements are Kth powers of their indices:00 is 1, 10 is 1, and 60 is 1"
},
{
"code": null,
"e": 25207,
"s": 25123,
"text": "Input: arr = [0, 1, 4, 3], K = 2Output: 2Explanation: 02 is 0, 12 is 1, and 22 is 4"
},
{
"code": null,
"e": 25400,
"s": 25207,
"text": "Approach: Given problem can be solved by finding the Kth powers of every index and checking if they are equal to the element present at that index. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25454,
"s": 25400,
"text": "Initialize a variable res to 0 for storing the answer"
},
{
"code": null,
"e": 25564,
"s": 25454,
"text": "If the value of K is 0:If the first element in the array arr exists and is equal to 1 then increment res by 1"
},
{
"code": null,
"e": 25651,
"s": 25564,
"text": "If the first element in the array arr exists and is equal to 1 then increment res by 1"
},
{
"code": null,
"e": 25779,
"s": 25651,
"text": "Else if the value of K is greater than 0:If the first element in the array arr exists and is equal to 0 then increment res by 1"
},
{
"code": null,
"e": 25866,
"s": 25779,
"text": "If the first element in the array arr exists and is equal to 0 then increment res by 1"
},
{
"code": null,
"e": 25954,
"s": 25866,
"text": "If the second element in the array arr exists and is equal to 1 then increment res by 1"
},
{
"code": null,
"e": 26195,
"s": 25954,
"text": "Iterate the array arr from index 2 till the end and at every index:Initialize a variable indPow to the current index i and multiply it by i, k-1 timesIf the value of indPow becomes equal to the current element arr[i] then increment res by 1"
},
{
"code": null,
"e": 26279,
"s": 26195,
"text": "Initialize a variable indPow to the current index i and multiply it by i, k-1 times"
},
{
"code": null,
"e": 26370,
"s": 26279,
"text": "If the value of indPow becomes equal to the current element arr[i] then increment res by 1"
},
{
"code": null,
"e": 26395,
"s": 26370,
"text": "Return res as our answer"
},
{
"code": null,
"e": 26447,
"s": 26395,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26451,
"s": 26447,
"text": "C++"
},
{
"code": null,
"e": 26456,
"s": 26451,
"text": "Java"
},
{
"code": null,
"e": 26464,
"s": 26456,
"text": "Python3"
},
{
"code": null,
"e": 26467,
"s": 26464,
"text": "C#"
},
{
"code": null,
"e": 26478,
"s": 26467,
"text": "Javascript"
},
{
"code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find count of elements which// are a non-negative power of their indicesint indPowEqualsEle(vector<int> arr, int K){ // Length of the array int len = arr.size(); // Initialize variable res for // calculating the answer int res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (int i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times long indPow = i; for (int j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res;} // Driver functionint main(){ // Initialize an array vector<int> arr = {1, 1, 4, 3, 16, 125, 1}; // Initialize power int K = 0; // Call the function // and print the answer cout << (indPowEqualsEle(arr, K)); return 0;} // This code is contributed by Potta Lokesh",
"e": 28080,
"s": 26478,
"text": null
},
{
"code": "// Java implementation for the above approach import java.io.*;import java.util.*; class GFG { // Function to find count of elements which // are a non-negative power of their indices public static int indPowEqualsEle(int[] arr, int K) { // Length of the array int len = arr.length; // Initialize variable res for // calculating the answer int res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (int i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times long indPow = i; for (int j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res; } // Driver function public static void main(String[] args) { // Initialize an array int[] arr = { 1, 1, 4, 3, 16, 125, 1 }; // Initialize power int K = 0; // Call the function // and print the answer System.out.println( indPowEqualsEle(arr, K)); }}",
"e": 29906,
"s": 28080,
"text": null
},
{
"code": "# python code for the above approach # Function to find count of elements which# are a non-negative power of their indicesdef indPowEqualsEle(arr, K): # Length of the array le = len(arr) # Initialize variable res for # calculating the answer res = 0 # If the value of K is 0 if (K == 0): # If the first element is 1 # then the condition is satisfied if (le > 0 and arr[0] == 1): res += 1 # If the value of K > 0 if (K > 0): # If the first is 0 increment res if (le > 0 and arr[0] == 1): res += 1 # If the second element is 1 # then increment res if (le > 1 and arr[1] == 1): res += 1 # Iterate the array arr from index 2 for i in range(2, le): # Initialize a variable # to index which is to be # multiplied K-1 times indPow = i for j in range(2, K): # Multiply current value # with index K - 1 times indPow *= i # If index power K is equal to # the element then increment res if (indPow == arr[i]): res += 1 # return the result return res # Driver functionif __name__ == \"__main__\": # Initialize an array arr = [1, 1, 4, 3, 16, 125, 1] # Initialize power K = 0 # Call the function # and print the answer print(indPowEqualsEle(arr, K)) # This code is contributed by rakeshsahni",
"e": 31333,
"s": 29906,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to find count of elements which// are a non-negative power of their indicesstatic int indPowEqualsEle(int []arr, int K){ // Length of the array int len = arr.Length; // Initialize variable res for // calculating the answer int res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (int i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times long indPow = i; for (int j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res;} // Driver Codepublic static void Main(){ // Initialize an array int []arr = {1, 1, 4, 3, 16, 125, 1}; // Initialize power int K = 0; // Call the function // and print the answer Console.Write(indPowEqualsEle(arr, K));}} // This code is contributed by Samim Hossain Mondal",
"e": 32953,
"s": 31333,
"text": null
},
{
"code": "//<script>// Javascript program for the above approach // Function to find count of elements which// are a non-negative power of their indicesfunction indPowEqualsEle(arr, K){ // Length of the array let len = arr.length; // Initialize variable res for // calculating the answer let res = 0; // If the value of K is 0 if (K == 0) { // If the first element is 1 // then the condition is satisfied if (len > 0 && arr[0] == 1) res++; } // If the value of K > 0 if (K > 0) { // If the first is 0 increment res if (len > 0 && arr[0] == 1) res++; } // If the second element is 1 // then increment res if (len > 1 && arr[1] == 1) res++; // Iterate the array arr from index 2 for (let i = 2; i < len; i++) { // Initialize a variable // to index which is to be // multiplied K-1 times let indPow = i; for (let j = 2; j < K; j++) { // Multiply current value // with index K - 1 times indPow *= i; } // If index power K is equal to // the element then increment res if (indPow == arr[i]) res++; } // return the result return res;} // Driver Code// Initialize an arraylet arr = [ 1, 1, 4, 3, 16, 125, 1 ]; // Initialize powerlet K = 0; // Call the function// and print the answerdocument.write(indPowEqualsEle(arr, K)); // This code is contributed by Samim Hossain Mondal</script>",
"e": 34494,
"s": 32953,
"text": null
},
{
"code": null,
"e": 34496,
"s": 34494,
"text": "3"
},
{
"code": null,
"e": 34543,
"s": 34496,
"text": "Time Complexity: O(N * K)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34557,
"s": 34543,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 34569,
"s": 34557,
"text": "rakeshsahni"
},
{
"code": null,
"e": 34579,
"s": 34569,
"text": "samim2000"
},
{
"code": null,
"e": 34593,
"s": 34579,
"text": "sumitgumber28"
},
{
"code": null,
"e": 34605,
"s": 34593,
"text": "maths-power"
},
{
"code": null,
"e": 34612,
"s": 34605,
"text": "Arrays"
},
{
"code": null,
"e": 34625,
"s": 34612,
"text": "Mathematical"
},
{
"code": null,
"e": 34632,
"s": 34625,
"text": "Arrays"
},
{
"code": null,
"e": 34645,
"s": 34632,
"text": "Mathematical"
},
{
"code": null,
"e": 34743,
"s": 34645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34752,
"s": 34743,
"text": "Comments"
},
{
"code": null,
"e": 34765,
"s": 34752,
"text": "Old Comments"
},
{
"code": null,
"e": 34790,
"s": 34765,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34810,
"s": 34790,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34835,
"s": 34810,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 34884,
"s": 34835,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34922,
"s": 34884,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34952,
"s": 34922,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34967,
"s": 34952,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35027,
"s": 34967,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35070,
"s": 35027,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Jackson - JsonParser Class | JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance.
Following is the declaration for com.fasterxml.jackson.core.JsonParser class:
public abstract class JsonParser
extends Object
implements Closeable, Versioned
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1900,
"s": 1753,
"text": "JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance."
},
{
"code": null,
"e": 1978,
"s": 1900,
"text": "Following is the declaration for com.fasterxml.jackson.core.JsonParser class:"
},
{
"code": null,
"e": 2067,
"s": 1978,
"text": "public abstract class JsonParser\n extends Object\n implements Closeable, Versioned"
},
{
"code": null,
"e": 2172,
"s": 2067,
"text": "protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled."
},
{
"code": null,
"e": 2277,
"s": 2172,
"text": "protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled."
},
{
"code": null,
"e": 2333,
"s": 2277,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 2350,
"s": 2333,
"text": "java.lang.Object"
},
{
"code": null,
"e": 2367,
"s": 2350,
"text": "java.lang.Object"
},
{
"code": null,
"e": 2374,
"s": 2367,
"text": " Print"
},
{
"code": null,
"e": 2385,
"s": 2374,
"text": " Add Notes"
}
] |
Excel Macros - Quick Guide | An Excel macro is an action or a set of actions that you can record, give a name, save and run as many times as you want and whenever you want. When you create a macro, you are recording your mouse clicks and keystrokes. When you run a saved macro, the recorded mouse clicks and keystrokes will be executed in the same sequence as they are recorded.
Macros help you to save time on repetitive tasks involved in data manipulation and data reports that are required to be done frequently.
You can record and run macros with either Excel commands or from Excel VBA.
VBA stands for Visual Basic for Applications and is a simple programming language that is available through Excel Visual Basic Editor (VBE), which is available from the DEVELOPER tab on the Ribbon. When you record a macro, Excel generates VBA code. If you just want to record a macro and run it, there is no need to learn Excel VBA. However, if you want to modify a macro, then you can do it only by modifying the VBA code in the Excel VBA editor.
You will learn how to record a simple macro and run it with Excel commands in the chapter - Creating a Simple Macro. You will learn more about macros and about creating and / or modifying macros from Excel VBA editor in the later chapters.
A macro can be saved in the same workbook from where you recorded it. In that case, you can run the macro from that workbook only and hence you should keep it open. Excel gives you an alternative way to store all your macros. It is the personal macro workbook, where you can save your macros, which enables you to run those macros from any workbook.
You will learn about Personal Macro Workbook in the chapter - Saving all your Macros in a Single Workbook.
Macros will be stored as VBA code in Excel. As with the case of any other code, macro code is also susceptible to malicious code that can run when you open a workbook. This is a threat to your computer. Microsoft provided with the Macro Security facility that helps you in protecting your computer from such macro viruses.
You will learn more about this in the chapter - Macro Security.
While recording a macro, you can use either absolute references or relative references for the cells on which you are clicking. Absolute references make your macro run at the same cells where you recorded the macro. On the other hand, relative references make your macro run at the active cell.
You will learn about these in the chapters - Using Absolute References for a Macro and Using Relative References for a Macro.
You can record and run macros from Excel even if you do not know Excel VBA. However, if you have to modify a recorded macro or create a macro by writing VBA code, you should learn Excel VBA. You can refer to the Excel VBA tutorial in this tutorials library for this
However, you should know how to view the macro code. You can learn how to access VBA editor in Excel and about the different parts of the VBA editor in the chapter – Excel VBA.
You can learn how to view the macro code in Excel VBA editor and you can understand the macro code in the chapter - Understanding Macro Code.
You can assign a macro to an object such as a shape or a graphic or a control. Then, you can run the macro by clicking on that object. You will learn about this in the chapter - Assigning Macros to Objects.
Excel provides several ways to run a macro. You can choose the way you want to run a macro. You will learn about these different possible ways of running a macro in the chapter - Running a Macro.
If you decide to write the macro code, you can learn it in the chapter - Creating a Macro Using VBA Editor. However, the prerequisite is that you should have Excel VBA knowledge.
You can modify macro code in Excel VBA editor. If you want to make extensive changes, you should have Excel VBA knowledge. But, if you want to make only minor changes to the code or if you want to copy the VBA code from a recorded macro to another macro, you can refer to the chapter - Editing a Macro.
You can rename a macro and even delete it. You will learn about this also in the same chapter.
A Form is normally used to collect required information. It will be self-explanatory making the task simple. Excel User Forms created from Excel VBA editor serve the same purpose, providing the familiar options such as text boxes, check boxes, radio buttons, list boxes, combo boxes, scroll bars, etc. as controls.
You will learn how to create a User Form and how to use the different controls in the chapter – User Forms.
At times, a macro may not run as expected. You might have created the macro or you might be using a macro supplied to you by someone. You can debug the macro code just as you debug any other code to uncover the defects and correct them. You will learn about this in the chapter - Debugging Macro Code.
You can make your macro run automatically when you open a workbook. You can do this either by creating an Auto_Run macro or by writing VBA code for workbook open event. You will learn this in the chapter - Configuring a Macro to Run on Opening a Workbook.
You can create a macro with Excel commands by recording the key strokes and mouse clicks, giving the macro a name and specifying how to store the macro. A macro thus recorded can be run with an Excel command.
Suppose you have to collect certain results repeatedly in the following format −
Instead of creating the table each time, you can have a macro to do it for you.
To record a macro do the following −
Click the VIEW tab on the Ribbon.
Click Macros in the Macros group.
Select Record Macro from the dropdown list.
The Record Macro dialog box appears.
Type MyFirstMacro in the Macro name box.
Type MyFirstMacro in the Macro name box.
Type A Simple Macro in the Description box and click OK.
Type A Simple Macro in the Description box and click OK.
Remember that whatever key strokes and mouse clicks you do, will be recorded now.
Click in the cell B2.
Click in the cell B2.
Create the table.
Create the table.
Click in a different cell in the worksheet.
Click in a different cell in the worksheet.
Click the VIEW tab on the Ribbon.
Click the VIEW tab on the Ribbon.
Click Macros.
Click Macros.
Select Stop Recording from the dropdown list.
Select Stop Recording from the dropdown list.
Your macro recording is completed.
The first step to click on a particular cell is important as it tells where exactly the macro has to start placing the recorded steps. Once you are done with the recording, you have to click Stop Recording to avoid recording of unnecessary steps.
You can run the macro you have recorded any number of times you want. To run the macro, do the following −
Click on a new worksheet.
Note the active cell. In our case, it is A1.
Click the VIEW tab on the Ribbon.
Click the VIEW tab on the Ribbon.
Click Macros.
Click Macros.
Select View Macros from the dropdown list.
Select View Macros from the dropdown list.
The Macro dialog box appears.
Only the macro that you recorded appears in the Macros list.
Click the macro name – MyFirstMacro in the Macro dialog box. The description you typed while recording the macro will get displayed. Macro description allows you to identify for what purpose you have recorded the macro.
Click the macro name – MyFirstMacro in the Macro dialog box. The description you typed while recording the macro will get displayed. Macro description allows you to identify for what purpose you have recorded the macro.
Click the Run button. The same table that you have created while recording the macro will appear in just a split of a second.
Click the Run button. The same table that you have created while recording the macro will appear in just a split of a second.
You have discovered the magic wand that Excel provides you to save time on mundane tasks. You will observe the following −
Though the active cell before running the macro was A1, the table is placed in the cell B2 as you have recorded.
Though the active cell before running the macro was A1, the table is placed in the cell B2 as you have recorded.
In addition, the active cell became E2, as you have clicked that cell before you stopped recording.
In addition, the active cell became E2, as you have clicked that cell before you stopped recording.
You can run the macro in multiple worksheets with different active cells before running the macro and observe the same conditions as given above. Just keep a note of this and you will understand later in this tutorial why it has occurred so.
You can also have a macro recording that places your recorded steps in the active cell. You will learn how to do this as you progress in the tutorial.
You might wonder how to save the macros that are created. In this context you need to know −
Storing a macro
Saving a macro enabled file
As and when you create a macro, you can choose where to store that particular macro. You can do this in the Record Macro dialog box.
Click the box - Store macro in. The following three options are available −
This Workbook.
New Workbook.
Personal Macro Workbook
This is the default option. The macro will be stored in your current workbook from where you created the macro.
This option, though available, is not recommended. You will be asking Excel to store the macro in a different new workbook and mostly it is not necessary.
If you create several macros that you use across your workbooks, Personal Macro Workbook provides you with the facility to store all the macros at one place. You will learn more about this option in the next chapter.
If you had chosen This Workbook as the option for storing the macro, you would need to save your workbook along with the macro.
Try to save the workbook. By default, you would be asking Excel to save the workbook as an .xls file. Excel displays a message saying that an Excel feature VB project cannot be saved in a macro free workbook, as shown below.
Note − If you click Yes, Excel will save your workbook as a macro free .xls file and your macro that you stored with This Workbook option will not get saved. To avoid this, Excel provides you an option to save your workbook as a macro-enabled workbook that will have .xlsm extension.
Click No in the warning message box.
Select Excel Macro-Enabled Workbook (*.xlsm) in the Save as type.
Click Save.
You will learn more about these in later chapters in this tutorial.
Excel provides you with a facility to store all your macros in a single workbook. The workbook is called Personal Macro Workbook - Personal.xlsb. It is a hidden workbook stored on your computer, which opens every time you open Excel. This enables you to run your macros from any workbook. There will be a single Personal Macro Workbook per computer and you cannot share it across computers. You can view and run the macros in your Personal Macro Workbook from any workbook on your computer.
You can save macros in your Personal Macro Workbook by selecting it as the storing option while recording the macros.
Select Personal Macro Workbook from the drop down list under the category Store macro in.
Record your second macro.
Give macro details in the Record Macro dialog box as shown below.
Click OK.
Your recording starts. Create a table as shown below.
Stop recording.
Stop recording.
Click the VIEW tab on the Ribbon.
Click the VIEW tab on the Ribbon.
Click Macros.
Click Macros.
Select View Macros from the dropdown list. The Macro dialog box appears.
Select View Macros from the dropdown list. The Macro dialog box appears.
The macro name appears with a prefix PERSONAL.XLSB! indicating that the Macro is in the Personal Macro Workbook.
Save your workbook. It will get saved as an .xls file as the macro is not in your workbook and close Excel.
You will get the following message regarding saving the changes to the Personal Macro Workbook −
Click the Save button. Your macro is saved in the Personal.xlsb file on your computer.
Personal Macro Workbook will be hidden, by default. When you start Excel, the personal macro workbook is loaded but you cannot see it because it is hidden. You can unhide it as follows −
Click the VIEW tab on the Ribbon.
Click the VIEW tab on the Ribbon.
Click Unhide in the Window group.
Click Unhide in the Window group.
The Unhide dialog box appears.
PERSONAL.XLSB appears in the Unhide workbook box and click OK.
Now you can view the macros saved in the personal macro workbook.
To hide the personal macro workbook, do the following −
Click on the personal macro workbook.
Click the VIEW tab on the Ribbon.
Click Hide on the Ribbon.
You can run the macros saved in personal macro workbook from any workbook. To run the macros, it does not make any difference whether the personal macro workbook is hidden or unhidden.
Click View Macros.
Select the macro name from the macros list.
Click the Run button. The macro will run.
You can add more macros in personal macro workbook by selecting it for Store macro in option while recording the macros, as you had seen earlier.
You can delete a macro in personal macro workbook as follows −
Make sure that the personal macro workbook is unhidden.
Click the macro name in the View Macros dialog box.
Click the Delete button.
If the personal macro workbook is hidden, you will get a message saying “Cannot edit a macro on a hidden workbook”.
Unhide the personal macro workbook and delete the selected macro.
The macro will not appear in the macros list. However, when you create a new macro and save it in your personal workbook or delete any macros that it contains, you will be prompted to save the personal workbook just as in the case you saved it first time.
The macros that you create in Excel would be written in the programming language VBA (Visual Basic for Applications). You will learn about the Excel macro code in later chapters. As you are aware, when there is an executable code, there is a threat of viruses. Macros are also susceptible to viruses.
Excel VBA in which the Macros are written has access to most Windows system calls and executes automatically when workbooks are opened. Hence, there is a potential threat of the existence of a virus written as a macro and is hidden within Excel that are executed on opening a workbook. Therefore, Excel macros can be very dangerous to your computer in many ways. However, Microsoft has taken appropriate measures to shield the workbooks from macro viruses.
Microsoft has introduced macro security so that you can identify which macros you can trust and which you cannot.
The most important Excel macro security feature is - file extensions.
Excel workbooks will be saved with .xlsx file extension by default. You can always trust workbooks with .xlsx file extension, as they are incapable of storing a macro and will not carry any threat.
Excel workbooks with macros are saved with .xlsm file extension. They are termed as Macro Enabled Excel Workbooks. Before you open such workbooks, you should make sure that the macros they contain are not malicious. For this, you must ensure that you can trust the origin of this type of workbooks.
Excel provides three ways to trust a macro enabled workbook.
Placing the macro enabled workbooks in a trusted folder
Placing the macro enabled workbooks in a trusted folder
Checking if a macro is digitally signed
Checking if a macro is digitally signed
Enabling security alert messages before opening macro enabled workbooks
Enabling security alert messages before opening macro enabled workbooks
This is the easiest and best way to manage macro security. Excel allows you to designate a folder as a trusted location. Place all your macro-enabled workbooks in that trusted folder. You can open macro-enabled workbooks that are saved to this location without warnings or restrictions.
Digital signatures confirm the identity of the author. You can configure Excel to run digitally signed macros from trusted persons without warnings or restrictions. Excel will also warn the recipient if it has been changed since the author signed it.
When you open a workbook, Excel warns you that the workbook contains macros and asks whether you wish to enable them. You can click the Enable Content button if the source of the workbook is reliable.
You can set any of these three options in the Trust Center in the Excel Options.
If you work in an organization, the system administrator might have changed the default settings to prevent anyone from changing the settings. Microsoft advises that you do not change security settings in the Trust Center as the consequences can be loss of data, data theft or security compromises on your computer or network.
However, you can learn the macro security settings in the following sections and check if they are to be changed. You have to use your own instinct to decide on any of these options based on the context and your knowledge of the file origin.
The macro settings are located in the Trust Center in the Excel Options. To access the Trust Center, do the following −
Click the FILE tab on the Ribbon.
Click the FILE tab on the Ribbon.
Click Options. The Excel Options dialog box appears.
Click Options. The Excel Options dialog box appears.
Click Trust Center in the left pane.
Click Trust Center in the left pane.
Click the Trust Center Settings button under Microsoft Excel Trust Center.
Click the Trust Center Settings button under Microsoft Excel Trust Center.
The Trust Center dialog box appears.
You will see various options available in the Excel Trust Center in the left pane. You will learn about the options related to Excel macros in the following sections.
Macro settings are located in the Trust Center.
Under Macro Settings, four options are available.
Disable all macros without notification − If this option is chosen, Macros and security alerts about macros are disabled.
Disable all macros without notification − If this option is chosen, Macros and security alerts about macros are disabled.
Disable all macros with notification − Macros are disabled, but security alerts appear if there are macros present. You can enable macros on a case-by-case basis.
Disable all macros with notification − Macros are disabled, but security alerts appear if there are macros present. You can enable macros on a case-by-case basis.
Disable all macros except digitally signed macros − Macros are disabled but security alerts appear if there are macros present. However, if the macro is digitally signed by a trusted publisher, the macro runs if you trust the publisher. If you have do not trust the publisher, you will be notified to enable the signed macro and trust the publisher.
Disable all macros except digitally signed macros − Macros are disabled but security alerts appear if there are macros present. However, if the macro is digitally signed by a trusted publisher, the macro runs if you trust the publisher. If you have do not trust the publisher, you will be notified to enable the signed macro and trust the publisher.
Enable all macros (not recommended, susceptible to macro viruses) − If this option is chosen, all macros run. This setting makes your computer vulnerable to potentially malicious code.
Enable all macros (not recommended, susceptible to macro viruses) − If this option is chosen, all macros run. This setting makes your computer vulnerable to potentially malicious code.
You have an additional security option under Developer Macro Settings with a Check box.
Trust access to the VBA project object model.
This option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client.
This security option is for code written to automate an Office program and manipulate the VBA environment and object model.
It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code.
For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box.
Trust access to the VBA project object model.
This option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client.
This option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client.
This security option is for code written to automate an Office program and manipulate the VBA environment and object model.
This security option is for code written to automate an Office program and manipulate the VBA environment and object model.
It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code.
It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code.
For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box.
For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box.
If you think that a macro-enabled workbook is from a reliable source, it is better to move the file to the trusted location identified by Excel, instead of changing the default Trust Center settings to a less-safe macro security setting.
You can find the trusted folder settings in the Trust Center.
Click the Trusted Locations in the Trust Center dialog box. The Trusted Locations set by Microsoft Office appear on the right side.
You can add new locations, remove the existing locations and modify the existing locations. The identified trusted locations will be treated by Microsoft office as reliable for opening files. However, if you add or modify a location, ensure that the location is secure.
You can also find the options that office does not recommend, such as locations on internet.
Microsoft provides an option to accommodate digitally signed macros. However, even if a macro is digitally signed, you need to ensure that it is from a trusted publisher.
You will find the trusted publishers in in the Trust Center.
Click Trusted Publishers in the Trust Center dialog box. A list of certificates appear on the right side with the details – Issued To, Issued By and Expiration Date.
Click Trusted Publishers in the Trust Center dialog box. A list of certificates appear on the right side with the details – Issued To, Issued By and Expiration Date.
Select a certificate and click View.
Select a certificate and click View.
The certificate information is displayed.
As you have learnt earlier in this chapter, you can set an option to run a macro that is digitally signed only if you trust the publisher. If you do not trust the publisher, you will be notified to enable the signed macro and trust the publisher.
The Message Bar displays security alert when there are macros in the file that you are opening. The yellow Message Bar with a shield icon alerts you that the macros are disabled.
If you know that the macro or macros are from a reliable source, you can click n the Enable Content button on the Message Bar, to enable the macros.
You can disable the Message Bar option if you do not want security alerts. On the other hand, you can enable the Message Bar option to increase security.
You can enable / disable security alerts with Message Bars as follows −
Click the FILE tab on the Ribbon.
Click Options. The Excel Options dialog box appears.
Click Trust Center.
Click the Trust Center Settings button.
Click Message Bar.
The Message Bar Settings for all Office Applications appear.
There are two options under - Showing the Message Bar.
Option 1 − Show the Message Bar in all applications when active content such as macros is blocked.
This is the default option. The Message Bar appears when potentially unsafe content has been disabled.
This is the default option. The Message Bar appears when potentially unsafe content has been disabled.
If you had selected - Disable all macros without notification in the Macro Settings of the Trust Center, this option is not selected and the Message Bar does not appear.
If you had selected - Disable all macros without notification in the Macro Settings of the Trust Center, this option is not selected and the Message Bar does not appear.
Option 2 − Never show information about blocked content.
If this option if selected, it disables the Message Bar and no alerts appear about security issues, regardless of any security settings in the Trust Center.
Excel macros can be recorded either with absolute references or relative references. A macro recorded with absolute references places the recorded steps exactly in the cells where it was recorded, irrespective of the active cell. On the other hand, a macro recorded with relative references can perform the recorded tasks at different parts on the worksheet.
You will learn about absolute references for macro in this chapter. You will learn about relative references in the next chapter.
Suppose you have to submit a report about your team’s work at the end of every day in the following format −
Now, the report should be placed in the cell B2 and should be in the given format.
A sample filled in report will be as shown below −
Except for the data in the following cells, the information is constant for every report that you generate for the project.
C3 – Report for Date.
C13 – No. of Tasks Completed Today.
C14 – Total No. of Tasks Completed.
C15 – % Work Complete.
Of these also, in C3 (Report for Date) you can place the Excel function = TODAY () that places the date of your report without your intervention. Further, in cell C15, you can have the formula C14/C12 and format the cell C15 as percentage to have the % Work Complete calculated by Excel for you.
This leaves you with only two cells – C13 and C14 that need to be filled in by you every day. Hence, it would be ideal to have information for the rest of the cells, every time you have to create the report. This saves time for you and you can do the mundane activity of reporting in just few minutes.
Now, suppose you have to send such reports for three projects. You can imagine the time you can save and take up more challenging work for the day and of course get the accolades from your management.
You can achieve this by recording a macro per project and running them on a day-to-day basis to generate the required reports in a matter of just few minutes. However, every time you run the macro, the report should appear on the worksheet as given above, irrespective of the active cell. For this, you have to use absolute references.
To record a macro with absolute references, you have to ensure that the macro is being recorded starting from the cell where the steps have to start. This means, in the case of the example given in the previous section, you need to do the following −
Start recording the macro.
Create a new worksheet.
Click in any cell other than B2 in the new worksheet.
Click in the cell B2.
Continue recording the macro.
This will create a new worksheet for every new report and get the report format placed in the cell B2 every time you run the macro.
Note − The first three steps given above are essential.
If you do not create a new worksheet, when you run the macro, it places whatever you recorded on the same worksheet at the same place. This is not what you want. You need to have every report on a different worksheet.
If you do not create a new worksheet, when you run the macro, it places whatever you recorded on the same worksheet at the same place. This is not what you want. You need to have every report on a different worksheet.
If you do not click in a different cell at the beginning of the recording, even if the active cell is B2, Excel places the recorded steps in the active cell. When you run the macro, it will place the recorded report format at any part of the worksheet based on the active cell. By explicitly clicking in a cell other than B2 and then the the cell B2, you are telling the recorder to always place your macro steps in the cell B2.
If you do not click in a different cell at the beginning of the recording, even if the active cell is B2, Excel places the recorded steps in the active cell. When you run the macro, it will place the recorded report format at any part of the worksheet based on the active cell. By explicitly clicking in a cell other than B2 and then the the cell B2, you are telling the recorder to always place your macro steps in the cell B2.
You can start recording the macro with the Record Macro command on the Ribbon under the VIEW tab → Macros. You can also click the Start Recording Macro button present on left side of the Excel task bar.
Start recording the macro. The Record Macro dialog box appears.
Start recording the macro. The Record Macro dialog box appears.
Give a meaningful name to identify the macro as a report of a particular project.
Give a meaningful name to identify the macro as a report of a particular project.
Select This Workbook under Store macro in, as you will produce reports from this specific workbook only.
Select This Workbook under Store macro in, as you will produce reports from this specific workbook only.
Give a description to your macro and click OK.
Give a description to your macro and click OK.
Your macro starts recording.
Create a new worksheet. This ensures your new report will be on a new worksheet.
Create a new worksheet. This ensures your new report will be on a new worksheet.
Click in any cell other than B2 in the new worksheet.
Click in any cell other than B2 in the new worksheet.
Click in the cell B2. This ensures that the macro places your recorded steps in B2 always.
Click in the cell B2. This ensures that the macro places your recorded steps in B2 always.
Create the format for the report.
Create the format for the report.
Fill in the static information for the project report.
Fill in the static information for the project report.
Place = TODAY () in C3 and = C14/C12 in the cell C15.
Place = TODAY () in C3 and = C14/C12 in the cell C15.
Format the cells with dates.
Format the cells with dates.
Stop recording the macro.
You can stop recording the macro either with the Stop Recording command on the Ribbon under VIEW tab → Macros or by clicking the Stop Recording Macro button present on left side of the Excel task bar.
Your Project Report macro is ready. Save the workbook as a macro-enabled workbook (with .xlsm extension).
You can generate any number of reports in a few seconds just by running the macro.
Click the VIEW button on the Ribbon.
Click Macros.
Select View Macros from the dropdown list. The Macro dialog box appears.
Click the macro Report_ProjectXYZ.
Click the Run button.
A new worksheet will be created in your workbook, with the report stencil created in it in the cell B2.
Relative reference macros record an offset from the active cell. Such macros will be useful if you have to repeat the steps at various places in the worksheet.
Suppose you are required to analyze the data of voters collected from 280 constituencies. For each constituency, the following details are collected −
Constituency name.
Total population in the constituency.
Number of voters in the constituency.
Number of male voters, and
Number of female voters.
The data is provided to you in a worksheet as given below.
It is not possible to analyze the data in the above format. Therefore, arrange the data in a table as shown below.
If you attempt to arrange the given data in the above format −
It takes substantial amount of time to arrange the data from the 280 constituencies
It takes substantial amount of time to arrange the data from the 280 constituencies
It can be error prone
It can be error prone
It becomes a mundane task not allowing you to focus on technical things
It becomes a mundane task not allowing you to focus on technical things
The solution is to record a macro so that you can complete the task in not more than a few seconds. The macro needs to use relative references, as you will move down the rows while arranging the data.
In order to let the macro recorder know that it has to use relative references, do the following −
Click the VIEW tab on the Ribbon.
Click the VIEW tab on the Ribbon.
Click Macros.
Click Macros.
Click Use Relative References.
Click Use Relative References.
The first step in arranging the above given data is to define the data format in a table with headers.
Create the row of headers as shown below.
Record the macro as follows −
Click Record Macro.
Click Record Macro.
Give a meaningful name, say, DataArrange to the macro.
Give a meaningful name, say, DataArrange to the macro.
Type = row ()- 3 in the cell B4. This is because the S. No. is the current row number – the 3 rows above it.
Type = row ()- 3 in the cell B4. This is because the S. No. is the current row number – the 3 rows above it.
Cut the cells B5, B6, B7, B8 and B9 and paste it in the cells C4 to C8 respectively.
Cut the cells B5, B6, B7, B8 and B9 and paste it in the cells C4 to C8 respectively.
Now click in the cell B5. Your table looks as shown below.
Now click in the cell B5. Your table looks as shown below.
The first data set is arranged in the first row of the table. Delete the rows B6 – B11 and click in the cell B5.
You can see that the active cell is B5 and the next data set will be placed here.
Stop recording the macro. Your macro for arranging the data is ready.
You need to run the macro repeatedly to complete the data arrangement in the table as given below.
The active cell is B5. Run the macro. The second data set will be arranged in the second row of the table and the active cell will be B6.
Run the macro again. The third data set will be arranged in the third row of the table and the active cell will become B7.
Each time you run the macro, the active cell advances to the next row, facilitating the repetition of recorded steps at the appropriate positions. This is possible because of the relative references in macro.
Run the macro until all the 280 data sets are arranged into 280 rows in the table. This process takes a few seconds and as the steps are automated, the entire exercise is error free.
Excel stores the macros as Excel VBA (Visual Basic for Applications) code. After recording a macro, you can view the code that is generated, modify it, copy a part of it, etc. You can even write a macro code yourself if you are comfortable with programming in VBA.
You will learn how to create a macro, by writing a VBA code, in the chapter - Creating a Macro Using VBA Editor. You will learn how to modify a macro by editing VBA code in the chapter - Editing a Macro. You will learn the Excel VBA features in this chapter.
You can access macro code in VBA from the Developer tab on the Ribbon.
If you do not find the Developer tab on the Ribbon, you need to add it as follows −
Right click on the Ribbon.
Right click on the Ribbon.
Select Customize the Ribbon from the dropdown list.
Select Customize the Ribbon from the dropdown list.
The Excel Options dialog box appears.
Select Main Tabs from Customize the Ribbon dropdown list.
Select Main Tabs from Customize the Ribbon dropdown list.
Check the box – Developer in the Main Tabs list and click OK. The developer tab appears.
Check the box – Developer in the Main Tabs list and click OK. The developer tab appears.
You need to know the commands that are for macros under the developer tab.
Click the DEVELOPER tab on the Ribbon. The following commands are available in the Code group −
Visual Basic
Macros
Record Macro
Use Relative References
Macro Security
The Visual Basic command is used to open the VBA Editor in Excel and the Macros command is used to view, run and delete the macros.
You have already learnt the commands other than VBA Editor in the previous chapters.
VBA Editor or VBE is the developer platform for VBA in Excel.
Open the workbook – MyFirstMacro.xlsm that you saved earlier in the chapter – Creating a Simple Macro, in this tutorial.
You can open the VBE in any of the two ways −
Option 1 − Click Visual Basic in the Code group under the Developer tab on the Ribbon.
Option 2 − Click Edit in the Macro dialog box that appears when you click VIEW tab → Macros → View Macros
VBE appears in a new window.
The name of your Excel macro enabled workbook name appears with the prefix – Microsoft Visual Basic for Applications.
You will find the following in the VBE −
Projects Explorer.
Properties.
Module window with Code.
Project Explorer is where you find the VBA project names. Under a project, you will find Sheet names and Module names. When you click a module name, the corresponding code appears on the right side in a window.
The Properties are the parameters for VBA objects. When you have an object such as command button, its properties will appear in the Properties window.
The code of a macro will be stored in a module in VBA. When you select a macro and click Edit, the code of the macro appears in the corresponding module window.
When you record a macro, Excel stores it as a VBA code. You can view this code in the VBA editor. You can understand the code and modify it if you have substantial knowledge of Excel VBA. You can refer to the Excel VBA tutorial in this tutorials library to obtain a grasp on the language.
However, you can still view the macro code in Excel VBA editor and match it to the steps that you recorded in macro. You will learn how to view the code and understand it for the first macro that you created in this tutorial – MyFirstMacro.
To view a macro code, do the following −
Open the workbook in which you stored the macro.
Click VIEW tab on the Ribbon.
Click Macros.
Select View Macros from the dropdown list.
The Macro dialog box appears.
Click MyFirstMacro in the macros list.
Click the Edit button.
The VBA editor opens and the code of the macro MyFirstMacro appears.
You can browse through the macro code and map them to your recorded steps.
Start reading the code.
Map the code to the recorded steps.
Scroll down the code to view more code. Alternatively, you can enlarge the code window.
Observe that the code is simple. If you learn Excel VBA, you can create the macros by writing the code in the VBA editor.
You will learn how to write a VBA code to create a macro in the chapter - Creating a Macro Using VBA Editor.
Suppose you have created a macro that you need to execute several times. For example, the macros that you have created for absolute references and relative references. Then, it would be easy for you if you can run the macro using a mouse click. You can accomplish this by assigning the macro to an object such as a shape or a graphic or a control.
In this chapter, you will learn how to include an object in your workbook and assign a macro to it.
Recall the macro that you created using relative references. The macro arranges the data given in one column into a table to facilitate data analysis.
You can insert a shape in your worksheet that is in a meaningful form with self-explanatory text, which when clicked runs the macro assigned to it.
Click the INSERT tab on the Ribbon.
Click the INSERT tab on the Ribbon.
Click Shapes in the Illustrations group.
Click Shapes in the Illustrations group.
Select any of the ready-made shapes that appear in the dropdown list. For example, the Flowchart shape – Preparation, as you are in the process of preparing the data.
Select any of the ready-made shapes that appear in the dropdown list. For example, the Flowchart shape – Preparation, as you are in the process of preparing the data.
Draw the shape and format it.
Right click on the shape and select Edit Text from the dropdown list.
Right click on the shape and select Edit Text from the dropdown list.
Type text inside the shape - Run Macro.
Type text inside the shape - Run Macro.
Format the text.
Format the text.
Right click on the shape.
Select Assign Macro from the dropdown list.
The Assign Macro dialog box appears. Click the macro name i.e. RelativeMacro and click OK.
The macro is assigned to the shape.
Click in the cell where you have to run the macro say B4.
Click in the cell where you have to run the macro say B4.
Move the cursor (pointer) onto the shape. The cursor (pointer) changes to finger.
Move the cursor (pointer) onto the shape. The cursor (pointer) changes to finger.
Now click the shape. The macro will run. Just repeat the mouse clicks to run the macro several times and you are done with the task of arranging the data into a table in a matter of a few seconds.
You can insert a graphic in the worksheet and assign a macro to it. The graphic can be chosen to visualize your macro. For example, you can have a graphic of table representing that the macro will arrange the data into a table.
Click the INSERT tab on the Ribbon.
Click Pictures in the Illustrations group.
Select a file that contains your graphic.
The rest of the steps are the same as those of shape given in the previous section.
Inserting a VBA control and assigning a macro to it makes your work look professional. You can insert VBA controls from the Developer tab on the Ribbon.
Click the DEVELOPER tab on the Ribbon.
Click the DEVELOPER tab on the Ribbon.
Click Insert in the Controls group.
Click Insert in the Controls group.
Select the Button icon under Form Controls from the dropdown list as shown in screenshot given below −
Click the cell on the worksheet where you want to insert the Button control. The Assign Macro dialog box appears.
Click the cell on the worksheet where you want to insert the Button control. The Assign Macro dialog box appears.
Click the macro name and click OK.
Click the macro name and click OK.
The control button with the assigned macro will be inserted.
Right click on the button.
Click Edit Text.
Type – Run Macro.
Format Text and resize Button.
You can run the macro any number of times by just clicking the Button repeatedly.
Using Form Controls is an easy and effective way of interacting with the user. You will learn more about this in the chapter – Interacting with the User.
There are several ways of executing a macro in your workbook. The macro would have been saved in your macro enabled workbook or in your Personal macro workbook that you can access from any workbook as you had learnt earlier.
You can run a macro in the following ways −
Running a Macro from the View Tab
Running a Macro by pressing Ctrl plus a shortcut key
Running a Macro by clicking a button on the Quick Access Toolbar
Running a Macro by clicking a button in a Custom Group on the Ribbon
Running a Macro by clicking on a Graphic Object
Running a Macro from Developer Tab
Running a Macro from VBA Editor
You have already learnt running a macro from the View tab on the Ribbon. A quick recap −
Click the VIEW tab on the Ribbon.
Click Macros.
Select View Macros from the dropdown list.
The Macro dialog box appears.
Click the macro name.
Click the Run button.
You can assign a shortcut key (Ctrl + key) for a macro. You can do this while recording the macro in the Create Macro dialog box. Otherwise, you can add this later in the Macro Options dialog box.
Click the VIEW tab.
Click Macros.
Select Record Macro from the dropdown list.
The Create Macro dialog box appears.
Type a macro name
Type a letter, say q, in the box next to Ctrl + under Shortcut key.
Click the VIEW tab.
Click Macros.
Select View Macros from the dropdown list.
The Macro dialog box appears.
Select the macro name.
Click the Options button.
The Macro Options dialog box appears. Type a letter, say q, in the box next to Ctrl + under Shortcut key. Click OK.
To run the macro with the shortcut key, press the Ctrl key and the key q together. The macro will run.
Note − You can use any lowercase or uppercase letters for the shortcut key of a macro. If you use any Ctrl + letter combination that is an Excel shortcut key, you will override it. Examples include Ctrl+C, Ctrl+V, Ctrl+X, etc. Hence, use your jurisdiction while choosing the letters.
You can add a macro button to the Quick Access Toolbar and run the macro by clicking it. This option would be useful when you store your macros in personal macro workbook. The added button will appear on the Quick Access Toolbar in whatever workbook you open, thus making it easy for you to run the macro.
Suppose you have a macro with the name MyMacro in your personal macro workbook.
To add the macro button to the Quick Access Toolbar do the following −
Right click on the Quick Access Toolbar.
Right click on the Quick Access Toolbar.
Select Customize Quick Access Toolbar from the dropdown list.
Select Customize Quick Access Toolbar from the dropdown list.
The Excel Options dialog box appears. Select Macros from the dropdown list under the category- Choose commands from.
A list of macros appears under Macros.
Click PERSONAL.XLSB!MyMacro.
Click the Add button.
The macro name appears on the right side, with a macro button image.
To change the macro button image, proceed as follows −
Click the macro name in the right box.
Click the Modify button.
The Modify Button dialog box appears. Select one symbol to set it as the icon of the button.
Modify the Display name that appears when you place the pointer on the Button image on the Quick Access Toolbar to a meaningful name, say, Run MyMacro for this example. Click OK.
The Macro name and the icon symbol change in the right pane. Click OK.
The macro button appears on the Quick Access Toolbar and the macro display name appears when you place the pointer on the button.
To run the macro, just click the macro button on the Quick Access Toolbar.
You can add a custom group and a custom button on the Ribbon and assign your macro to the button.
Right click on the Ribbon.
Select Customize the Ribbon from the dropdown list.
The Excel Options dialog box appears.
Select Main Tabs under Customize the Ribbon.
Click New Tab.
The New Tab (Custom) appears in Main Tabs list.
Click New Tab (Custom).
Click the New Group button.
The New Group (Custom) appears under New Tab (Custom).
Click New Tab (Custom).
Click the Rename button.
The Rename dialog box appears. Type the name for your custom tab that appears in Main tabs on the Ribbon, say - My Macros and click OK.
Note − All the Main tabs on the Ribbon are in uppercase letters. You can use your discretion to use uppercase or lowercase letters. I have chosen lowercase with capitalization of words so that it stands out in the standard tabs.
The new tab name changes to My Macros (Custom).
Click New Group (Custom).
Click the Rename button.
The Rename dialog box appears. Type the group name in the Display name dialog box and click OK.
The new group name changes to Personal Macros (custom).
Click Macros in the left pane under Choose commands from.
Select your macro name, say – MyFirstMacro from the macros list.
Click the Add button.
The macro will be added under the Personal Macros (Custom) group.
Click My Macros (Custom) in the list.
Click the arrows to move the tab up or down.
The position of the tab in the main tabs list determines where it will be placed on the Ribbon. Click OK.
Your custom tab – My Macros appears on the Ribbon.
Click the tab - My Macros. Personal Macros group appears on the Ribbon. MyFirstMacro appears in the Personal Macros group. To run the macro, just click on MyFirstMacro in the Personal Macros group.
You can insert an object such as a shape, a graphic or a VBA control in your worksheet and assign a macro to it. To run the macro, just click the object.
For details on running a macro using objects, refer to chapter – Assigning Macros to Objects.
You can run a macro from the Developer tab.
Click the Developer tab on the Ribbon.
Click Macros.
The Macro dialog box appears. Click the macro name and then click Run.
You can run a macro from the VBA editor as follows −
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
You can create a macro by writing the code in the VBA editor. In this chapter, you will learn where and how to write the code for a macro.
Before you start coding for a Macro, understand the VBA Objects and Modules.
Open the macro-enabled workbook with your first macro.
Click the DEVELOPER tab on the Ribbon.
Click Visual Basic in the Code group.
The VBA editor window opens.
You will observe the following in the Projects Explorer window −
Your macro enabled workbook – MyFirstMacro.xlsm appears as a VBA Project.
Your macro enabled workbook – MyFirstMacro.xlsm appears as a VBA Project.
All the worksheets and the workbook appear as Microsoft Excel Objects under the project.
All the worksheets and the workbook appear as Microsoft Excel Objects under the project.
Module1 appears under Modules. Your macro code is located here.
Module1 appears under Modules. Your macro code is located here.
Click Module1.
Click Module1.
Click the View tab on the Ribbon.
Click the View tab on the Ribbon.
Select Code from the dropdown list.
Select Code from the dropdown list.
The code of your macro appears.
Next, create a second macro in the same workbook – this time by writing VBA code.
You can do this in two steps −
Insert a command button.
Insert a command button.
Write the code stating the actions to take place when you click the command button.
Write the code stating the actions to take place when you click the command button.
Create a new worksheet.
Create a new worksheet.
Click in the new worksheet.
Click in the new worksheet.
Click the DEVELOPER button on the Ribbon.
Click the DEVELOPER button on the Ribbon.
Click Insert in the Controls group.
Click Insert in the Controls group.
Select the button icon from Form Controls.
Select the button icon from Form Controls.
Click in the worksheet where you want to place the command button.
The Assign Macro dialog box appears.
The Visual Basic editor appears.
You will observe the following −
A new module – Module2 is inserted in the Project Explorer.
Code window with title Module2 (Code) appears.
A sub procedure Button1_Click () is inserted in the Module2 code.
Your coding is half done by the VBA editor itself.
For example, type MsgBox “Best Wishes to You!” in the sub procedure Button1_Click (). A message box with the given string will be displayed when the command button is clicked.
That’s it! Your macro code is ready to run. As you are aware, VBA code does not require compilation as it runs with an interpreter.
You can test your macro code from the VBA editor itself.
Click the Run tab on the Ribbon.
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list. The message box with the string you typed appears in your worksheet.
Select Run Sub/UserForm from the dropdown list. The message box with the string you typed appears in your worksheet.
You can see that the button is selected. Click OK in the message box. You will be taken back to the VBA editor.
You can run the macro that you coded any number of times from the worksheet.
Click somewhere on the worksheet.
Click the Button. The Message box appears on the worksheet.
You have created a macro by writing VBA code. As you can observe, VBA coding is simple.
You have learnt how to write macro code in VBA editor in the previous chapter. You can edit the macro code, rename a macro and delete a macro.
If you master Excel VBA, writing code or modifying code for a macro is a trivial task. You can edit the macro code however you want. If you want to make only few simple changes in the macro code, you can even copy macro code from one place to another.
You have created two macros – MyFirstMacro and Button1_Click in the macro enabled workbook MyFirstMacro.xlsm. You have created the first macro by recording the steps and the second macro by writing code. You can copy code from the first macro into the second macro.
Open the workbook MyFirstMacro.xlsm.
Open the workbook MyFirstMacro.xlsm.
Click the Developer tab on the Ribbon.
Click the Developer tab on the Ribbon.
Click Visual Basic. The Visual Basic editor opens.
Click Visual Basic. The Visual Basic editor opens.
Open the code for Module1 (MyFirstMacro macro code) and Module2 (Button1_Click () macro code).
Open the code for Module1 (MyFirstMacro macro code) and Module2 (Button1_Click () macro code).
Click the Window tab on the Ribbon.
Click the Window tab on the Ribbon.
Select Tile Horizontally from the dropdown list.
Select Tile Horizontally from the dropdown list.
You can view the code of the two macros in the tiled windows.
Copy the MsgBox line in the Module2 code.
Copy the MsgBox line in the Module2 code.
Paste it above that line.
Paste it above that line.
Modify the string as −
MsgBox “Hello World!”
Modify the string as −
MsgBox “Hello World!”
Copy the following code from Module1.
Copy the following code from Module1.
Paste it in the Module2 code in between the two MsgBox lines of code.
Click the Save icon to save the code.
Click the Save icon to save the code.
Click the Button in the Excel sheet. A Message box appears with the message - Hello World! Click OK.
Click the Button in the Excel sheet. A Message box appears with the message - Hello World! Click OK.
The table data appears (according to the code that you copied) and message box appears with message - Best Wishes to You!
You can modify the code in just a few steps. This is the easiest task for a beginner.
Suppose you want to run the edited macro from any worksheet other than the one that has the command button. You can do it irrespective of button click by renaming the macro.
Click the VIEW tab on the Ribbon.
Click Macros.
Select View Macros from the dropdown list.
The Macro dialog box appears.
Click the macro name – Button1_Click.
Click the Edit button.
The macro code appears in the VBA editor.
Change the name that appears in the Sub line from Button1_Click to RenamedMacro. Leave Sub and parenthesis as they are.
Open the Macro dialog box. The macro name appears as you renamed.
Click RenamedMacro.
Click the Run button. The macro runs. Now a button click is not necessary.
You can delete a macro that you have recorded or coded.
Open the Macros dialog box.
Click the macro name.
Click the Delete button.
The Delete confirmation message appears.
Click Yes if you are sure to delete the macro. Otherwise, click No.
At times, you might have to collect information repeatedly from others. Excel VBA provides you with an easy way of handling this task- UserForm. As any other form that you fill up, UserForm makes it simple to understand, what information is to be provided. UserForm is user friendly in the way that the controls provided are self-explanatory, accompanied by additional instructions where necessary.
Major advantage of UserForm is that you can save on time that you spend on what and how the information is to be filled.
To create a UserForm, proceed as follows −
Click the DEVELOPER tab on the Ribbon.
Click Visual Basic. A Visual Basic window for the workbook opens.
Click Insert,
Select UserForm from the dropdown list.
The UserForm appears on the right side of the window.
Maximize the UserForm.xlsx – UserForm1 window.
You are in the design mode now. You can insert controls on the UserForm and write code for the respective actions. The controls are available in the ToolBox. Properties of UserForm are in the Properties window. UserForm1 (caption of the UserForm) is given under Forms in the Projects Explorer.
Change the caption of the UserForm to Project Report – Daily in the properties window.
Change the name of the UserForm to ProjectReport.
The changes are reflected in the UserForm, properties and project explorer.
A UserForm will have different components. As and when you click on any of the components, either you will be provided with instructions on what and how the information is to be provided or you will be provided with options (choices) to select from. All these are provided by means of ActiveX controls in the ToolBox of the UserForm.
Excel provides two types of controls – Form controls and ActiveX controls. You need to understand the difference between these two types of controls.
Form controls are the Excel original controls that are compatible with earlier versions of Excel, starting with Excel version 5.0. Form controls are also designed for use on XLM macro sheets.
You can run macros by using Form controls. You can assign an existing macro to a control, or write or record a new macro. When the control is clicked, the macro. You have already learnt how to insert a command button from Form controls in the worksheet to run a macro. However, these controls cannot be added to a UserForm.
ActiveX controls can be used on VBA UserForms. ActiveX controls have extensive properties that you can use to customize their appearance, behavior, fonts and other characteristics.
You have the following ActiveX controls in the UserForm ToolBox −
Pointer
Label
TextBox
ComboBox
ListBox
CheckBox
OptionButton
Frame
ToggleButton
CommandButton
TabStrip
MultiPage
ScrollBar
SpinButton
Image
In addition to these controls, Visual Basic provides you with MsgBox function that can be used to display messages and/or prompt the user for an action.
In the next few sections, you will understand these controls and MsgBox. Then, you will be in a position to choose which of these controls are required to design your UserForm.
You can use Labels for identification purpose by displaying descriptive text, such as titles, captions and / or brief instructions.
Example
You can use a TextBox that is a rectangular box, to type, view or edit text. You can also use a TextBox as a static text field that presents read-only information.
Example
You can use a List Box to display a list of one or more items of text from which a user can choose. Use a list box for displaying large numbers of choices that vary in number or content.
Insert a ListBox on the UserForm.
Click on the ListBox.
Type ProjectCodes for Name in the Properties window of the ListBox.
There are three types of List Boxes −
Single-selection List box − A single-selection List Box enables only one choice. In this case, a list box resembles a group of option buttons, except that a list box can handle a large number of items more efficiently.
Single-selection List box − A single-selection List Box enables only one choice. In this case, a list box resembles a group of option buttons, except that a list box can handle a large number of items more efficiently.
Multiple selection List Box − A multiple selection List Box enables either one choice or contiguous (adjacent) choices.
Multiple selection List Box − A multiple selection List Box enables either one choice or contiguous (adjacent) choices.
Extended-selection List Box − An extended-selection List Box enables one choice, contiguous choices and noncontiguous (or disjointed) choices.
Extended-selection List Box − An extended-selection List Box enables one choice, contiguous choices and noncontiguous (or disjointed) choices.
You can select one of these types of List Boxes, from the Properties window.
Right click on the UserForm.
Select View Code from the dropdown list. The code window of UserForm opens.
Click Initialize in the top right box of the code window.
Type the following under Private Sub UserForm_Initialize().
ProjectCodes.List = Array ("Proj2016-1", "Proj2016-2", "Proj2016-3", "Proj20164", "Proj2016-5")
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Next, you can write code for actions on selecting an item in the list. Otherwise, you can just display the text that is selected, which is the case for filling the Project Code in the Report.
You can use ComboBox that combines a text box with a list box to create a dropdown list box. A combo box is more compact than a list box but requires the user to click the down arrow to display the list of items. Use a combo box to choose only one item from the list.
Insert a ComboBox on the UserForm.
Click the ComboBox.
Type ProjectCodes2 for Name in the Properties window of the ComboBox.
Right click on the UserForm.
Select View Code from the dropdown list.
The code window of UserForm opens.
Type the following as shown below.
ProjectCodes2.List = Array ("Proj2016-1", "Proj2016-2", "Proj2016-3", "Proj20164", "Proj2016-5")
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Click the down arrow to display the list of items.
Click on the required item, say, Project2016-5. The selected option will be displayed in the combo box.
You can use check boxes to select one or more options that are displayed by clicking in the boxes. The options will have labels and you can clearly visualize what options are selected.
A check box can have two states −
Selected (turned on), denoted by a tick mark in the box
Cleared (turned off), denoted by a clear box
You can use check boxes for selection of options in a combo box to save space. In such a case, the check box can have a third state also −
Mixed, meaning a combination of on and off states, denoted by a black dot in the box. This will be displayed to indicate multiple selections in the combo box with check boxes.
Mixed, meaning a combination of on and off states, denoted by a black dot in the box. This will be displayed to indicate multiple selections in the combo box with check boxes.
Insert check boxes in the UserForm as shown below.
Insert check boxes in the UserForm as shown below.
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Click in the boxes for your selected options.
You can use an option button, also known as the radio button to make a single choice within a limited set of mutually exclusive choices. An option button is usually contained in a group box or a frame.
An option button is represented by a small circle. An option button can have one of the following two states −
Selected (turned on), denoted by a dot in the circle
Cleared (turned off), denoted by a blank
You can use a frame control, also referred to as a group box to group related controls into one visual unit. Typically, option buttons, check boxes or closely related contents are grouped in a frame control.
A frame control is represented by a rectangular object with an optional label.
Insert a frame with caption “Choice”.
Insert a frame with caption “Choice”.
Insert two option buttons with captions “Yes” and “No” in the frame control. The options Yes and No are mutually exclusive.
Insert two option buttons with captions “Yes” and “No” in the frame control. The options Yes and No are mutually exclusive.
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Click on your selected option.
You can use a toggle button to indicate a state, such as Yes or No, or a mode, such as on or off. The button alternates between an enabled and a disabled state when it is clicked.
Insert a toggle button on UserForm as shown below −
Click the Run tab on the Ribbon.
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list. The toggle button will be in enabled state by default.
Select Run Sub/UserForm from the dropdown list. The toggle button will be in enabled state by default.
Click the toggle button. The toggle button will be disabled.
If you click the toggle button again, it will be enabled.
You can use a command button to run a macro that performs some actions when the user clicks on it. You have already learnt how to use a command button on a worksheet to run a macro.
Command button is also referred to as a push button. Insert a command button on the UserForm as shown below −
Right click on the command button.
Type the following code in the sub Commandbutton1_click ().
ProjectCodes2.DropDown
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Click the command button. The dropdown list of combo box opens, as it is the action that you have written in the code.
You can insert a tab strip that resembles Excel tabs on the UserForm.
You can use a scroll bar to scroll through a range of values by clicking on the scroll arrows or by dragging the scroll box.
Insert a scroll bar on the UserForm by drawing it at the required position and adjust the length of the scroll bar.
Right click on the scroll bar.
Select View Code from the dropdown list. The Code window opens.
Add the following line under sub ScrollBar1_Scroll().
TextBox2.Text = "Scrolling Values"
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Drag the scroll box. The Text – Scrolling Values will be displayed in the text box as you specified it as the action for scroll bar scroll.
You can use the MsgBox () function to display a message when you click on something. It can be a guideline or some information or a warning or an error alert.
For example, you can display a message that values are being scrolled when you start scrolling the scroll box.
You can use message-box icon displays that portray the specific message. You have the multiple message box icons to suit your purpose −
Type the following code under ScrollBar1_scroll.
MsgBox "Select Ok or Cancel", vbOKCancel, "OK - Cancel Message"
MsgBox "It's an Error!", vbCritical, "Run time result"
MsgBox "Why this value", vbQuestion, "Run time result"
MsgBox "Value Been for a Long Time", vbInformation, "Run time result"
MsgBox "Oh Is it so", vbExclamation, "Run time result"
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list.
Drag the scroll box.
You will get the following message boxes successively.
Now, you have an understanding of the different controls that you can use on a UserForm. Select the controls, group them if required and arrange them on the UserForm as per some meaningful sequence. Write the required actions as code corresponding to the respective controls.
Refer to the VBA tutorial in this tutorials library for an example of UserForm.
You have learnt that the macro is stored as VBA code in Excel. You have also learnt that you can directly write code to create a macro in VBA editor. However, as with the case with any code, even the macro code can have defects and the macro may not run as you expected.
This requires examining the code to find the defects and correct them. The term that is used for this activity in software development is debugging.
VBA editor allows you to pause the execution of the code and perform any required debug task. Following are some of the debugging tasks that you can do.
Stepping Through Code
Using Breakpoints
Backing Up or Moving Forward in Code
Not Stepping Through Each Line of Code
Querying Anything While Stepping Through Code
Halting the Execution
These are just some of the tasks that you might perform in VBA's debugging environment.
The first thing that you have to do for debugging is to step through the code while executing it. If you have an idea of which part of the code is probably producing the defect, you can jump to that line of the code. Otherwise, you can execute the code line by line, backing up or moving forward in the code.
You can step into the code either from Macro dialog box in your workbook or from the VBA editor itself.
Stepping into the code from the workbook
To step into the code from the workbook, do the following −
Click the VIEW tab on the Ribbon.
Click Macros.
Select View Macros from the dropdown list.
The Macro dialog box appears.
Click the macro name.
Click the Step into button.
VBA editor opens and the macro code appears in the code window. The first line in the macro code will be highlighted in yellow color.
Stepping into the code from the VBA editor
To step into the code from the VBA editor, do the following −
Click the DEVELOPER tab on the Ribbon.
Click Visual Basic. The VBA editor opens.
Click the module that contains the macro code.
The macro code appears in the code window.
Click the Debug tab on the Ribbon.
Click the Debug tab on the Ribbon.
Select Step into from the dropdown list.
Select Step into from the dropdown list.
The first line in the macro code will be highlighted. The code is in the debugging mode and the options in the Debug dropdown list will become active.
You can move forward or backward in the code by selecting Step Over or Step Out.
You can avoid stepping through each line code, if you identify a potential part of the code that needs to be discussed, by selecting Run to Cursor.
Alternatively, you can set breakpoints at specific lines of code and execute the code, observing the results at each breakpoint. You can toggle a breakpoint and clear all breakpoints if and when required.
You can add a watch while debugging, to evaluate an expression and stop the execution when a variable attains a specific value. This means that you configure a watch expression, which will be monitored until it is true and then the macro will halt and leave you in break mode. VBA provides you with several watch types to select from, in order to accomplish what you are looking for.
During debugging, at any point of time, if you have found a clue on what is going wrong, you can halt the execution to decipher further.
If you are an experienced developer, the debugging terminology is familiar to you and VBA editor debugging options make your life simple. Even otherwise, it will not take much time to master this skill if you have learnt VBA and understand the code.
You can record a macro and save it with the name Auto_Open to run it whenever you open the workbook that contains this macro.
You can also write VBA code for the same purpose with the Open event of the workbook. The Open event runs the code in the sub procedure Workbook_Open () every time you open the workbook.
You can record an Auto_Run macro as follows −
Click the VIEW tab on the Ribbon.
Click Macros.
Click Record Macro. The Record Macro dialog box appears.
Type Auto_Run for the macro name.
Type a description and click OK.
Start recording the macro.
Stop Recording.
Save the workbook as macro enabled workbook.
Close the workbook.
Open the workbook. The macro Auto_Run will run automatically.
If you want Excel to start without running an Auto_Open macro, hold the SHIFT key when you start Excel.
The following are the limitations of Auto_Open macro −
If the workbook in which you saved the Auto_Open macro contains code for workbook Open event, the code for the Open event will override the actions in the Auto_Open macro.
If the workbook in which you saved the Auto_Open macro contains code for workbook Open event, the code for the Open event will override the actions in the Auto_Open macro.
An Auto_Open macro is ignored when the workbook is opened by running code that uses the Open method.
An Auto_Open macro is ignored when the workbook is opened by running code that uses the Open method.
An Auto_Open macro runs before any other workbooks open. Hence, if you record actions that you want Excel to perform on the default Book1 workbook or on a workbook that is loaded from the XLStart folder, the Auto_Open macro will fail when you restart Excel, because the macro runs before the default and startup workbooks open.
An Auto_Open macro runs before any other workbooks open. Hence, if you record actions that you want Excel to perform on the default Book1 workbook or on a workbook that is loaded from the XLStart folder, the Auto_Open macro will fail when you restart Excel, because the macro runs before the default and startup workbooks open.
If you encounter any of these limitations, instead of recording an Auto_Open macro, you must write a code for the Open event as described in the next section.
You can write code that will get executed when you open a workbook. VBA provides you with an event called open that incorporates a VBA procedure for the actions to be done on opening a workbook.
Open the workbook in which you stored the macro that you have written for the absolute references – Report_ProjectXYZ. When this macro is run, a new worksheet will be added in the workbook and the project report structure appears on the new worksheet.
You can write a macro code that will perform these actions when you open the workbook. That means when you open the Project Report workbook, a new worksheet with the report structure will be ready for you to enter the details.
Follow the below given procedure in VBA editor−
Double click on ThisWorkbook in Projects Explorer.
Double click on ThisWorkbook in Projects Explorer.
In the code window, select Workbook in the left dropdown list and Open in the right dropdown list. Sub Workbook_Open () appears.
In the code window, select Workbook in the left dropdown list and Open in the right dropdown list. Sub Workbook_Open () appears.
Click Modules in the Projects Explorer.
Click Modules in the Projects Explorer.
Double click on the module name that contains the macro code.
Double click on the module name that contains the macro code.
Copy the macro code from the module and paste it in the Sub WorkBook_Open ().
Copy the macro code from the module and paste it in the Sub WorkBook_Open ().
Save the macro-enabled workbook. Open it again. The macro runs and a new worksheet with the report structure is inserted.
102 Lectures
10 hours
Pavan Lalwani
101 Lectures
6 hours
Pavan Lalwani
56 Lectures
5.5 hours
Pavan Lalwani
63 Lectures
3.5 hours
Yoda Learning
134 Lectures
8.5 hours
Yoda Learning
33 Lectures
3 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2393,
"s": 2043,
"text": "An Excel macro is an action or a set of actions that you can record, give a name, save and run as many times as you want and whenever you want. When you create a macro, you are recording your mouse clicks and keystrokes. When you run a saved macro, the recorded mouse clicks and keystrokes will be executed in the same sequence as they are recorded."
},
{
"code": null,
"e": 2530,
"s": 2393,
"text": "Macros help you to save time on repetitive tasks involved in data manipulation and data reports that are required to be done frequently."
},
{
"code": null,
"e": 2606,
"s": 2530,
"text": "You can record and run macros with either Excel commands or from Excel VBA."
},
{
"code": null,
"e": 3054,
"s": 2606,
"text": "VBA stands for Visual Basic for Applications and is a simple programming language that is available through Excel Visual Basic Editor (VBE), which is available from the DEVELOPER tab on the Ribbon. When you record a macro, Excel generates VBA code. If you just want to record a macro and run it, there is no need to learn Excel VBA. However, if you want to modify a macro, then you can do it only by modifying the VBA code in the Excel VBA editor."
},
{
"code": null,
"e": 3294,
"s": 3054,
"text": "You will learn how to record a simple macro and run it with Excel commands in the chapter - Creating a Simple Macro. You will learn more about macros and about creating and / or modifying macros from Excel VBA editor in the later chapters."
},
{
"code": null,
"e": 3644,
"s": 3294,
"text": "A macro can be saved in the same workbook from where you recorded it. In that case, you can run the macro from that workbook only and hence you should keep it open. Excel gives you an alternative way to store all your macros. It is the personal macro workbook, where you can save your macros, which enables you to run those macros from any workbook."
},
{
"code": null,
"e": 3751,
"s": 3644,
"text": "You will learn about Personal Macro Workbook in the chapter - Saving all your Macros in a Single Workbook."
},
{
"code": null,
"e": 4074,
"s": 3751,
"text": "Macros will be stored as VBA code in Excel. As with the case of any other code, macro code is also susceptible to malicious code that can run when you open a workbook. This is a threat to your computer. Microsoft provided with the Macro Security facility that helps you in protecting your computer from such macro viruses."
},
{
"code": null,
"e": 4138,
"s": 4074,
"text": "You will learn more about this in the chapter - Macro Security."
},
{
"code": null,
"e": 4433,
"s": 4138,
"text": "While recording a macro, you can use either absolute references or relative references for the cells on which you are clicking. Absolute references make your macro run at the same cells where you recorded the macro. On the other hand, relative references make your macro run at the active cell."
},
{
"code": null,
"e": 4559,
"s": 4433,
"text": "You will learn about these in the chapters - Using Absolute References for a Macro and Using Relative References for a Macro."
},
{
"code": null,
"e": 4825,
"s": 4559,
"text": "You can record and run macros from Excel even if you do not know Excel VBA. However, if you have to modify a recorded macro or create a macro by writing VBA code, you should learn Excel VBA. You can refer to the Excel VBA tutorial in this tutorials library for this"
},
{
"code": null,
"e": 5002,
"s": 4825,
"text": "However, you should know how to view the macro code. You can learn how to access VBA editor in Excel and about the different parts of the VBA editor in the chapter – Excel VBA."
},
{
"code": null,
"e": 5144,
"s": 5002,
"text": "You can learn how to view the macro code in Excel VBA editor and you can understand the macro code in the chapter - Understanding Macro Code."
},
{
"code": null,
"e": 5351,
"s": 5144,
"text": "You can assign a macro to an object such as a shape or a graphic or a control. Then, you can run the macro by clicking on that object. You will learn about this in the chapter - Assigning Macros to Objects."
},
{
"code": null,
"e": 5547,
"s": 5351,
"text": "Excel provides several ways to run a macro. You can choose the way you want to run a macro. You will learn about these different possible ways of running a macro in the chapter - Running a Macro."
},
{
"code": null,
"e": 5726,
"s": 5547,
"text": "If you decide to write the macro code, you can learn it in the chapter - Creating a Macro Using VBA Editor. However, the prerequisite is that you should have Excel VBA knowledge."
},
{
"code": null,
"e": 6029,
"s": 5726,
"text": "You can modify macro code in Excel VBA editor. If you want to make extensive changes, you should have Excel VBA knowledge. But, if you want to make only minor changes to the code or if you want to copy the VBA code from a recorded macro to another macro, you can refer to the chapter - Editing a Macro."
},
{
"code": null,
"e": 6124,
"s": 6029,
"text": "You can rename a macro and even delete it. You will learn about this also in the same chapter."
},
{
"code": null,
"e": 6439,
"s": 6124,
"text": "A Form is normally used to collect required information. It will be self-explanatory making the task simple. Excel User Forms created from Excel VBA editor serve the same purpose, providing the familiar options such as text boxes, check boxes, radio buttons, list boxes, combo boxes, scroll bars, etc. as controls."
},
{
"code": null,
"e": 6547,
"s": 6439,
"text": "You will learn how to create a User Form and how to use the different controls in the chapter – User Forms."
},
{
"code": null,
"e": 6849,
"s": 6547,
"text": "At times, a macro may not run as expected. You might have created the macro or you might be using a macro supplied to you by someone. You can debug the macro code just as you debug any other code to uncover the defects and correct them. You will learn about this in the chapter - Debugging Macro Code."
},
{
"code": null,
"e": 7105,
"s": 6849,
"text": "You can make your macro run automatically when you open a workbook. You can do this either by creating an Auto_Run macro or by writing VBA code for workbook open event. You will learn this in the chapter - Configuring a Macro to Run on Opening a Workbook."
},
{
"code": null,
"e": 7314,
"s": 7105,
"text": "You can create a macro with Excel commands by recording the key strokes and mouse clicks, giving the macro a name and specifying how to store the macro. A macro thus recorded can be run with an Excel command."
},
{
"code": null,
"e": 7395,
"s": 7314,
"text": "Suppose you have to collect certain results repeatedly in the following format −"
},
{
"code": null,
"e": 7475,
"s": 7395,
"text": "Instead of creating the table each time, you can have a macro to do it for you."
},
{
"code": null,
"e": 7512,
"s": 7475,
"text": "To record a macro do the following −"
},
{
"code": null,
"e": 7546,
"s": 7512,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 7580,
"s": 7546,
"text": "Click Macros in the Macros group."
},
{
"code": null,
"e": 7624,
"s": 7580,
"text": "Select Record Macro from the dropdown list."
},
{
"code": null,
"e": 7661,
"s": 7624,
"text": "The Record Macro dialog box appears."
},
{
"code": null,
"e": 7702,
"s": 7661,
"text": "Type MyFirstMacro in the Macro name box."
},
{
"code": null,
"e": 7743,
"s": 7702,
"text": "Type MyFirstMacro in the Macro name box."
},
{
"code": null,
"e": 7800,
"s": 7743,
"text": "Type A Simple Macro in the Description box and click OK."
},
{
"code": null,
"e": 7857,
"s": 7800,
"text": "Type A Simple Macro in the Description box and click OK."
},
{
"code": null,
"e": 7939,
"s": 7857,
"text": "Remember that whatever key strokes and mouse clicks you do, will be recorded now."
},
{
"code": null,
"e": 7961,
"s": 7939,
"text": "Click in the cell B2."
},
{
"code": null,
"e": 7983,
"s": 7961,
"text": "Click in the cell B2."
},
{
"code": null,
"e": 8001,
"s": 7983,
"text": "Create the table."
},
{
"code": null,
"e": 8019,
"s": 8001,
"text": "Create the table."
},
{
"code": null,
"e": 8063,
"s": 8019,
"text": "Click in a different cell in the worksheet."
},
{
"code": null,
"e": 8107,
"s": 8063,
"text": "Click in a different cell in the worksheet."
},
{
"code": null,
"e": 8141,
"s": 8107,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 8175,
"s": 8141,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 8189,
"s": 8175,
"text": "Click Macros."
},
{
"code": null,
"e": 8203,
"s": 8189,
"text": "Click Macros."
},
{
"code": null,
"e": 8249,
"s": 8203,
"text": "Select Stop Recording from the dropdown list."
},
{
"code": null,
"e": 8295,
"s": 8249,
"text": "Select Stop Recording from the dropdown list."
},
{
"code": null,
"e": 8330,
"s": 8295,
"text": "Your macro recording is completed."
},
{
"code": null,
"e": 8577,
"s": 8330,
"text": "The first step to click on a particular cell is important as it tells where exactly the macro has to start placing the recorded steps. Once you are done with the recording, you have to click Stop Recording to avoid recording of unnecessary steps."
},
{
"code": null,
"e": 8684,
"s": 8577,
"text": "You can run the macro you have recorded any number of times you want. To run the macro, do the following −"
},
{
"code": null,
"e": 8710,
"s": 8684,
"text": "Click on a new worksheet."
},
{
"code": null,
"e": 8755,
"s": 8710,
"text": "Note the active cell. In our case, it is A1."
},
{
"code": null,
"e": 8789,
"s": 8755,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 8823,
"s": 8789,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 8837,
"s": 8823,
"text": "Click Macros."
},
{
"code": null,
"e": 8851,
"s": 8837,
"text": "Click Macros."
},
{
"code": null,
"e": 8894,
"s": 8851,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 8937,
"s": 8894,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 8967,
"s": 8937,
"text": "The Macro dialog box appears."
},
{
"code": null,
"e": 9028,
"s": 8967,
"text": "Only the macro that you recorded appears in the Macros list."
},
{
"code": null,
"e": 9248,
"s": 9028,
"text": "Click the macro name – MyFirstMacro in the Macro dialog box. The description you typed while recording the macro will get displayed. Macro description allows you to identify for what purpose you have recorded the macro."
},
{
"code": null,
"e": 9468,
"s": 9248,
"text": "Click the macro name – MyFirstMacro in the Macro dialog box. The description you typed while recording the macro will get displayed. Macro description allows you to identify for what purpose you have recorded the macro."
},
{
"code": null,
"e": 9594,
"s": 9468,
"text": "Click the Run button. The same table that you have created while recording the macro will appear in just a split of a second."
},
{
"code": null,
"e": 9720,
"s": 9594,
"text": "Click the Run button. The same table that you have created while recording the macro will appear in just a split of a second."
},
{
"code": null,
"e": 9843,
"s": 9720,
"text": "You have discovered the magic wand that Excel provides you to save time on mundane tasks. You will observe the following −"
},
{
"code": null,
"e": 9956,
"s": 9843,
"text": "Though the active cell before running the macro was A1, the table is placed in the cell B2 as you have recorded."
},
{
"code": null,
"e": 10069,
"s": 9956,
"text": "Though the active cell before running the macro was A1, the table is placed in the cell B2 as you have recorded."
},
{
"code": null,
"e": 10169,
"s": 10069,
"text": "In addition, the active cell became E2, as you have clicked that cell before you stopped recording."
},
{
"code": null,
"e": 10269,
"s": 10169,
"text": "In addition, the active cell became E2, as you have clicked that cell before you stopped recording."
},
{
"code": null,
"e": 10511,
"s": 10269,
"text": "You can run the macro in multiple worksheets with different active cells before running the macro and observe the same conditions as given above. Just keep a note of this and you will understand later in this tutorial why it has occurred so."
},
{
"code": null,
"e": 10662,
"s": 10511,
"text": "You can also have a macro recording that places your recorded steps in the active cell. You will learn how to do this as you progress in the tutorial."
},
{
"code": null,
"e": 10755,
"s": 10662,
"text": "You might wonder how to save the macros that are created. In this context you need to know −"
},
{
"code": null,
"e": 10771,
"s": 10755,
"text": "Storing a macro"
},
{
"code": null,
"e": 10799,
"s": 10771,
"text": "Saving a macro enabled file"
},
{
"code": null,
"e": 10932,
"s": 10799,
"text": "As and when you create a macro, you can choose where to store that particular macro. You can do this in the Record Macro dialog box."
},
{
"code": null,
"e": 11008,
"s": 10932,
"text": "Click the box - Store macro in. The following three options are available −"
},
{
"code": null,
"e": 11023,
"s": 11008,
"text": "This Workbook."
},
{
"code": null,
"e": 11037,
"s": 11023,
"text": "New Workbook."
},
{
"code": null,
"e": 11061,
"s": 11037,
"text": "Personal Macro Workbook"
},
{
"code": null,
"e": 11173,
"s": 11061,
"text": "This is the default option. The macro will be stored in your current workbook from where you created the macro."
},
{
"code": null,
"e": 11328,
"s": 11173,
"text": "This option, though available, is not recommended. You will be asking Excel to store the macro in a different new workbook and mostly it is not necessary."
},
{
"code": null,
"e": 11545,
"s": 11328,
"text": "If you create several macros that you use across your workbooks, Personal Macro Workbook provides you with the facility to store all the macros at one place. You will learn more about this option in the next chapter."
},
{
"code": null,
"e": 11673,
"s": 11545,
"text": "If you had chosen This Workbook as the option for storing the macro, you would need to save your workbook along with the macro."
},
{
"code": null,
"e": 11898,
"s": 11673,
"text": "Try to save the workbook. By default, you would be asking Excel to save the workbook as an .xls file. Excel displays a message saying that an Excel feature VB project cannot be saved in a macro free workbook, as shown below."
},
{
"code": null,
"e": 12182,
"s": 11898,
"text": "Note − If you click Yes, Excel will save your workbook as a macro free .xls file and your macro that you stored with This Workbook option will not get saved. To avoid this, Excel provides you an option to save your workbook as a macro-enabled workbook that will have .xlsm extension."
},
{
"code": null,
"e": 12219,
"s": 12182,
"text": "Click No in the warning message box."
},
{
"code": null,
"e": 12285,
"s": 12219,
"text": "Select Excel Macro-Enabled Workbook (*.xlsm) in the Save as type."
},
{
"code": null,
"e": 12297,
"s": 12285,
"text": "Click Save."
},
{
"code": null,
"e": 12365,
"s": 12297,
"text": "You will learn more about these in later chapters in this tutorial."
},
{
"code": null,
"e": 12856,
"s": 12365,
"text": "Excel provides you with a facility to store all your macros in a single workbook. The workbook is called Personal Macro Workbook - Personal.xlsb. It is a hidden workbook stored on your computer, which opens every time you open Excel. This enables you to run your macros from any workbook. There will be a single Personal Macro Workbook per computer and you cannot share it across computers. You can view and run the macros in your Personal Macro Workbook from any workbook on your computer."
},
{
"code": null,
"e": 12974,
"s": 12856,
"text": "You can save macros in your Personal Macro Workbook by selecting it as the storing option while recording the macros."
},
{
"code": null,
"e": 13064,
"s": 12974,
"text": "Select Personal Macro Workbook from the drop down list under the category Store macro in."
},
{
"code": null,
"e": 13090,
"s": 13064,
"text": "Record your second macro."
},
{
"code": null,
"e": 13156,
"s": 13090,
"text": "Give macro details in the Record Macro dialog box as shown below."
},
{
"code": null,
"e": 13166,
"s": 13156,
"text": "Click OK."
},
{
"code": null,
"e": 13220,
"s": 13166,
"text": "Your recording starts. Create a table as shown below."
},
{
"code": null,
"e": 13236,
"s": 13220,
"text": "Stop recording."
},
{
"code": null,
"e": 13252,
"s": 13236,
"text": "Stop recording."
},
{
"code": null,
"e": 13286,
"s": 13252,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 13320,
"s": 13286,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 13334,
"s": 13320,
"text": "Click Macros."
},
{
"code": null,
"e": 13348,
"s": 13334,
"text": "Click Macros."
},
{
"code": null,
"e": 13421,
"s": 13348,
"text": "Select View Macros from the dropdown list. The Macro dialog box appears."
},
{
"code": null,
"e": 13494,
"s": 13421,
"text": "Select View Macros from the dropdown list. The Macro dialog box appears."
},
{
"code": null,
"e": 13607,
"s": 13494,
"text": "The macro name appears with a prefix PERSONAL.XLSB! indicating that the Macro is in the Personal Macro Workbook."
},
{
"code": null,
"e": 13715,
"s": 13607,
"text": "Save your workbook. It will get saved as an .xls file as the macro is not in your workbook and close Excel."
},
{
"code": null,
"e": 13812,
"s": 13715,
"text": "You will get the following message regarding saving the changes to the Personal Macro Workbook −"
},
{
"code": null,
"e": 13899,
"s": 13812,
"text": "Click the Save button. Your macro is saved in the Personal.xlsb file on your computer."
},
{
"code": null,
"e": 14086,
"s": 13899,
"text": "Personal Macro Workbook will be hidden, by default. When you start Excel, the personal macro workbook is loaded but you cannot see it because it is hidden. You can unhide it as follows −"
},
{
"code": null,
"e": 14120,
"s": 14086,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 14154,
"s": 14120,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 14188,
"s": 14154,
"text": "Click Unhide in the Window group."
},
{
"code": null,
"e": 14222,
"s": 14188,
"text": "Click Unhide in the Window group."
},
{
"code": null,
"e": 14253,
"s": 14222,
"text": "The Unhide dialog box appears."
},
{
"code": null,
"e": 14316,
"s": 14253,
"text": "PERSONAL.XLSB appears in the Unhide workbook box and click OK."
},
{
"code": null,
"e": 14382,
"s": 14316,
"text": "Now you can view the macros saved in the personal macro workbook."
},
{
"code": null,
"e": 14438,
"s": 14382,
"text": "To hide the personal macro workbook, do the following −"
},
{
"code": null,
"e": 14476,
"s": 14438,
"text": "Click on the personal macro workbook."
},
{
"code": null,
"e": 14510,
"s": 14476,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 14536,
"s": 14510,
"text": "Click Hide on the Ribbon."
},
{
"code": null,
"e": 14721,
"s": 14536,
"text": "You can run the macros saved in personal macro workbook from any workbook. To run the macros, it does not make any difference whether the personal macro workbook is hidden or unhidden."
},
{
"code": null,
"e": 14740,
"s": 14721,
"text": "Click View Macros."
},
{
"code": null,
"e": 14784,
"s": 14740,
"text": "Select the macro name from the macros list."
},
{
"code": null,
"e": 14826,
"s": 14784,
"text": "Click the Run button. The macro will run."
},
{
"code": null,
"e": 14972,
"s": 14826,
"text": "You can add more macros in personal macro workbook by selecting it for Store macro in option while recording the macros, as you had seen earlier."
},
{
"code": null,
"e": 15035,
"s": 14972,
"text": "You can delete a macro in personal macro workbook as follows −"
},
{
"code": null,
"e": 15091,
"s": 15035,
"text": "Make sure that the personal macro workbook is unhidden."
},
{
"code": null,
"e": 15143,
"s": 15091,
"text": "Click the macro name in the View Macros dialog box."
},
{
"code": null,
"e": 15168,
"s": 15143,
"text": "Click the Delete button."
},
{
"code": null,
"e": 15284,
"s": 15168,
"text": "If the personal macro workbook is hidden, you will get a message saying “Cannot edit a macro on a hidden workbook”."
},
{
"code": null,
"e": 15350,
"s": 15284,
"text": "Unhide the personal macro workbook and delete the selected macro."
},
{
"code": null,
"e": 15606,
"s": 15350,
"text": "The macro will not appear in the macros list. However, when you create a new macro and save it in your personal workbook or delete any macros that it contains, you will be prompted to save the personal workbook just as in the case you saved it first time."
},
{
"code": null,
"e": 15907,
"s": 15606,
"text": "The macros that you create in Excel would be written in the programming language VBA (Visual Basic for Applications). You will learn about the Excel macro code in later chapters. As you are aware, when there is an executable code, there is a threat of viruses. Macros are also susceptible to viruses."
},
{
"code": null,
"e": 16364,
"s": 15907,
"text": "Excel VBA in which the Macros are written has access to most Windows system calls and executes automatically when workbooks are opened. Hence, there is a potential threat of the existence of a virus written as a macro and is hidden within Excel that are executed on opening a workbook. Therefore, Excel macros can be very dangerous to your computer in many ways. However, Microsoft has taken appropriate measures to shield the workbooks from macro viruses."
},
{
"code": null,
"e": 16478,
"s": 16364,
"text": "Microsoft has introduced macro security so that you can identify which macros you can trust and which you cannot."
},
{
"code": null,
"e": 16548,
"s": 16478,
"text": "The most important Excel macro security feature is - file extensions."
},
{
"code": null,
"e": 16746,
"s": 16548,
"text": "Excel workbooks will be saved with .xlsx file extension by default. You can always trust workbooks with .xlsx file extension, as they are incapable of storing a macro and will not carry any threat."
},
{
"code": null,
"e": 17045,
"s": 16746,
"text": "Excel workbooks with macros are saved with .xlsm file extension. They are termed as Macro Enabled Excel Workbooks. Before you open such workbooks, you should make sure that the macros they contain are not malicious. For this, you must ensure that you can trust the origin of this type of workbooks."
},
{
"code": null,
"e": 17106,
"s": 17045,
"text": "Excel provides three ways to trust a macro enabled workbook."
},
{
"code": null,
"e": 17162,
"s": 17106,
"text": "Placing the macro enabled workbooks in a trusted folder"
},
{
"code": null,
"e": 17218,
"s": 17162,
"text": "Placing the macro enabled workbooks in a trusted folder"
},
{
"code": null,
"e": 17258,
"s": 17218,
"text": "Checking if a macro is digitally signed"
},
{
"code": null,
"e": 17298,
"s": 17258,
"text": "Checking if a macro is digitally signed"
},
{
"code": null,
"e": 17370,
"s": 17298,
"text": "Enabling security alert messages before opening macro enabled workbooks"
},
{
"code": null,
"e": 17442,
"s": 17370,
"text": "Enabling security alert messages before opening macro enabled workbooks"
},
{
"code": null,
"e": 17729,
"s": 17442,
"text": "This is the easiest and best way to manage macro security. Excel allows you to designate a folder as a trusted location. Place all your macro-enabled workbooks in that trusted folder. You can open macro-enabled workbooks that are saved to this location without warnings or restrictions."
},
{
"code": null,
"e": 17980,
"s": 17729,
"text": "Digital signatures confirm the identity of the author. You can configure Excel to run digitally signed macros from trusted persons without warnings or restrictions. Excel will also warn the recipient if it has been changed since the author signed it."
},
{
"code": null,
"e": 18181,
"s": 17980,
"text": "When you open a workbook, Excel warns you that the workbook contains macros and asks whether you wish to enable them. You can click the Enable Content button if the source of the workbook is reliable."
},
{
"code": null,
"e": 18262,
"s": 18181,
"text": "You can set any of these three options in the Trust Center in the Excel Options."
},
{
"code": null,
"e": 18589,
"s": 18262,
"text": "If you work in an organization, the system administrator might have changed the default settings to prevent anyone from changing the settings. Microsoft advises that you do not change security settings in the Trust Center as the consequences can be loss of data, data theft or security compromises on your computer or network."
},
{
"code": null,
"e": 18831,
"s": 18589,
"text": "However, you can learn the macro security settings in the following sections and check if they are to be changed. You have to use your own instinct to decide on any of these options based on the context and your knowledge of the file origin."
},
{
"code": null,
"e": 18951,
"s": 18831,
"text": "The macro settings are located in the Trust Center in the Excel Options. To access the Trust Center, do the following −"
},
{
"code": null,
"e": 18985,
"s": 18951,
"text": "Click the FILE tab on the Ribbon."
},
{
"code": null,
"e": 19019,
"s": 18985,
"text": "Click the FILE tab on the Ribbon."
},
{
"code": null,
"e": 19072,
"s": 19019,
"text": "Click Options. The Excel Options dialog box appears."
},
{
"code": null,
"e": 19125,
"s": 19072,
"text": "Click Options. The Excel Options dialog box appears."
},
{
"code": null,
"e": 19163,
"s": 19125,
"text": "Click Trust Center in the left pane. "
},
{
"code": null,
"e": 19201,
"s": 19163,
"text": "Click Trust Center in the left pane. "
},
{
"code": null,
"e": 19276,
"s": 19201,
"text": "Click the Trust Center Settings button under Microsoft Excel Trust Center."
},
{
"code": null,
"e": 19351,
"s": 19276,
"text": "Click the Trust Center Settings button under Microsoft Excel Trust Center."
},
{
"code": null,
"e": 19388,
"s": 19351,
"text": "The Trust Center dialog box appears."
},
{
"code": null,
"e": 19555,
"s": 19388,
"text": "You will see various options available in the Excel Trust Center in the left pane. You will learn about the options related to Excel macros in the following sections."
},
{
"code": null,
"e": 19603,
"s": 19555,
"text": "Macro settings are located in the Trust Center."
},
{
"code": null,
"e": 19653,
"s": 19603,
"text": "Under Macro Settings, four options are available."
},
{
"code": null,
"e": 19775,
"s": 19653,
"text": "Disable all macros without notification − If this option is chosen, Macros and security alerts about macros are disabled."
},
{
"code": null,
"e": 19897,
"s": 19775,
"text": "Disable all macros without notification − If this option is chosen, Macros and security alerts about macros are disabled."
},
{
"code": null,
"e": 20060,
"s": 19897,
"text": "Disable all macros with notification − Macros are disabled, but security alerts appear if there are macros present. You can enable macros on a case-by-case basis."
},
{
"code": null,
"e": 20223,
"s": 20060,
"text": "Disable all macros with notification − Macros are disabled, but security alerts appear if there are macros present. You can enable macros on a case-by-case basis."
},
{
"code": null,
"e": 20573,
"s": 20223,
"text": "Disable all macros except digitally signed macros − Macros are disabled but security alerts appear if there are macros present. However, if the macro is digitally signed by a trusted publisher, the macro runs if you trust the publisher. If you have do not trust the publisher, you will be notified to enable the signed macro and trust the publisher."
},
{
"code": null,
"e": 20923,
"s": 20573,
"text": "Disable all macros except digitally signed macros − Macros are disabled but security alerts appear if there are macros present. However, if the macro is digitally signed by a trusted publisher, the macro runs if you trust the publisher. If you have do not trust the publisher, you will be notified to enable the signed macro and trust the publisher."
},
{
"code": null,
"e": 21108,
"s": 20923,
"text": "Enable all macros (not recommended, susceptible to macro viruses) − If this option is chosen, all macros run. This setting makes your computer vulnerable to potentially malicious code."
},
{
"code": null,
"e": 21293,
"s": 21108,
"text": "Enable all macros (not recommended, susceptible to macro viruses) − If this option is chosen, all macros run. This setting makes your computer vulnerable to potentially malicious code."
},
{
"code": null,
"e": 21381,
"s": 21293,
"text": "You have an additional security option under Developer Macro Settings with a Check box."
},
{
"code": null,
"e": 21970,
"s": 21381,
"text": "Trust access to the VBA project object model.\n\nThis option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client.\nThis security option is for code written to automate an Office program and manipulate the VBA environment and object model.\nIt is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code.\nFor automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box.\n\n"
},
{
"code": null,
"e": 22016,
"s": 21970,
"text": "Trust access to the VBA project object model."
},
{
"code": null,
"e": 22138,
"s": 22016,
"text": "This option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client."
},
{
"code": null,
"e": 22260,
"s": 22138,
"text": "This option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client."
},
{
"code": null,
"e": 22384,
"s": 22260,
"text": "This security option is for code written to automate an Office program and manipulate the VBA environment and object model."
},
{
"code": null,
"e": 22508,
"s": 22384,
"text": "This security option is for code written to automate an Office program and manipulate the VBA environment and object model."
},
{
"code": null,
"e": 22661,
"s": 22508,
"text": "It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code."
},
{
"code": null,
"e": 22814,
"s": 22661,
"text": "It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code."
},
{
"code": null,
"e": 22955,
"s": 22814,
"text": "For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box."
},
{
"code": null,
"e": 23096,
"s": 22955,
"text": "For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box."
},
{
"code": null,
"e": 23334,
"s": 23096,
"text": "If you think that a macro-enabled workbook is from a reliable source, it is better to move the file to the trusted location identified by Excel, instead of changing the default Trust Center settings to a less-safe macro security setting."
},
{
"code": null,
"e": 23396,
"s": 23334,
"text": "You can find the trusted folder settings in the Trust Center."
},
{
"code": null,
"e": 23528,
"s": 23396,
"text": "Click the Trusted Locations in the Trust Center dialog box. The Trusted Locations set by Microsoft Office appear on the right side."
},
{
"code": null,
"e": 23798,
"s": 23528,
"text": "You can add new locations, remove the existing locations and modify the existing locations. The identified trusted locations will be treated by Microsoft office as reliable for opening files. However, if you add or modify a location, ensure that the location is secure."
},
{
"code": null,
"e": 23891,
"s": 23798,
"text": "You can also find the options that office does not recommend, such as locations on internet."
},
{
"code": null,
"e": 24062,
"s": 23891,
"text": "Microsoft provides an option to accommodate digitally signed macros. However, even if a macro is digitally signed, you need to ensure that it is from a trusted publisher."
},
{
"code": null,
"e": 24123,
"s": 24062,
"text": "You will find the trusted publishers in in the Trust Center."
},
{
"code": null,
"e": 24289,
"s": 24123,
"text": "Click Trusted Publishers in the Trust Center dialog box. A list of certificates appear on the right side with the details – Issued To, Issued By and Expiration Date."
},
{
"code": null,
"e": 24455,
"s": 24289,
"text": "Click Trusted Publishers in the Trust Center dialog box. A list of certificates appear on the right side with the details – Issued To, Issued By and Expiration Date."
},
{
"code": null,
"e": 24492,
"s": 24455,
"text": "Select a certificate and click View."
},
{
"code": null,
"e": 24529,
"s": 24492,
"text": "Select a certificate and click View."
},
{
"code": null,
"e": 24571,
"s": 24529,
"text": "The certificate information is displayed."
},
{
"code": null,
"e": 24818,
"s": 24571,
"text": "As you have learnt earlier in this chapter, you can set an option to run a macro that is digitally signed only if you trust the publisher. If you do not trust the publisher, you will be notified to enable the signed macro and trust the publisher."
},
{
"code": null,
"e": 24997,
"s": 24818,
"text": "The Message Bar displays security alert when there are macros in the file that you are opening. The yellow Message Bar with a shield icon alerts you that the macros are disabled."
},
{
"code": null,
"e": 25146,
"s": 24997,
"text": "If you know that the macro or macros are from a reliable source, you can click n the Enable Content button on the Message Bar, to enable the macros."
},
{
"code": null,
"e": 25300,
"s": 25146,
"text": "You can disable the Message Bar option if you do not want security alerts. On the other hand, you can enable the Message Bar option to increase security."
},
{
"code": null,
"e": 25372,
"s": 25300,
"text": "You can enable / disable security alerts with Message Bars as follows −"
},
{
"code": null,
"e": 25406,
"s": 25372,
"text": "Click the FILE tab on the Ribbon."
},
{
"code": null,
"e": 25459,
"s": 25406,
"text": "Click Options. The Excel Options dialog box appears."
},
{
"code": null,
"e": 25479,
"s": 25459,
"text": "Click Trust Center."
},
{
"code": null,
"e": 25519,
"s": 25479,
"text": "Click the Trust Center Settings button."
},
{
"code": null,
"e": 25538,
"s": 25519,
"text": "Click Message Bar."
},
{
"code": null,
"e": 25599,
"s": 25538,
"text": "The Message Bar Settings for all Office Applications appear."
},
{
"code": null,
"e": 25654,
"s": 25599,
"text": "There are two options under - Showing the Message Bar."
},
{
"code": null,
"e": 25753,
"s": 25654,
"text": "Option 1 − Show the Message Bar in all applications when active content such as macros is blocked."
},
{
"code": null,
"e": 25856,
"s": 25753,
"text": "This is the default option. The Message Bar appears when potentially unsafe content has been disabled."
},
{
"code": null,
"e": 25959,
"s": 25856,
"text": "This is the default option. The Message Bar appears when potentially unsafe content has been disabled."
},
{
"code": null,
"e": 26129,
"s": 25959,
"text": "If you had selected - Disable all macros without notification in the Macro Settings of the Trust Center, this option is not selected and the Message Bar does not appear."
},
{
"code": null,
"e": 26299,
"s": 26129,
"text": "If you had selected - Disable all macros without notification in the Macro Settings of the Trust Center, this option is not selected and the Message Bar does not appear."
},
{
"code": null,
"e": 26356,
"s": 26299,
"text": "Option 2 − Never show information about blocked content."
},
{
"code": null,
"e": 26513,
"s": 26356,
"text": "If this option if selected, it disables the Message Bar and no alerts appear about security issues, regardless of any security settings in the Trust Center."
},
{
"code": null,
"e": 26872,
"s": 26513,
"text": "Excel macros can be recorded either with absolute references or relative references. A macro recorded with absolute references places the recorded steps exactly in the cells where it was recorded, irrespective of the active cell. On the other hand, a macro recorded with relative references can perform the recorded tasks at different parts on the worksheet."
},
{
"code": null,
"e": 27002,
"s": 26872,
"text": "You will learn about absolute references for macro in this chapter. You will learn about relative references in the next chapter."
},
{
"code": null,
"e": 27111,
"s": 27002,
"text": "Suppose you have to submit a report about your team’s work at the end of every day in the following format −"
},
{
"code": null,
"e": 27194,
"s": 27111,
"text": "Now, the report should be placed in the cell B2 and should be in the given format."
},
{
"code": null,
"e": 27245,
"s": 27194,
"text": "A sample filled in report will be as shown below −"
},
{
"code": null,
"e": 27369,
"s": 27245,
"text": "Except for the data in the following cells, the information is constant for every report that you generate for the project."
},
{
"code": null,
"e": 27391,
"s": 27369,
"text": "C3 – Report for Date."
},
{
"code": null,
"e": 27427,
"s": 27391,
"text": "C13 – No. of Tasks Completed Today."
},
{
"code": null,
"e": 27463,
"s": 27427,
"text": "C14 – Total No. of Tasks Completed."
},
{
"code": null,
"e": 27486,
"s": 27463,
"text": "C15 – % Work Complete."
},
{
"code": null,
"e": 27782,
"s": 27486,
"text": "Of these also, in C3 (Report for Date) you can place the Excel function = TODAY () that places the date of your report without your intervention. Further, in cell C15, you can have the formula C14/C12 and format the cell C15 as percentage to have the % Work Complete calculated by Excel for you."
},
{
"code": null,
"e": 28084,
"s": 27782,
"text": "This leaves you with only two cells – C13 and C14 that need to be filled in by you every day. Hence, it would be ideal to have information for the rest of the cells, every time you have to create the report. This saves time for you and you can do the mundane activity of reporting in just few minutes."
},
{
"code": null,
"e": 28285,
"s": 28084,
"text": "Now, suppose you have to send such reports for three projects. You can imagine the time you can save and take up more challenging work for the day and of course get the accolades from your management."
},
{
"code": null,
"e": 28621,
"s": 28285,
"text": "You can achieve this by recording a macro per project and running them on a day-to-day basis to generate the required reports in a matter of just few minutes. However, every time you run the macro, the report should appear on the worksheet as given above, irrespective of the active cell. For this, you have to use absolute references."
},
{
"code": null,
"e": 28872,
"s": 28621,
"text": "To record a macro with absolute references, you have to ensure that the macro is being recorded starting from the cell where the steps have to start. This means, in the case of the example given in the previous section, you need to do the following −"
},
{
"code": null,
"e": 28899,
"s": 28872,
"text": "Start recording the macro."
},
{
"code": null,
"e": 28923,
"s": 28899,
"text": "Create a new worksheet."
},
{
"code": null,
"e": 28977,
"s": 28923,
"text": "Click in any cell other than B2 in the new worksheet."
},
{
"code": null,
"e": 28999,
"s": 28977,
"text": "Click in the cell B2."
},
{
"code": null,
"e": 29029,
"s": 28999,
"text": "Continue recording the macro."
},
{
"code": null,
"e": 29161,
"s": 29029,
"text": "This will create a new worksheet for every new report and get the report format placed in the cell B2 every time you run the macro."
},
{
"code": null,
"e": 29217,
"s": 29161,
"text": "Note − The first three steps given above are essential."
},
{
"code": null,
"e": 29435,
"s": 29217,
"text": "If you do not create a new worksheet, when you run the macro, it places whatever you recorded on the same worksheet at the same place. This is not what you want. You need to have every report on a different worksheet."
},
{
"code": null,
"e": 29653,
"s": 29435,
"text": "If you do not create a new worksheet, when you run the macro, it places whatever you recorded on the same worksheet at the same place. This is not what you want. You need to have every report on a different worksheet."
},
{
"code": null,
"e": 30082,
"s": 29653,
"text": "If you do not click in a different cell at the beginning of the recording, even if the active cell is B2, Excel places the recorded steps in the active cell. When you run the macro, it will place the recorded report format at any part of the worksheet based on the active cell. By explicitly clicking in a cell other than B2 and then the the cell B2, you are telling the recorder to always place your macro steps in the cell B2."
},
{
"code": null,
"e": 30511,
"s": 30082,
"text": "If you do not click in a different cell at the beginning of the recording, even if the active cell is B2, Excel places the recorded steps in the active cell. When you run the macro, it will place the recorded report format at any part of the worksheet based on the active cell. By explicitly clicking in a cell other than B2 and then the the cell B2, you are telling the recorder to always place your macro steps in the cell B2."
},
{
"code": null,
"e": 30714,
"s": 30511,
"text": "You can start recording the macro with the Record Macro command on the Ribbon under the VIEW tab → Macros. You can also click the Start Recording Macro button present on left side of the Excel task bar."
},
{
"code": null,
"e": 30778,
"s": 30714,
"text": "Start recording the macro. The Record Macro dialog box appears."
},
{
"code": null,
"e": 30842,
"s": 30778,
"text": "Start recording the macro. The Record Macro dialog box appears."
},
{
"code": null,
"e": 30924,
"s": 30842,
"text": "Give a meaningful name to identify the macro as a report of a particular project."
},
{
"code": null,
"e": 31006,
"s": 30924,
"text": "Give a meaningful name to identify the macro as a report of a particular project."
},
{
"code": null,
"e": 31111,
"s": 31006,
"text": "Select This Workbook under Store macro in, as you will produce reports from this specific workbook only."
},
{
"code": null,
"e": 31216,
"s": 31111,
"text": "Select This Workbook under Store macro in, as you will produce reports from this specific workbook only."
},
{
"code": null,
"e": 31263,
"s": 31216,
"text": "Give a description to your macro and click OK."
},
{
"code": null,
"e": 31310,
"s": 31263,
"text": "Give a description to your macro and click OK."
},
{
"code": null,
"e": 31339,
"s": 31310,
"text": "Your macro starts recording."
},
{
"code": null,
"e": 31420,
"s": 31339,
"text": "Create a new worksheet. This ensures your new report will be on a new worksheet."
},
{
"code": null,
"e": 31501,
"s": 31420,
"text": "Create a new worksheet. This ensures your new report will be on a new worksheet."
},
{
"code": null,
"e": 31555,
"s": 31501,
"text": "Click in any cell other than B2 in the new worksheet."
},
{
"code": null,
"e": 31609,
"s": 31555,
"text": "Click in any cell other than B2 in the new worksheet."
},
{
"code": null,
"e": 31700,
"s": 31609,
"text": "Click in the cell B2. This ensures that the macro places your recorded steps in B2 always."
},
{
"code": null,
"e": 31791,
"s": 31700,
"text": "Click in the cell B2. This ensures that the macro places your recorded steps in B2 always."
},
{
"code": null,
"e": 31825,
"s": 31791,
"text": "Create the format for the report."
},
{
"code": null,
"e": 31859,
"s": 31825,
"text": "Create the format for the report."
},
{
"code": null,
"e": 31914,
"s": 31859,
"text": "Fill in the static information for the project report."
},
{
"code": null,
"e": 31969,
"s": 31914,
"text": "Fill in the static information for the project report."
},
{
"code": null,
"e": 32023,
"s": 31969,
"text": "Place = TODAY () in C3 and = C14/C12 in the cell C15."
},
{
"code": null,
"e": 32077,
"s": 32023,
"text": "Place = TODAY () in C3 and = C14/C12 in the cell C15."
},
{
"code": null,
"e": 32106,
"s": 32077,
"text": "Format the cells with dates."
},
{
"code": null,
"e": 32135,
"s": 32106,
"text": "Format the cells with dates."
},
{
"code": null,
"e": 32161,
"s": 32135,
"text": "Stop recording the macro."
},
{
"code": null,
"e": 32362,
"s": 32161,
"text": "You can stop recording the macro either with the Stop Recording command on the Ribbon under VIEW tab → Macros or by clicking the Stop Recording Macro button present on left side of the Excel task bar."
},
{
"code": null,
"e": 32468,
"s": 32362,
"text": "Your Project Report macro is ready. Save the workbook as a macro-enabled workbook (with .xlsm extension)."
},
{
"code": null,
"e": 32551,
"s": 32468,
"text": "You can generate any number of reports in a few seconds just by running the macro."
},
{
"code": null,
"e": 32588,
"s": 32551,
"text": "Click the VIEW button on the Ribbon."
},
{
"code": null,
"e": 32602,
"s": 32588,
"text": "Click Macros."
},
{
"code": null,
"e": 32675,
"s": 32602,
"text": "Select View Macros from the dropdown list. The Macro dialog box appears."
},
{
"code": null,
"e": 32710,
"s": 32675,
"text": "Click the macro Report_ProjectXYZ."
},
{
"code": null,
"e": 32732,
"s": 32710,
"text": "Click the Run button."
},
{
"code": null,
"e": 32836,
"s": 32732,
"text": "A new worksheet will be created in your workbook, with the report stencil created in it in the cell B2."
},
{
"code": null,
"e": 32996,
"s": 32836,
"text": "Relative reference macros record an offset from the active cell. Such macros will be useful if you have to repeat the steps at various places in the worksheet."
},
{
"code": null,
"e": 33147,
"s": 32996,
"text": "Suppose you are required to analyze the data of voters collected from 280 constituencies. For each constituency, the following details are collected −"
},
{
"code": null,
"e": 33166,
"s": 33147,
"text": "Constituency name."
},
{
"code": null,
"e": 33204,
"s": 33166,
"text": "Total population in the constituency."
},
{
"code": null,
"e": 33242,
"s": 33204,
"text": "Number of voters in the constituency."
},
{
"code": null,
"e": 33269,
"s": 33242,
"text": "Number of male voters, and"
},
{
"code": null,
"e": 33294,
"s": 33269,
"text": "Number of female voters."
},
{
"code": null,
"e": 33353,
"s": 33294,
"text": "The data is provided to you in a worksheet as given below."
},
{
"code": null,
"e": 33468,
"s": 33353,
"text": "It is not possible to analyze the data in the above format. Therefore, arrange the data in a table as shown below."
},
{
"code": null,
"e": 33531,
"s": 33468,
"text": "If you attempt to arrange the given data in the above format −"
},
{
"code": null,
"e": 33615,
"s": 33531,
"text": "It takes substantial amount of time to arrange the data from the 280 constituencies"
},
{
"code": null,
"e": 33699,
"s": 33615,
"text": "It takes substantial amount of time to arrange the data from the 280 constituencies"
},
{
"code": null,
"e": 33721,
"s": 33699,
"text": "It can be error prone"
},
{
"code": null,
"e": 33743,
"s": 33721,
"text": "It can be error prone"
},
{
"code": null,
"e": 33815,
"s": 33743,
"text": "It becomes a mundane task not allowing you to focus on technical things"
},
{
"code": null,
"e": 33887,
"s": 33815,
"text": "It becomes a mundane task not allowing you to focus on technical things"
},
{
"code": null,
"e": 34088,
"s": 33887,
"text": "The solution is to record a macro so that you can complete the task in not more than a few seconds. The macro needs to use relative references, as you will move down the rows while arranging the data."
},
{
"code": null,
"e": 34187,
"s": 34088,
"text": "In order to let the macro recorder know that it has to use relative references, do the following −"
},
{
"code": null,
"e": 34221,
"s": 34187,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 34255,
"s": 34221,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 34269,
"s": 34255,
"text": "Click Macros."
},
{
"code": null,
"e": 34283,
"s": 34269,
"text": "Click Macros."
},
{
"code": null,
"e": 34314,
"s": 34283,
"text": "Click Use Relative References."
},
{
"code": null,
"e": 34345,
"s": 34314,
"text": "Click Use Relative References."
},
{
"code": null,
"e": 34448,
"s": 34345,
"text": "The first step in arranging the above given data is to define the data format in a table with headers."
},
{
"code": null,
"e": 34490,
"s": 34448,
"text": "Create the row of headers as shown below."
},
{
"code": null,
"e": 34520,
"s": 34490,
"text": "Record the macro as follows −"
},
{
"code": null,
"e": 34540,
"s": 34520,
"text": "Click Record Macro."
},
{
"code": null,
"e": 34560,
"s": 34540,
"text": "Click Record Macro."
},
{
"code": null,
"e": 34615,
"s": 34560,
"text": "Give a meaningful name, say, DataArrange to the macro."
},
{
"code": null,
"e": 34670,
"s": 34615,
"text": "Give a meaningful name, say, DataArrange to the macro."
},
{
"code": null,
"e": 34780,
"s": 34670,
"text": "Type = row ()- 3 in the cell B4. This is because the S. No. is the current row number – the 3 rows above it."
},
{
"code": null,
"e": 34890,
"s": 34780,
"text": "Type = row ()- 3 in the cell B4. This is because the S. No. is the current row number – the 3 rows above it."
},
{
"code": null,
"e": 34975,
"s": 34890,
"text": "Cut the cells B5, B6, B7, B8 and B9 and paste it in the cells C4 to C8 respectively."
},
{
"code": null,
"e": 35060,
"s": 34975,
"text": "Cut the cells B5, B6, B7, B8 and B9 and paste it in the cells C4 to C8 respectively."
},
{
"code": null,
"e": 35119,
"s": 35060,
"text": "Now click in the cell B5. Your table looks as shown below."
},
{
"code": null,
"e": 35178,
"s": 35119,
"text": "Now click in the cell B5. Your table looks as shown below."
},
{
"code": null,
"e": 35291,
"s": 35178,
"text": "The first data set is arranged in the first row of the table. Delete the rows B6 – B11 and click in the cell B5."
},
{
"code": null,
"e": 35373,
"s": 35291,
"text": "You can see that the active cell is B5 and the next data set will be placed here."
},
{
"code": null,
"e": 35443,
"s": 35373,
"text": "Stop recording the macro. Your macro for arranging the data is ready."
},
{
"code": null,
"e": 35542,
"s": 35443,
"text": "You need to run the macro repeatedly to complete the data arrangement in the table as given below."
},
{
"code": null,
"e": 35680,
"s": 35542,
"text": "The active cell is B5. Run the macro. The second data set will be arranged in the second row of the table and the active cell will be B6."
},
{
"code": null,
"e": 35803,
"s": 35680,
"text": "Run the macro again. The third data set will be arranged in the third row of the table and the active cell will become B7."
},
{
"code": null,
"e": 36012,
"s": 35803,
"text": "Each time you run the macro, the active cell advances to the next row, facilitating the repetition of recorded steps at the appropriate positions. This is possible because of the relative references in macro."
},
{
"code": null,
"e": 36195,
"s": 36012,
"text": "Run the macro until all the 280 data sets are arranged into 280 rows in the table. This process takes a few seconds and as the steps are automated, the entire exercise is error free."
},
{
"code": null,
"e": 36460,
"s": 36195,
"text": "Excel stores the macros as Excel VBA (Visual Basic for Applications) code. After recording a macro, you can view the code that is generated, modify it, copy a part of it, etc. You can even write a macro code yourself if you are comfortable with programming in VBA."
},
{
"code": null,
"e": 36719,
"s": 36460,
"text": "You will learn how to create a macro, by writing a VBA code, in the chapter - Creating a Macro Using VBA Editor. You will learn how to modify a macro by editing VBA code in the chapter - Editing a Macro. You will learn the Excel VBA features in this chapter."
},
{
"code": null,
"e": 36790,
"s": 36719,
"text": "You can access macro code in VBA from the Developer tab on the Ribbon."
},
{
"code": null,
"e": 36874,
"s": 36790,
"text": "If you do not find the Developer tab on the Ribbon, you need to add it as follows −"
},
{
"code": null,
"e": 36901,
"s": 36874,
"text": "Right click on the Ribbon."
},
{
"code": null,
"e": 36928,
"s": 36901,
"text": "Right click on the Ribbon."
},
{
"code": null,
"e": 36980,
"s": 36928,
"text": "Select Customize the Ribbon from the dropdown list."
},
{
"code": null,
"e": 37032,
"s": 36980,
"text": "Select Customize the Ribbon from the dropdown list."
},
{
"code": null,
"e": 37070,
"s": 37032,
"text": "The Excel Options dialog box appears."
},
{
"code": null,
"e": 37128,
"s": 37070,
"text": "Select Main Tabs from Customize the Ribbon dropdown list."
},
{
"code": null,
"e": 37186,
"s": 37128,
"text": "Select Main Tabs from Customize the Ribbon dropdown list."
},
{
"code": null,
"e": 37275,
"s": 37186,
"text": "Check the box – Developer in the Main Tabs list and click OK. The developer tab appears."
},
{
"code": null,
"e": 37364,
"s": 37275,
"text": "Check the box – Developer in the Main Tabs list and click OK. The developer tab appears."
},
{
"code": null,
"e": 37439,
"s": 37364,
"text": "You need to know the commands that are for macros under the developer tab."
},
{
"code": null,
"e": 37535,
"s": 37439,
"text": "Click the DEVELOPER tab on the Ribbon. The following commands are available in the Code group −"
},
{
"code": null,
"e": 37548,
"s": 37535,
"text": "Visual Basic"
},
{
"code": null,
"e": 37555,
"s": 37548,
"text": "Macros"
},
{
"code": null,
"e": 37568,
"s": 37555,
"text": "Record Macro"
},
{
"code": null,
"e": 37592,
"s": 37568,
"text": "Use Relative References"
},
{
"code": null,
"e": 37607,
"s": 37592,
"text": "Macro Security"
},
{
"code": null,
"e": 37739,
"s": 37607,
"text": "The Visual Basic command is used to open the VBA Editor in Excel and the Macros command is used to view, run and delete the macros."
},
{
"code": null,
"e": 37824,
"s": 37739,
"text": "You have already learnt the commands other than VBA Editor in the previous chapters."
},
{
"code": null,
"e": 37886,
"s": 37824,
"text": "VBA Editor or VBE is the developer platform for VBA in Excel."
},
{
"code": null,
"e": 38007,
"s": 37886,
"text": "Open the workbook – MyFirstMacro.xlsm that you saved earlier in the chapter – Creating a Simple Macro, in this tutorial."
},
{
"code": null,
"e": 38053,
"s": 38007,
"text": "You can open the VBE in any of the two ways −"
},
{
"code": null,
"e": 38140,
"s": 38053,
"text": "Option 1 − Click Visual Basic in the Code group under the Developer tab on the Ribbon."
},
{
"code": null,
"e": 38246,
"s": 38140,
"text": "Option 2 − Click Edit in the Macro dialog box that appears when you click VIEW tab → Macros → View Macros"
},
{
"code": null,
"e": 38275,
"s": 38246,
"text": "VBE appears in a new window."
},
{
"code": null,
"e": 38393,
"s": 38275,
"text": "The name of your Excel macro enabled workbook name appears with the prefix – Microsoft Visual Basic for Applications."
},
{
"code": null,
"e": 38434,
"s": 38393,
"text": "You will find the following in the VBE −"
},
{
"code": null,
"e": 38453,
"s": 38434,
"text": "Projects Explorer."
},
{
"code": null,
"e": 38465,
"s": 38453,
"text": "Properties."
},
{
"code": null,
"e": 38490,
"s": 38465,
"text": "Module window with Code."
},
{
"code": null,
"e": 38701,
"s": 38490,
"text": "Project Explorer is where you find the VBA project names. Under a project, you will find Sheet names and Module names. When you click a module name, the corresponding code appears on the right side in a window."
},
{
"code": null,
"e": 38853,
"s": 38701,
"text": "The Properties are the parameters for VBA objects. When you have an object such as command button, its properties will appear in the Properties window."
},
{
"code": null,
"e": 39014,
"s": 38853,
"text": "The code of a macro will be stored in a module in VBA. When you select a macro and click Edit, the code of the macro appears in the corresponding module window."
},
{
"code": null,
"e": 39303,
"s": 39014,
"text": "When you record a macro, Excel stores it as a VBA code. You can view this code in the VBA editor. You can understand the code and modify it if you have substantial knowledge of Excel VBA. You can refer to the Excel VBA tutorial in this tutorials library to obtain a grasp on the language."
},
{
"code": null,
"e": 39544,
"s": 39303,
"text": "However, you can still view the macro code in Excel VBA editor and match it to the steps that you recorded in macro. You will learn how to view the code and understand it for the first macro that you created in this tutorial – MyFirstMacro."
},
{
"code": null,
"e": 39585,
"s": 39544,
"text": "To view a macro code, do the following −"
},
{
"code": null,
"e": 39634,
"s": 39585,
"text": "Open the workbook in which you stored the macro."
},
{
"code": null,
"e": 39664,
"s": 39634,
"text": "Click VIEW tab on the Ribbon."
},
{
"code": null,
"e": 39678,
"s": 39664,
"text": "Click Macros."
},
{
"code": null,
"e": 39721,
"s": 39678,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 39751,
"s": 39721,
"text": "The Macro dialog box appears."
},
{
"code": null,
"e": 39790,
"s": 39751,
"text": "Click MyFirstMacro in the macros list."
},
{
"code": null,
"e": 39813,
"s": 39790,
"text": "Click the Edit button."
},
{
"code": null,
"e": 39882,
"s": 39813,
"text": "The VBA editor opens and the code of the macro MyFirstMacro appears."
},
{
"code": null,
"e": 39957,
"s": 39882,
"text": "You can browse through the macro code and map them to your recorded steps."
},
{
"code": null,
"e": 39981,
"s": 39957,
"text": "Start reading the code."
},
{
"code": null,
"e": 40017,
"s": 39981,
"text": "Map the code to the recorded steps."
},
{
"code": null,
"e": 40105,
"s": 40017,
"text": "Scroll down the code to view more code. Alternatively, you can enlarge the code window."
},
{
"code": null,
"e": 40227,
"s": 40105,
"text": "Observe that the code is simple. If you learn Excel VBA, you can create the macros by writing the code in the VBA editor."
},
{
"code": null,
"e": 40336,
"s": 40227,
"text": "You will learn how to write a VBA code to create a macro in the chapter - Creating a Macro Using VBA Editor."
},
{
"code": null,
"e": 40684,
"s": 40336,
"text": "Suppose you have created a macro that you need to execute several times. For example, the macros that you have created for absolute references and relative references. Then, it would be easy for you if you can run the macro using a mouse click. You can accomplish this by assigning the macro to an object such as a shape or a graphic or a control."
},
{
"code": null,
"e": 40784,
"s": 40684,
"text": "In this chapter, you will learn how to include an object in your workbook and assign a macro to it."
},
{
"code": null,
"e": 40935,
"s": 40784,
"text": "Recall the macro that you created using relative references. The macro arranges the data given in one column into a table to facilitate data analysis."
},
{
"code": null,
"e": 41083,
"s": 40935,
"text": "You can insert a shape in your worksheet that is in a meaningful form with self-explanatory text, which when clicked runs the macro assigned to it."
},
{
"code": null,
"e": 41119,
"s": 41083,
"text": "Click the INSERT tab on the Ribbon."
},
{
"code": null,
"e": 41155,
"s": 41119,
"text": "Click the INSERT tab on the Ribbon."
},
{
"code": null,
"e": 41196,
"s": 41155,
"text": "Click Shapes in the Illustrations group."
},
{
"code": null,
"e": 41237,
"s": 41196,
"text": "Click Shapes in the Illustrations group."
},
{
"code": null,
"e": 41404,
"s": 41237,
"text": "Select any of the ready-made shapes that appear in the dropdown list. For example, the Flowchart shape – Preparation, as you are in the process of preparing the data."
},
{
"code": null,
"e": 41571,
"s": 41404,
"text": "Select any of the ready-made shapes that appear in the dropdown list. For example, the Flowchart shape – Preparation, as you are in the process of preparing the data."
},
{
"code": null,
"e": 41601,
"s": 41571,
"text": "Draw the shape and format it."
},
{
"code": null,
"e": 41671,
"s": 41601,
"text": "Right click on the shape and select Edit Text from the dropdown list."
},
{
"code": null,
"e": 41741,
"s": 41671,
"text": "Right click on the shape and select Edit Text from the dropdown list."
},
{
"code": null,
"e": 41781,
"s": 41741,
"text": "Type text inside the shape - Run Macro."
},
{
"code": null,
"e": 41821,
"s": 41781,
"text": "Type text inside the shape - Run Macro."
},
{
"code": null,
"e": 41838,
"s": 41821,
"text": "Format the text."
},
{
"code": null,
"e": 41855,
"s": 41838,
"text": "Format the text."
},
{
"code": null,
"e": 41881,
"s": 41855,
"text": "Right click on the shape."
},
{
"code": null,
"e": 41925,
"s": 41881,
"text": "Select Assign Macro from the dropdown list."
},
{
"code": null,
"e": 42016,
"s": 41925,
"text": "The Assign Macro dialog box appears. Click the macro name i.e. RelativeMacro and click OK."
},
{
"code": null,
"e": 42052,
"s": 42016,
"text": "The macro is assigned to the shape."
},
{
"code": null,
"e": 42110,
"s": 42052,
"text": "Click in the cell where you have to run the macro say B4."
},
{
"code": null,
"e": 42168,
"s": 42110,
"text": "Click in the cell where you have to run the macro say B4."
},
{
"code": null,
"e": 42250,
"s": 42168,
"text": "Move the cursor (pointer) onto the shape. The cursor (pointer) changes to finger."
},
{
"code": null,
"e": 42332,
"s": 42250,
"text": "Move the cursor (pointer) onto the shape. The cursor (pointer) changes to finger."
},
{
"code": null,
"e": 42529,
"s": 42332,
"text": "Now click the shape. The macro will run. Just repeat the mouse clicks to run the macro several times and you are done with the task of arranging the data into a table in a matter of a few seconds."
},
{
"code": null,
"e": 42757,
"s": 42529,
"text": "You can insert a graphic in the worksheet and assign a macro to it. The graphic can be chosen to visualize your macro. For example, you can have a graphic of table representing that the macro will arrange the data into a table."
},
{
"code": null,
"e": 42793,
"s": 42757,
"text": "Click the INSERT tab on the Ribbon."
},
{
"code": null,
"e": 42836,
"s": 42793,
"text": "Click Pictures in the Illustrations group."
},
{
"code": null,
"e": 42878,
"s": 42836,
"text": "Select a file that contains your graphic."
},
{
"code": null,
"e": 42962,
"s": 42878,
"text": "The rest of the steps are the same as those of shape given in the previous section."
},
{
"code": null,
"e": 43115,
"s": 42962,
"text": "Inserting a VBA control and assigning a macro to it makes your work look professional. You can insert VBA controls from the Developer tab on the Ribbon."
},
{
"code": null,
"e": 43154,
"s": 43115,
"text": "Click the DEVELOPER tab on the Ribbon."
},
{
"code": null,
"e": 43193,
"s": 43154,
"text": "Click the DEVELOPER tab on the Ribbon."
},
{
"code": null,
"e": 43229,
"s": 43193,
"text": "Click Insert in the Controls group."
},
{
"code": null,
"e": 43265,
"s": 43229,
"text": "Click Insert in the Controls group."
},
{
"code": null,
"e": 43368,
"s": 43265,
"text": "Select the Button icon under Form Controls from the dropdown list as shown in screenshot given below −"
},
{
"code": null,
"e": 43482,
"s": 43368,
"text": "Click the cell on the worksheet where you want to insert the Button control. The Assign Macro dialog box appears."
},
{
"code": null,
"e": 43596,
"s": 43482,
"text": "Click the cell on the worksheet where you want to insert the Button control. The Assign Macro dialog box appears."
},
{
"code": null,
"e": 43631,
"s": 43596,
"text": "Click the macro name and click OK."
},
{
"code": null,
"e": 43666,
"s": 43631,
"text": "Click the macro name and click OK."
},
{
"code": null,
"e": 43727,
"s": 43666,
"text": "The control button with the assigned macro will be inserted."
},
{
"code": null,
"e": 43754,
"s": 43727,
"text": "Right click on the button."
},
{
"code": null,
"e": 43771,
"s": 43754,
"text": "Click Edit Text."
},
{
"code": null,
"e": 43789,
"s": 43771,
"text": "Type – Run Macro."
},
{
"code": null,
"e": 43820,
"s": 43789,
"text": "Format Text and resize Button."
},
{
"code": null,
"e": 43902,
"s": 43820,
"text": "You can run the macro any number of times by just clicking the Button repeatedly."
},
{
"code": null,
"e": 44056,
"s": 43902,
"text": "Using Form Controls is an easy and effective way of interacting with the user. You will learn more about this in the chapter – Interacting with the User."
},
{
"code": null,
"e": 44281,
"s": 44056,
"text": "There are several ways of executing a macro in your workbook. The macro would have been saved in your macro enabled workbook or in your Personal macro workbook that you can access from any workbook as you had learnt earlier."
},
{
"code": null,
"e": 44325,
"s": 44281,
"text": "You can run a macro in the following ways −"
},
{
"code": null,
"e": 44359,
"s": 44325,
"text": "Running a Macro from the View Tab"
},
{
"code": null,
"e": 44412,
"s": 44359,
"text": "Running a Macro by pressing Ctrl plus a shortcut key"
},
{
"code": null,
"e": 44477,
"s": 44412,
"text": "Running a Macro by clicking a button on the Quick Access Toolbar"
},
{
"code": null,
"e": 44546,
"s": 44477,
"text": "Running a Macro by clicking a button in a Custom Group on the Ribbon"
},
{
"code": null,
"e": 44594,
"s": 44546,
"text": "Running a Macro by clicking on a Graphic Object"
},
{
"code": null,
"e": 44629,
"s": 44594,
"text": "Running a Macro from Developer Tab"
},
{
"code": null,
"e": 44661,
"s": 44629,
"text": "Running a Macro from VBA Editor"
},
{
"code": null,
"e": 44750,
"s": 44661,
"text": "You have already learnt running a macro from the View tab on the Ribbon. A quick recap −"
},
{
"code": null,
"e": 44784,
"s": 44750,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 44798,
"s": 44784,
"text": "Click Macros."
},
{
"code": null,
"e": 44841,
"s": 44798,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 44871,
"s": 44841,
"text": "The Macro dialog box appears."
},
{
"code": null,
"e": 44893,
"s": 44871,
"text": "Click the macro name."
},
{
"code": null,
"e": 44915,
"s": 44893,
"text": "Click the Run button."
},
{
"code": null,
"e": 45112,
"s": 44915,
"text": "You can assign a shortcut key (Ctrl + key) for a macro. You can do this while recording the macro in the Create Macro dialog box. Otherwise, you can add this later in the Macro Options dialog box."
},
{
"code": null,
"e": 45132,
"s": 45112,
"text": "Click the VIEW tab."
},
{
"code": null,
"e": 45146,
"s": 45132,
"text": "Click Macros."
},
{
"code": null,
"e": 45190,
"s": 45146,
"text": "Select Record Macro from the dropdown list."
},
{
"code": null,
"e": 45227,
"s": 45190,
"text": "The Create Macro dialog box appears."
},
{
"code": null,
"e": 45245,
"s": 45227,
"text": "Type a macro name"
},
{
"code": null,
"e": 45313,
"s": 45245,
"text": "Type a letter, say q, in the box next to Ctrl + under Shortcut key."
},
{
"code": null,
"e": 45333,
"s": 45313,
"text": "Click the VIEW tab."
},
{
"code": null,
"e": 45347,
"s": 45333,
"text": "Click Macros."
},
{
"code": null,
"e": 45390,
"s": 45347,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 45420,
"s": 45390,
"text": "The Macro dialog box appears."
},
{
"code": null,
"e": 45443,
"s": 45420,
"text": "Select the macro name."
},
{
"code": null,
"e": 45469,
"s": 45443,
"text": "Click the Options button."
},
{
"code": null,
"e": 45585,
"s": 45469,
"text": "The Macro Options dialog box appears. Type a letter, say q, in the box next to Ctrl + under Shortcut key. Click OK."
},
{
"code": null,
"e": 45688,
"s": 45585,
"text": "To run the macro with the shortcut key, press the Ctrl key and the key q together. The macro will run."
},
{
"code": null,
"e": 45972,
"s": 45688,
"text": "Note − You can use any lowercase or uppercase letters for the shortcut key of a macro. If you use any Ctrl + letter combination that is an Excel shortcut key, you will override it. Examples include Ctrl+C, Ctrl+V, Ctrl+X, etc. Hence, use your jurisdiction while choosing the letters."
},
{
"code": null,
"e": 46278,
"s": 45972,
"text": "You can add a macro button to the Quick Access Toolbar and run the macro by clicking it. This option would be useful when you store your macros in personal macro workbook. The added button will appear on the Quick Access Toolbar in whatever workbook you open, thus making it easy for you to run the macro."
},
{
"code": null,
"e": 46358,
"s": 46278,
"text": "Suppose you have a macro with the name MyMacro in your personal macro workbook."
},
{
"code": null,
"e": 46429,
"s": 46358,
"text": "To add the macro button to the Quick Access Toolbar do the following −"
},
{
"code": null,
"e": 46470,
"s": 46429,
"text": "Right click on the Quick Access Toolbar."
},
{
"code": null,
"e": 46511,
"s": 46470,
"text": "Right click on the Quick Access Toolbar."
},
{
"code": null,
"e": 46573,
"s": 46511,
"text": "Select Customize Quick Access Toolbar from the dropdown list."
},
{
"code": null,
"e": 46635,
"s": 46573,
"text": "Select Customize Quick Access Toolbar from the dropdown list."
},
{
"code": null,
"e": 46752,
"s": 46635,
"text": "The Excel Options dialog box appears. Select Macros from the dropdown list under the category- Choose commands from."
},
{
"code": null,
"e": 46791,
"s": 46752,
"text": "A list of macros appears under Macros."
},
{
"code": null,
"e": 46820,
"s": 46791,
"text": "Click PERSONAL.XLSB!MyMacro."
},
{
"code": null,
"e": 46842,
"s": 46820,
"text": "Click the Add button."
},
{
"code": null,
"e": 46911,
"s": 46842,
"text": "The macro name appears on the right side, with a macro button image."
},
{
"code": null,
"e": 46966,
"s": 46911,
"text": "To change the macro button image, proceed as follows −"
},
{
"code": null,
"e": 47005,
"s": 46966,
"text": "Click the macro name in the right box."
},
{
"code": null,
"e": 47030,
"s": 47005,
"text": "Click the Modify button."
},
{
"code": null,
"e": 47123,
"s": 47030,
"text": "The Modify Button dialog box appears. Select one symbol to set it as the icon of the button."
},
{
"code": null,
"e": 47302,
"s": 47123,
"text": "Modify the Display name that appears when you place the pointer on the Button image on the Quick Access Toolbar to a meaningful name, say, Run MyMacro for this example. Click OK."
},
{
"code": null,
"e": 47373,
"s": 47302,
"text": "The Macro name and the icon symbol change in the right pane. Click OK."
},
{
"code": null,
"e": 47503,
"s": 47373,
"text": "The macro button appears on the Quick Access Toolbar and the macro display name appears when you place the pointer on the button."
},
{
"code": null,
"e": 47578,
"s": 47503,
"text": "To run the macro, just click the macro button on the Quick Access Toolbar."
},
{
"code": null,
"e": 47676,
"s": 47578,
"text": "You can add a custom group and a custom button on the Ribbon and assign your macro to the button."
},
{
"code": null,
"e": 47703,
"s": 47676,
"text": "Right click on the Ribbon."
},
{
"code": null,
"e": 47755,
"s": 47703,
"text": "Select Customize the Ribbon from the dropdown list."
},
{
"code": null,
"e": 47793,
"s": 47755,
"text": "The Excel Options dialog box appears."
},
{
"code": null,
"e": 47838,
"s": 47793,
"text": "Select Main Tabs under Customize the Ribbon."
},
{
"code": null,
"e": 47853,
"s": 47838,
"text": "Click New Tab."
},
{
"code": null,
"e": 47901,
"s": 47853,
"text": "The New Tab (Custom) appears in Main Tabs list."
},
{
"code": null,
"e": 47925,
"s": 47901,
"text": "Click New Tab (Custom)."
},
{
"code": null,
"e": 47953,
"s": 47925,
"text": "Click the New Group button."
},
{
"code": null,
"e": 48008,
"s": 47953,
"text": "The New Group (Custom) appears under New Tab (Custom)."
},
{
"code": null,
"e": 48032,
"s": 48008,
"text": "Click New Tab (Custom)."
},
{
"code": null,
"e": 48057,
"s": 48032,
"text": "Click the Rename button."
},
{
"code": null,
"e": 48193,
"s": 48057,
"text": "The Rename dialog box appears. Type the name for your custom tab that appears in Main tabs on the Ribbon, say - My Macros and click OK."
},
{
"code": null,
"e": 48422,
"s": 48193,
"text": "Note − All the Main tabs on the Ribbon are in uppercase letters. You can use your discretion to use uppercase or lowercase letters. I have chosen lowercase with capitalization of words so that it stands out in the standard tabs."
},
{
"code": null,
"e": 48470,
"s": 48422,
"text": "The new tab name changes to My Macros (Custom)."
},
{
"code": null,
"e": 48496,
"s": 48470,
"text": "Click New Group (Custom)."
},
{
"code": null,
"e": 48521,
"s": 48496,
"text": "Click the Rename button."
},
{
"code": null,
"e": 48617,
"s": 48521,
"text": "The Rename dialog box appears. Type the group name in the Display name dialog box and click OK."
},
{
"code": null,
"e": 48673,
"s": 48617,
"text": "The new group name changes to Personal Macros (custom)."
},
{
"code": null,
"e": 48731,
"s": 48673,
"text": "Click Macros in the left pane under Choose commands from."
},
{
"code": null,
"e": 48796,
"s": 48731,
"text": "Select your macro name, say – MyFirstMacro from the macros list."
},
{
"code": null,
"e": 48818,
"s": 48796,
"text": "Click the Add button."
},
{
"code": null,
"e": 48884,
"s": 48818,
"text": "The macro will be added under the Personal Macros (Custom) group."
},
{
"code": null,
"e": 48923,
"s": 48884,
"text": "Click My Macros (Custom) in the list. "
},
{
"code": null,
"e": 48968,
"s": 48923,
"text": "Click the arrows to move the tab up or down."
},
{
"code": null,
"e": 49074,
"s": 48968,
"text": "The position of the tab in the main tabs list determines where it will be placed on the Ribbon. Click OK."
},
{
"code": null,
"e": 49125,
"s": 49074,
"text": "Your custom tab – My Macros appears on the Ribbon."
},
{
"code": null,
"e": 49323,
"s": 49125,
"text": "Click the tab - My Macros. Personal Macros group appears on the Ribbon. MyFirstMacro appears in the Personal Macros group. To run the macro, just click on MyFirstMacro in the Personal Macros group."
},
{
"code": null,
"e": 49477,
"s": 49323,
"text": "You can insert an object such as a shape, a graphic or a VBA control in your worksheet and assign a macro to it. To run the macro, just click the object."
},
{
"code": null,
"e": 49571,
"s": 49477,
"text": "For details on running a macro using objects, refer to chapter – Assigning Macros to Objects."
},
{
"code": null,
"e": 49615,
"s": 49571,
"text": "You can run a macro from the Developer tab."
},
{
"code": null,
"e": 49654,
"s": 49615,
"text": "Click the Developer tab on the Ribbon."
},
{
"code": null,
"e": 49668,
"s": 49654,
"text": "Click Macros."
},
{
"code": null,
"e": 49739,
"s": 49668,
"text": "The Macro dialog box appears. Click the macro name and then click Run."
},
{
"code": null,
"e": 49792,
"s": 49739,
"text": "You can run a macro from the VBA editor as follows −"
},
{
"code": null,
"e": 49825,
"s": 49792,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 49873,
"s": 49825,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 50012,
"s": 49873,
"text": "You can create a macro by writing the code in the VBA editor. In this chapter, you will learn where and how to write the code for a macro."
},
{
"code": null,
"e": 50089,
"s": 50012,
"text": "Before you start coding for a Macro, understand the VBA Objects and Modules."
},
{
"code": null,
"e": 50144,
"s": 50089,
"text": "Open the macro-enabled workbook with your first macro."
},
{
"code": null,
"e": 50183,
"s": 50144,
"text": "Click the DEVELOPER tab on the Ribbon."
},
{
"code": null,
"e": 50221,
"s": 50183,
"text": "Click Visual Basic in the Code group."
},
{
"code": null,
"e": 50250,
"s": 50221,
"text": "The VBA editor window opens."
},
{
"code": null,
"e": 50315,
"s": 50250,
"text": "You will observe the following in the Projects Explorer window −"
},
{
"code": null,
"e": 50389,
"s": 50315,
"text": "Your macro enabled workbook – MyFirstMacro.xlsm appears as a VBA Project."
},
{
"code": null,
"e": 50463,
"s": 50389,
"text": "Your macro enabled workbook – MyFirstMacro.xlsm appears as a VBA Project."
},
{
"code": null,
"e": 50552,
"s": 50463,
"text": "All the worksheets and the workbook appear as Microsoft Excel Objects under the project."
},
{
"code": null,
"e": 50641,
"s": 50552,
"text": "All the worksheets and the workbook appear as Microsoft Excel Objects under the project."
},
{
"code": null,
"e": 50705,
"s": 50641,
"text": "Module1 appears under Modules. Your macro code is located here."
},
{
"code": null,
"e": 50769,
"s": 50705,
"text": "Module1 appears under Modules. Your macro code is located here."
},
{
"code": null,
"e": 50784,
"s": 50769,
"text": "Click Module1."
},
{
"code": null,
"e": 50799,
"s": 50784,
"text": "Click Module1."
},
{
"code": null,
"e": 50833,
"s": 50799,
"text": "Click the View tab on the Ribbon."
},
{
"code": null,
"e": 50867,
"s": 50833,
"text": "Click the View tab on the Ribbon."
},
{
"code": null,
"e": 50903,
"s": 50867,
"text": "Select Code from the dropdown list."
},
{
"code": null,
"e": 50939,
"s": 50903,
"text": "Select Code from the dropdown list."
},
{
"code": null,
"e": 50971,
"s": 50939,
"text": "The code of your macro appears."
},
{
"code": null,
"e": 51053,
"s": 50971,
"text": "Next, create a second macro in the same workbook – this time by writing VBA code."
},
{
"code": null,
"e": 51084,
"s": 51053,
"text": "You can do this in two steps −"
},
{
"code": null,
"e": 51109,
"s": 51084,
"text": "Insert a command button."
},
{
"code": null,
"e": 51134,
"s": 51109,
"text": "Insert a command button."
},
{
"code": null,
"e": 51218,
"s": 51134,
"text": "Write the code stating the actions to take place when you click the command button."
},
{
"code": null,
"e": 51302,
"s": 51218,
"text": "Write the code stating the actions to take place when you click the command button."
},
{
"code": null,
"e": 51326,
"s": 51302,
"text": "Create a new worksheet."
},
{
"code": null,
"e": 51350,
"s": 51326,
"text": "Create a new worksheet."
},
{
"code": null,
"e": 51378,
"s": 51350,
"text": "Click in the new worksheet."
},
{
"code": null,
"e": 51406,
"s": 51378,
"text": "Click in the new worksheet."
},
{
"code": null,
"e": 51448,
"s": 51406,
"text": "Click the DEVELOPER button on the Ribbon."
},
{
"code": null,
"e": 51490,
"s": 51448,
"text": "Click the DEVELOPER button on the Ribbon."
},
{
"code": null,
"e": 51526,
"s": 51490,
"text": "Click Insert in the Controls group."
},
{
"code": null,
"e": 51562,
"s": 51526,
"text": "Click Insert in the Controls group."
},
{
"code": null,
"e": 51605,
"s": 51562,
"text": "Select the button icon from Form Controls."
},
{
"code": null,
"e": 51648,
"s": 51605,
"text": "Select the button icon from Form Controls."
},
{
"code": null,
"e": 51715,
"s": 51648,
"text": "Click in the worksheet where you want to place the command button."
},
{
"code": null,
"e": 51752,
"s": 51715,
"text": "The Assign Macro dialog box appears."
},
{
"code": null,
"e": 51785,
"s": 51752,
"text": "The Visual Basic editor appears."
},
{
"code": null,
"e": 51818,
"s": 51785,
"text": "You will observe the following −"
},
{
"code": null,
"e": 51878,
"s": 51818,
"text": "A new module – Module2 is inserted in the Project Explorer."
},
{
"code": null,
"e": 51925,
"s": 51878,
"text": "Code window with title Module2 (Code) appears."
},
{
"code": null,
"e": 51991,
"s": 51925,
"text": "A sub procedure Button1_Click () is inserted in the Module2 code."
},
{
"code": null,
"e": 52042,
"s": 51991,
"text": "Your coding is half done by the VBA editor itself."
},
{
"code": null,
"e": 52218,
"s": 52042,
"text": "For example, type MsgBox “Best Wishes to You!” in the sub procedure Button1_Click (). A message box with the given string will be displayed when the command button is clicked."
},
{
"code": null,
"e": 52350,
"s": 52218,
"text": "That’s it! Your macro code is ready to run. As you are aware, VBA code does not require compilation as it runs with an interpreter."
},
{
"code": null,
"e": 52407,
"s": 52350,
"text": "You can test your macro code from the VBA editor itself."
},
{
"code": null,
"e": 52440,
"s": 52407,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 52473,
"s": 52440,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 52590,
"s": 52473,
"text": "Select Run Sub/UserForm from the dropdown list. The message box with the string you typed appears in your worksheet."
},
{
"code": null,
"e": 52707,
"s": 52590,
"text": "Select Run Sub/UserForm from the dropdown list. The message box with the string you typed appears in your worksheet."
},
{
"code": null,
"e": 52819,
"s": 52707,
"text": "You can see that the button is selected. Click OK in the message box. You will be taken back to the VBA editor."
},
{
"code": null,
"e": 52896,
"s": 52819,
"text": "You can run the macro that you coded any number of times from the worksheet."
},
{
"code": null,
"e": 52930,
"s": 52896,
"text": "Click somewhere on the worksheet."
},
{
"code": null,
"e": 52990,
"s": 52930,
"text": "Click the Button. The Message box appears on the worksheet."
},
{
"code": null,
"e": 53078,
"s": 52990,
"text": "You have created a macro by writing VBA code. As you can observe, VBA coding is simple."
},
{
"code": null,
"e": 53221,
"s": 53078,
"text": "You have learnt how to write macro code in VBA editor in the previous chapter. You can edit the macro code, rename a macro and delete a macro."
},
{
"code": null,
"e": 53473,
"s": 53221,
"text": "If you master Excel VBA, writing code or modifying code for a macro is a trivial task. You can edit the macro code however you want. If you want to make only few simple changes in the macro code, you can even copy macro code from one place to another."
},
{
"code": null,
"e": 53739,
"s": 53473,
"text": "You have created two macros – MyFirstMacro and Button1_Click in the macro enabled workbook MyFirstMacro.xlsm. You have created the first macro by recording the steps and the second macro by writing code. You can copy code from the first macro into the second macro."
},
{
"code": null,
"e": 53776,
"s": 53739,
"text": "Open the workbook MyFirstMacro.xlsm."
},
{
"code": null,
"e": 53813,
"s": 53776,
"text": "Open the workbook MyFirstMacro.xlsm."
},
{
"code": null,
"e": 53852,
"s": 53813,
"text": "Click the Developer tab on the Ribbon."
},
{
"code": null,
"e": 53891,
"s": 53852,
"text": "Click the Developer tab on the Ribbon."
},
{
"code": null,
"e": 53942,
"s": 53891,
"text": "Click Visual Basic. The Visual Basic editor opens."
},
{
"code": null,
"e": 53993,
"s": 53942,
"text": "Click Visual Basic. The Visual Basic editor opens."
},
{
"code": null,
"e": 54088,
"s": 53993,
"text": "Open the code for Module1 (MyFirstMacro macro code) and Module2 (Button1_Click () macro code)."
},
{
"code": null,
"e": 54183,
"s": 54088,
"text": "Open the code for Module1 (MyFirstMacro macro code) and Module2 (Button1_Click () macro code)."
},
{
"code": null,
"e": 54219,
"s": 54183,
"text": "Click the Window tab on the Ribbon."
},
{
"code": null,
"e": 54255,
"s": 54219,
"text": "Click the Window tab on the Ribbon."
},
{
"code": null,
"e": 54304,
"s": 54255,
"text": "Select Tile Horizontally from the dropdown list."
},
{
"code": null,
"e": 54353,
"s": 54304,
"text": "Select Tile Horizontally from the dropdown list."
},
{
"code": null,
"e": 54415,
"s": 54353,
"text": "You can view the code of the two macros in the tiled windows."
},
{
"code": null,
"e": 54457,
"s": 54415,
"text": "Copy the MsgBox line in the Module2 code."
},
{
"code": null,
"e": 54499,
"s": 54457,
"text": "Copy the MsgBox line in the Module2 code."
},
{
"code": null,
"e": 54525,
"s": 54499,
"text": "Paste it above that line."
},
{
"code": null,
"e": 54551,
"s": 54525,
"text": "Paste it above that line."
},
{
"code": null,
"e": 54596,
"s": 54551,
"text": "Modify the string as −\nMsgBox “Hello World!”"
},
{
"code": null,
"e": 54619,
"s": 54596,
"text": "Modify the string as −"
},
{
"code": null,
"e": 54641,
"s": 54619,
"text": "MsgBox “Hello World!”"
},
{
"code": null,
"e": 54679,
"s": 54641,
"text": "Copy the following code from Module1."
},
{
"code": null,
"e": 54717,
"s": 54679,
"text": "Copy the following code from Module1."
},
{
"code": null,
"e": 54787,
"s": 54717,
"text": "Paste it in the Module2 code in between the two MsgBox lines of code."
},
{
"code": null,
"e": 54825,
"s": 54787,
"text": "Click the Save icon to save the code."
},
{
"code": null,
"e": 54863,
"s": 54825,
"text": "Click the Save icon to save the code."
},
{
"code": null,
"e": 54964,
"s": 54863,
"text": "Click the Button in the Excel sheet. A Message box appears with the message - Hello World! Click OK."
},
{
"code": null,
"e": 55065,
"s": 54964,
"text": "Click the Button in the Excel sheet. A Message box appears with the message - Hello World! Click OK."
},
{
"code": null,
"e": 55187,
"s": 55065,
"text": "The table data appears (according to the code that you copied) and message box appears with message - Best Wishes to You!"
},
{
"code": null,
"e": 55273,
"s": 55187,
"text": "You can modify the code in just a few steps. This is the easiest task for a beginner."
},
{
"code": null,
"e": 55447,
"s": 55273,
"text": "Suppose you want to run the edited macro from any worksheet other than the one that has the command button. You can do it irrespective of button click by renaming the macro."
},
{
"code": null,
"e": 55481,
"s": 55447,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 55495,
"s": 55481,
"text": "Click Macros."
},
{
"code": null,
"e": 55538,
"s": 55495,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 55568,
"s": 55538,
"text": "The Macro dialog box appears."
},
{
"code": null,
"e": 55606,
"s": 55568,
"text": "Click the macro name – Button1_Click."
},
{
"code": null,
"e": 55629,
"s": 55606,
"text": "Click the Edit button."
},
{
"code": null,
"e": 55671,
"s": 55629,
"text": "The macro code appears in the VBA editor."
},
{
"code": null,
"e": 55791,
"s": 55671,
"text": "Change the name that appears in the Sub line from Button1_Click to RenamedMacro. Leave Sub and parenthesis as they are."
},
{
"code": null,
"e": 55857,
"s": 55791,
"text": "Open the Macro dialog box. The macro name appears as you renamed."
},
{
"code": null,
"e": 55877,
"s": 55857,
"text": "Click RenamedMacro."
},
{
"code": null,
"e": 55952,
"s": 55877,
"text": "Click the Run button. The macro runs. Now a button click is not necessary."
},
{
"code": null,
"e": 56008,
"s": 55952,
"text": "You can delete a macro that you have recorded or coded."
},
{
"code": null,
"e": 56036,
"s": 56008,
"text": "Open the Macros dialog box."
},
{
"code": null,
"e": 56058,
"s": 56036,
"text": "Click the macro name."
},
{
"code": null,
"e": 56083,
"s": 56058,
"text": "Click the Delete button."
},
{
"code": null,
"e": 56124,
"s": 56083,
"text": "The Delete confirmation message appears."
},
{
"code": null,
"e": 56192,
"s": 56124,
"text": "Click Yes if you are sure to delete the macro. Otherwise, click No."
},
{
"code": null,
"e": 56591,
"s": 56192,
"text": "At times, you might have to collect information repeatedly from others. Excel VBA provides you with an easy way of handling this task- UserForm. As any other form that you fill up, UserForm makes it simple to understand, what information is to be provided. UserForm is user friendly in the way that the controls provided are self-explanatory, accompanied by additional instructions where necessary."
},
{
"code": null,
"e": 56712,
"s": 56591,
"text": "Major advantage of UserForm is that you can save on time that you spend on what and how the information is to be filled."
},
{
"code": null,
"e": 56755,
"s": 56712,
"text": "To create a UserForm, proceed as follows −"
},
{
"code": null,
"e": 56794,
"s": 56755,
"text": "Click the DEVELOPER tab on the Ribbon."
},
{
"code": null,
"e": 56860,
"s": 56794,
"text": "Click Visual Basic. A Visual Basic window for the workbook opens."
},
{
"code": null,
"e": 56874,
"s": 56860,
"text": "Click Insert,"
},
{
"code": null,
"e": 56914,
"s": 56874,
"text": "Select UserForm from the dropdown list."
},
{
"code": null,
"e": 56968,
"s": 56914,
"text": "The UserForm appears on the right side of the window."
},
{
"code": null,
"e": 57015,
"s": 56968,
"text": "Maximize the UserForm.xlsx – UserForm1 window."
},
{
"code": null,
"e": 57309,
"s": 57015,
"text": "You are in the design mode now. You can insert controls on the UserForm and write code for the respective actions. The controls are available in the ToolBox. Properties of UserForm are in the Properties window. UserForm1 (caption of the UserForm) is given under Forms in the Projects Explorer."
},
{
"code": null,
"e": 57396,
"s": 57309,
"text": "Change the caption of the UserForm to Project Report – Daily in the properties window."
},
{
"code": null,
"e": 57446,
"s": 57396,
"text": "Change the name of the UserForm to ProjectReport."
},
{
"code": null,
"e": 57522,
"s": 57446,
"text": "The changes are reflected in the UserForm, properties and project explorer."
},
{
"code": null,
"e": 57856,
"s": 57522,
"text": "A UserForm will have different components. As and when you click on any of the components, either you will be provided with instructions on what and how the information is to be provided or you will be provided with options (choices) to select from. All these are provided by means of ActiveX controls in the ToolBox of the UserForm."
},
{
"code": null,
"e": 58006,
"s": 57856,
"text": "Excel provides two types of controls – Form controls and ActiveX controls. You need to understand the difference between these two types of controls."
},
{
"code": null,
"e": 58198,
"s": 58006,
"text": "Form controls are the Excel original controls that are compatible with earlier versions of Excel, starting with Excel version 5.0. Form controls are also designed for use on XLM macro sheets."
},
{
"code": null,
"e": 58522,
"s": 58198,
"text": "You can run macros by using Form controls. You can assign an existing macro to a control, or write or record a new macro. When the control is clicked, the macro. You have already learnt how to insert a command button from Form controls in the worksheet to run a macro. However, these controls cannot be added to a UserForm."
},
{
"code": null,
"e": 58703,
"s": 58522,
"text": "ActiveX controls can be used on VBA UserForms. ActiveX controls have extensive properties that you can use to customize their appearance, behavior, fonts and other characteristics."
},
{
"code": null,
"e": 58769,
"s": 58703,
"text": "You have the following ActiveX controls in the UserForm ToolBox −"
},
{
"code": null,
"e": 58777,
"s": 58769,
"text": "Pointer"
},
{
"code": null,
"e": 58783,
"s": 58777,
"text": "Label"
},
{
"code": null,
"e": 58791,
"s": 58783,
"text": "TextBox"
},
{
"code": null,
"e": 58800,
"s": 58791,
"text": "ComboBox"
},
{
"code": null,
"e": 58808,
"s": 58800,
"text": "ListBox"
},
{
"code": null,
"e": 58817,
"s": 58808,
"text": "CheckBox"
},
{
"code": null,
"e": 58830,
"s": 58817,
"text": "OptionButton"
},
{
"code": null,
"e": 58836,
"s": 58830,
"text": "Frame"
},
{
"code": null,
"e": 58849,
"s": 58836,
"text": "ToggleButton"
},
{
"code": null,
"e": 58863,
"s": 58849,
"text": "CommandButton"
},
{
"code": null,
"e": 58872,
"s": 58863,
"text": "TabStrip"
},
{
"code": null,
"e": 58882,
"s": 58872,
"text": "MultiPage"
},
{
"code": null,
"e": 58892,
"s": 58882,
"text": "ScrollBar"
},
{
"code": null,
"e": 58903,
"s": 58892,
"text": "SpinButton"
},
{
"code": null,
"e": 58909,
"s": 58903,
"text": "Image"
},
{
"code": null,
"e": 59062,
"s": 58909,
"text": "In addition to these controls, Visual Basic provides you with MsgBox function that can be used to display messages and/or prompt the user for an action."
},
{
"code": null,
"e": 59239,
"s": 59062,
"text": "In the next few sections, you will understand these controls and MsgBox. Then, you will be in a position to choose which of these controls are required to design your UserForm."
},
{
"code": null,
"e": 59371,
"s": 59239,
"text": "You can use Labels for identification purpose by displaying descriptive text, such as titles, captions and / or brief instructions."
},
{
"code": null,
"e": 59379,
"s": 59371,
"text": "Example"
},
{
"code": null,
"e": 59543,
"s": 59379,
"text": "You can use a TextBox that is a rectangular box, to type, view or edit text. You can also use a TextBox as a static text field that presents read-only information."
},
{
"code": null,
"e": 59551,
"s": 59543,
"text": "Example"
},
{
"code": null,
"e": 59738,
"s": 59551,
"text": "You can use a List Box to display a list of one or more items of text from which a user can choose. Use a list box for displaying large numbers of choices that vary in number or content."
},
{
"code": null,
"e": 59772,
"s": 59738,
"text": "Insert a ListBox on the UserForm."
},
{
"code": null,
"e": 59794,
"s": 59772,
"text": "Click on the ListBox."
},
{
"code": null,
"e": 59862,
"s": 59794,
"text": "Type ProjectCodes for Name in the Properties window of the ListBox."
},
{
"code": null,
"e": 59900,
"s": 59862,
"text": "There are three types of List Boxes −"
},
{
"code": null,
"e": 60119,
"s": 59900,
"text": "Single-selection List box − A single-selection List Box enables only one choice. In this case, a list box resembles a group of option buttons, except that a list box can handle a large number of items more efficiently."
},
{
"code": null,
"e": 60338,
"s": 60119,
"text": "Single-selection List box − A single-selection List Box enables only one choice. In this case, a list box resembles a group of option buttons, except that a list box can handle a large number of items more efficiently."
},
{
"code": null,
"e": 60458,
"s": 60338,
"text": "Multiple selection List Box − A multiple selection List Box enables either one choice or contiguous (adjacent) choices."
},
{
"code": null,
"e": 60578,
"s": 60458,
"text": "Multiple selection List Box − A multiple selection List Box enables either one choice or contiguous (adjacent) choices."
},
{
"code": null,
"e": 60721,
"s": 60578,
"text": "Extended-selection List Box − An extended-selection List Box enables one choice, contiguous choices and noncontiguous (or disjointed) choices."
},
{
"code": null,
"e": 60864,
"s": 60721,
"text": "Extended-selection List Box − An extended-selection List Box enables one choice, contiguous choices and noncontiguous (or disjointed) choices."
},
{
"code": null,
"e": 60941,
"s": 60864,
"text": "You can select one of these types of List Boxes, from the Properties window."
},
{
"code": null,
"e": 60970,
"s": 60941,
"text": "Right click on the UserForm."
},
{
"code": null,
"e": 61046,
"s": 60970,
"text": "Select View Code from the dropdown list. The code window of UserForm opens."
},
{
"code": null,
"e": 61104,
"s": 61046,
"text": "Click Initialize in the top right box of the code window."
},
{
"code": null,
"e": 61164,
"s": 61104,
"text": "Type the following under Private Sub UserForm_Initialize()."
},
{
"code": null,
"e": 61262,
"s": 61164,
"text": "ProjectCodes.List = Array (\"Proj2016-1\", \"Proj2016-2\", \"Proj2016-3\", \"Proj20164\", \"Proj2016-5\") \n"
},
{
"code": null,
"e": 61295,
"s": 61262,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 61343,
"s": 61295,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 61535,
"s": 61343,
"text": "Next, you can write code for actions on selecting an item in the list. Otherwise, you can just display the text that is selected, which is the case for filling the Project Code in the Report."
},
{
"code": null,
"e": 61803,
"s": 61535,
"text": "You can use ComboBox that combines a text box with a list box to create a dropdown list box. A combo box is more compact than a list box but requires the user to click the down arrow to display the list of items. Use a combo box to choose only one item from the list."
},
{
"code": null,
"e": 61838,
"s": 61803,
"text": "Insert a ComboBox on the UserForm."
},
{
"code": null,
"e": 61858,
"s": 61838,
"text": "Click the ComboBox."
},
{
"code": null,
"e": 61928,
"s": 61858,
"text": "Type ProjectCodes2 for Name in the Properties window of the ComboBox."
},
{
"code": null,
"e": 61957,
"s": 61928,
"text": "Right click on the UserForm."
},
{
"code": null,
"e": 61998,
"s": 61957,
"text": "Select View Code from the dropdown list."
},
{
"code": null,
"e": 62033,
"s": 61998,
"text": "The code window of UserForm opens."
},
{
"code": null,
"e": 62068,
"s": 62033,
"text": "Type the following as shown below."
},
{
"code": null,
"e": 62167,
"s": 62068,
"text": "ProjectCodes2.List = Array (\"Proj2016-1\", \"Proj2016-2\", \"Proj2016-3\", \"Proj20164\", \"Proj2016-5\") \n"
},
{
"code": null,
"e": 62200,
"s": 62167,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 62248,
"s": 62200,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 62299,
"s": 62248,
"text": "Click the down arrow to display the list of items."
},
{
"code": null,
"e": 62403,
"s": 62299,
"text": "Click on the required item, say, Project2016-5. The selected option will be displayed in the combo box."
},
{
"code": null,
"e": 62588,
"s": 62403,
"text": "You can use check boxes to select one or more options that are displayed by clicking in the boxes. The options will have labels and you can clearly visualize what options are selected."
},
{
"code": null,
"e": 62622,
"s": 62588,
"text": "A check box can have two states −"
},
{
"code": null,
"e": 62678,
"s": 62622,
"text": "Selected (turned on), denoted by a tick mark in the box"
},
{
"code": null,
"e": 62723,
"s": 62678,
"text": "Cleared (turned off), denoted by a clear box"
},
{
"code": null,
"e": 62862,
"s": 62723,
"text": "You can use check boxes for selection of options in a combo box to save space. In such a case, the check box can have a third state also −"
},
{
"code": null,
"e": 63038,
"s": 62862,
"text": "Mixed, meaning a combination of on and off states, denoted by a black dot in the box. This will be displayed to indicate multiple selections in the combo box with check boxes."
},
{
"code": null,
"e": 63214,
"s": 63038,
"text": "Mixed, meaning a combination of on and off states, denoted by a black dot in the box. This will be displayed to indicate multiple selections in the combo box with check boxes."
},
{
"code": null,
"e": 63265,
"s": 63214,
"text": "Insert check boxes in the UserForm as shown below."
},
{
"code": null,
"e": 63316,
"s": 63265,
"text": "Insert check boxes in the UserForm as shown below."
},
{
"code": null,
"e": 63349,
"s": 63316,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 63397,
"s": 63349,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 63443,
"s": 63397,
"text": "Click in the boxes for your selected options."
},
{
"code": null,
"e": 63645,
"s": 63443,
"text": "You can use an option button, also known as the radio button to make a single choice within a limited set of mutually exclusive choices. An option button is usually contained in a group box or a frame."
},
{
"code": null,
"e": 63756,
"s": 63645,
"text": "An option button is represented by a small circle. An option button can have one of the following two states −"
},
{
"code": null,
"e": 63809,
"s": 63756,
"text": "Selected (turned on), denoted by a dot in the circle"
},
{
"code": null,
"e": 63850,
"s": 63809,
"text": "Cleared (turned off), denoted by a blank"
},
{
"code": null,
"e": 64058,
"s": 63850,
"text": "You can use a frame control, also referred to as a group box to group related controls into one visual unit. Typically, option buttons, check boxes or closely related contents are grouped in a frame control."
},
{
"code": null,
"e": 64137,
"s": 64058,
"text": "A frame control is represented by a rectangular object with an optional label."
},
{
"code": null,
"e": 64175,
"s": 64137,
"text": "Insert a frame with caption “Choice”."
},
{
"code": null,
"e": 64213,
"s": 64175,
"text": "Insert a frame with caption “Choice”."
},
{
"code": null,
"e": 64337,
"s": 64213,
"text": "Insert two option buttons with captions “Yes” and “No” in the frame control. The options Yes and No are mutually exclusive."
},
{
"code": null,
"e": 64461,
"s": 64337,
"text": "Insert two option buttons with captions “Yes” and “No” in the frame control. The options Yes and No are mutually exclusive."
},
{
"code": null,
"e": 64494,
"s": 64461,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 64542,
"s": 64494,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 64573,
"s": 64542,
"text": "Click on your selected option."
},
{
"code": null,
"e": 64753,
"s": 64573,
"text": "You can use a toggle button to indicate a state, such as Yes or No, or a mode, such as on or off. The button alternates between an enabled and a disabled state when it is clicked."
},
{
"code": null,
"e": 64805,
"s": 64753,
"text": "Insert a toggle button on UserForm as shown below −"
},
{
"code": null,
"e": 64838,
"s": 64805,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 64871,
"s": 64838,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 64974,
"s": 64871,
"text": "Select Run Sub/UserForm from the dropdown list. The toggle button will be in enabled state by default."
},
{
"code": null,
"e": 65077,
"s": 64974,
"text": "Select Run Sub/UserForm from the dropdown list. The toggle button will be in enabled state by default."
},
{
"code": null,
"e": 65138,
"s": 65077,
"text": "Click the toggle button. The toggle button will be disabled."
},
{
"code": null,
"e": 65196,
"s": 65138,
"text": "If you click the toggle button again, it will be enabled."
},
{
"code": null,
"e": 65378,
"s": 65196,
"text": "You can use a command button to run a macro that performs some actions when the user clicks on it. You have already learnt how to use a command button on a worksheet to run a macro."
},
{
"code": null,
"e": 65488,
"s": 65378,
"text": "Command button is also referred to as a push button. Insert a command button on the UserForm as shown below −"
},
{
"code": null,
"e": 65523,
"s": 65488,
"text": "Right click on the command button."
},
{
"code": null,
"e": 65583,
"s": 65523,
"text": "Type the following code in the sub Commandbutton1_click ()."
},
{
"code": null,
"e": 65608,
"s": 65583,
"text": "ProjectCodes2.DropDown \n"
},
{
"code": null,
"e": 65641,
"s": 65608,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 65689,
"s": 65641,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 65808,
"s": 65689,
"text": "Click the command button. The dropdown list of combo box opens, as it is the action that you have written in the code."
},
{
"code": null,
"e": 65878,
"s": 65808,
"text": "You can insert a tab strip that resembles Excel tabs on the UserForm."
},
{
"code": null,
"e": 66003,
"s": 65878,
"text": "You can use a scroll bar to scroll through a range of values by clicking on the scroll arrows or by dragging the scroll box."
},
{
"code": null,
"e": 66119,
"s": 66003,
"text": "Insert a scroll bar on the UserForm by drawing it at the required position and adjust the length of the scroll bar."
},
{
"code": null,
"e": 66150,
"s": 66119,
"text": "Right click on the scroll bar."
},
{
"code": null,
"e": 66214,
"s": 66150,
"text": "Select View Code from the dropdown list. The Code window opens."
},
{
"code": null,
"e": 66268,
"s": 66214,
"text": "Add the following line under sub ScrollBar1_Scroll()."
},
{
"code": null,
"e": 66305,
"s": 66268,
"text": "TextBox2.Text = \"Scrolling Values\" \n"
},
{
"code": null,
"e": 66338,
"s": 66305,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 66386,
"s": 66338,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 66526,
"s": 66386,
"text": "Drag the scroll box. The Text – Scrolling Values will be displayed in the text box as you specified it as the action for scroll bar scroll."
},
{
"code": null,
"e": 66685,
"s": 66526,
"text": "You can use the MsgBox () function to display a message when you click on something. It can be a guideline or some information or a warning or an error alert."
},
{
"code": null,
"e": 66796,
"s": 66685,
"text": "For example, you can display a message that values are being scrolled when you start scrolling the scroll box."
},
{
"code": null,
"e": 66932,
"s": 66796,
"text": "You can use message-box icon displays that portray the specific message. You have the multiple message box icons to suit your purpose −"
},
{
"code": null,
"e": 66981,
"s": 66932,
"text": "Type the following code under ScrollBar1_scroll."
},
{
"code": null,
"e": 67287,
"s": 66981,
"text": "MsgBox \"Select Ok or Cancel\", vbOKCancel, \"OK - Cancel Message\" \nMsgBox \"It's an Error!\", vbCritical, \"Run time result\" \nMsgBox \"Why this value\", vbQuestion, \"Run time result\" \nMsgBox \"Value Been for a Long Time\", vbInformation, \"Run time result\" \nMsgBox \"Oh Is it so\", vbExclamation, \"Run time result\" \n"
},
{
"code": null,
"e": 67320,
"s": 67287,
"text": "Click the Run tab on the Ribbon."
},
{
"code": null,
"e": 67368,
"s": 67320,
"text": "Select Run Sub/UserForm from the dropdown list."
},
{
"code": null,
"e": 67389,
"s": 67368,
"text": "Drag the scroll box."
},
{
"code": null,
"e": 67444,
"s": 67389,
"text": "You will get the following message boxes successively."
},
{
"code": null,
"e": 67720,
"s": 67444,
"text": "Now, you have an understanding of the different controls that you can use on a UserForm. Select the controls, group them if required and arrange them on the UserForm as per some meaningful sequence. Write the required actions as code corresponding to the respective controls."
},
{
"code": null,
"e": 67800,
"s": 67720,
"text": "Refer to the VBA tutorial in this tutorials library for an example of UserForm."
},
{
"code": null,
"e": 68071,
"s": 67800,
"text": "You have learnt that the macro is stored as VBA code in Excel. You have also learnt that you can directly write code to create a macro in VBA editor. However, as with the case with any code, even the macro code can have defects and the macro may not run as you expected."
},
{
"code": null,
"e": 68220,
"s": 68071,
"text": "This requires examining the code to find the defects and correct them. The term that is used for this activity in software development is debugging."
},
{
"code": null,
"e": 68373,
"s": 68220,
"text": "VBA editor allows you to pause the execution of the code and perform any required debug task. Following are some of the debugging tasks that you can do."
},
{
"code": null,
"e": 68395,
"s": 68373,
"text": "Stepping Through Code"
},
{
"code": null,
"e": 68413,
"s": 68395,
"text": "Using Breakpoints"
},
{
"code": null,
"e": 68450,
"s": 68413,
"text": "Backing Up or Moving Forward in Code"
},
{
"code": null,
"e": 68489,
"s": 68450,
"text": "Not Stepping Through Each Line of Code"
},
{
"code": null,
"e": 68535,
"s": 68489,
"text": "Querying Anything While Stepping Through Code"
},
{
"code": null,
"e": 68557,
"s": 68535,
"text": "Halting the Execution"
},
{
"code": null,
"e": 68645,
"s": 68557,
"text": "These are just some of the tasks that you might perform in VBA's debugging environment."
},
{
"code": null,
"e": 68954,
"s": 68645,
"text": "The first thing that you have to do for debugging is to step through the code while executing it. If you have an idea of which part of the code is probably producing the defect, you can jump to that line of the code. Otherwise, you can execute the code line by line, backing up or moving forward in the code."
},
{
"code": null,
"e": 69058,
"s": 68954,
"text": "You can step into the code either from Macro dialog box in your workbook or from the VBA editor itself."
},
{
"code": null,
"e": 69099,
"s": 69058,
"text": "Stepping into the code from the workbook"
},
{
"code": null,
"e": 69159,
"s": 69099,
"text": "To step into the code from the workbook, do the following −"
},
{
"code": null,
"e": 69193,
"s": 69159,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 69207,
"s": 69193,
"text": "Click Macros."
},
{
"code": null,
"e": 69250,
"s": 69207,
"text": "Select View Macros from the dropdown list."
},
{
"code": null,
"e": 69280,
"s": 69250,
"text": "The Macro dialog box appears."
},
{
"code": null,
"e": 69302,
"s": 69280,
"text": "Click the macro name."
},
{
"code": null,
"e": 69330,
"s": 69302,
"text": "Click the Step into button."
},
{
"code": null,
"e": 69464,
"s": 69330,
"text": "VBA editor opens and the macro code appears in the code window. The first line in the macro code will be highlighted in yellow color."
},
{
"code": null,
"e": 69507,
"s": 69464,
"text": "Stepping into the code from the VBA editor"
},
{
"code": null,
"e": 69569,
"s": 69507,
"text": "To step into the code from the VBA editor, do the following −"
},
{
"code": null,
"e": 69608,
"s": 69569,
"text": "Click the DEVELOPER tab on the Ribbon."
},
{
"code": null,
"e": 69650,
"s": 69608,
"text": "Click Visual Basic. The VBA editor opens."
},
{
"code": null,
"e": 69697,
"s": 69650,
"text": "Click the module that contains the macro code."
},
{
"code": null,
"e": 69740,
"s": 69697,
"text": "The macro code appears in the code window."
},
{
"code": null,
"e": 69775,
"s": 69740,
"text": "Click the Debug tab on the Ribbon."
},
{
"code": null,
"e": 69810,
"s": 69775,
"text": "Click the Debug tab on the Ribbon."
},
{
"code": null,
"e": 69851,
"s": 69810,
"text": "Select Step into from the dropdown list."
},
{
"code": null,
"e": 69892,
"s": 69851,
"text": "Select Step into from the dropdown list."
},
{
"code": null,
"e": 70043,
"s": 69892,
"text": "The first line in the macro code will be highlighted. The code is in the debugging mode and the options in the Debug dropdown list will become active."
},
{
"code": null,
"e": 70124,
"s": 70043,
"text": "You can move forward or backward in the code by selecting Step Over or Step Out."
},
{
"code": null,
"e": 70272,
"s": 70124,
"text": "You can avoid stepping through each line code, if you identify a potential part of the code that needs to be discussed, by selecting Run to Cursor."
},
{
"code": null,
"e": 70477,
"s": 70272,
"text": "Alternatively, you can set breakpoints at specific lines of code and execute the code, observing the results at each breakpoint. You can toggle a breakpoint and clear all breakpoints if and when required."
},
{
"code": null,
"e": 70861,
"s": 70477,
"text": "You can add a watch while debugging, to evaluate an expression and stop the execution when a variable attains a specific value. This means that you configure a watch expression, which will be monitored until it is true and then the macro will halt and leave you in break mode. VBA provides you with several watch types to select from, in order to accomplish what you are looking for."
},
{
"code": null,
"e": 70998,
"s": 70861,
"text": "During debugging, at any point of time, if you have found a clue on what is going wrong, you can halt the execution to decipher further."
},
{
"code": null,
"e": 71248,
"s": 70998,
"text": "If you are an experienced developer, the debugging terminology is familiar to you and VBA editor debugging options make your life simple. Even otherwise, it will not take much time to master this skill if you have learnt VBA and understand the code."
},
{
"code": null,
"e": 71374,
"s": 71248,
"text": "You can record a macro and save it with the name Auto_Open to run it whenever you open the workbook that contains this macro."
},
{
"code": null,
"e": 71561,
"s": 71374,
"text": "You can also write VBA code for the same purpose with the Open event of the workbook. The Open event runs the code in the sub procedure Workbook_Open () every time you open the workbook."
},
{
"code": null,
"e": 71607,
"s": 71561,
"text": "You can record an Auto_Run macro as follows −"
},
{
"code": null,
"e": 71641,
"s": 71607,
"text": "Click the VIEW tab on the Ribbon."
},
{
"code": null,
"e": 71655,
"s": 71641,
"text": "Click Macros."
},
{
"code": null,
"e": 71712,
"s": 71655,
"text": "Click Record Macro. The Record Macro dialog box appears."
},
{
"code": null,
"e": 71746,
"s": 71712,
"text": "Type Auto_Run for the macro name."
},
{
"code": null,
"e": 71779,
"s": 71746,
"text": "Type a description and click OK."
},
{
"code": null,
"e": 71807,
"s": 71779,
"text": "Start recording the macro. "
},
{
"code": null,
"e": 71823,
"s": 71807,
"text": "Stop Recording."
},
{
"code": null,
"e": 71868,
"s": 71823,
"text": "Save the workbook as macro enabled workbook."
},
{
"code": null,
"e": 71888,
"s": 71868,
"text": "Close the workbook."
},
{
"code": null,
"e": 71950,
"s": 71888,
"text": "Open the workbook. The macro Auto_Run will run automatically."
},
{
"code": null,
"e": 72054,
"s": 71950,
"text": "If you want Excel to start without running an Auto_Open macro, hold the SHIFT key when you start Excel."
},
{
"code": null,
"e": 72109,
"s": 72054,
"text": "The following are the limitations of Auto_Open macro −"
},
{
"code": null,
"e": 72281,
"s": 72109,
"text": "If the workbook in which you saved the Auto_Open macro contains code for workbook Open event, the code for the Open event will override the actions in the Auto_Open macro."
},
{
"code": null,
"e": 72453,
"s": 72281,
"text": "If the workbook in which you saved the Auto_Open macro contains code for workbook Open event, the code for the Open event will override the actions in the Auto_Open macro."
},
{
"code": null,
"e": 72554,
"s": 72453,
"text": "An Auto_Open macro is ignored when the workbook is opened by running code that uses the Open method."
},
{
"code": null,
"e": 72655,
"s": 72554,
"text": "An Auto_Open macro is ignored when the workbook is opened by running code that uses the Open method."
},
{
"code": null,
"e": 72983,
"s": 72655,
"text": "An Auto_Open macro runs before any other workbooks open. Hence, if you record actions that you want Excel to perform on the default Book1 workbook or on a workbook that is loaded from the XLStart folder, the Auto_Open macro will fail when you restart Excel, because the macro runs before the default and startup workbooks open."
},
{
"code": null,
"e": 73311,
"s": 72983,
"text": "An Auto_Open macro runs before any other workbooks open. Hence, if you record actions that you want Excel to perform on the default Book1 workbook or on a workbook that is loaded from the XLStart folder, the Auto_Open macro will fail when you restart Excel, because the macro runs before the default and startup workbooks open."
},
{
"code": null,
"e": 73470,
"s": 73311,
"text": "If you encounter any of these limitations, instead of recording an Auto_Open macro, you must write a code for the Open event as described in the next section."
},
{
"code": null,
"e": 73665,
"s": 73470,
"text": "You can write code that will get executed when you open a workbook. VBA provides you with an event called open that incorporates a VBA procedure for the actions to be done on opening a workbook."
},
{
"code": null,
"e": 73917,
"s": 73665,
"text": "Open the workbook in which you stored the macro that you have written for the absolute references – Report_ProjectXYZ. When this macro is run, a new worksheet will be added in the workbook and the project report structure appears on the new worksheet."
},
{
"code": null,
"e": 74144,
"s": 73917,
"text": "You can write a macro code that will perform these actions when you open the workbook. That means when you open the Project Report workbook, a new worksheet with the report structure will be ready for you to enter the details."
},
{
"code": null,
"e": 74192,
"s": 74144,
"text": "Follow the below given procedure in VBA editor−"
},
{
"code": null,
"e": 74243,
"s": 74192,
"text": "Double click on ThisWorkbook in Projects Explorer."
},
{
"code": null,
"e": 74294,
"s": 74243,
"text": "Double click on ThisWorkbook in Projects Explorer."
},
{
"code": null,
"e": 74423,
"s": 74294,
"text": "In the code window, select Workbook in the left dropdown list and Open in the right dropdown list. Sub Workbook_Open () appears."
},
{
"code": null,
"e": 74552,
"s": 74423,
"text": "In the code window, select Workbook in the left dropdown list and Open in the right dropdown list. Sub Workbook_Open () appears."
},
{
"code": null,
"e": 74592,
"s": 74552,
"text": "Click Modules in the Projects Explorer."
},
{
"code": null,
"e": 74632,
"s": 74592,
"text": "Click Modules in the Projects Explorer."
},
{
"code": null,
"e": 74694,
"s": 74632,
"text": "Double click on the module name that contains the macro code."
},
{
"code": null,
"e": 74756,
"s": 74694,
"text": "Double click on the module name that contains the macro code."
},
{
"code": null,
"e": 74834,
"s": 74756,
"text": "Copy the macro code from the module and paste it in the Sub WorkBook_Open ()."
},
{
"code": null,
"e": 74912,
"s": 74834,
"text": "Copy the macro code from the module and paste it in the Sub WorkBook_Open ()."
},
{
"code": null,
"e": 75034,
"s": 74912,
"text": "Save the macro-enabled workbook. Open it again. The macro runs and a new worksheet with the report structure is inserted."
},
{
"code": null,
"e": 75069,
"s": 75034,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 75084,
"s": 75069,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 75118,
"s": 75084,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 75133,
"s": 75118,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 75168,
"s": 75133,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 75183,
"s": 75168,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 75218,
"s": 75183,
"text": "\n 63 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 75233,
"s": 75218,
"text": " Yoda Learning"
},
{
"code": null,
"e": 75269,
"s": 75233,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 75284,
"s": 75269,
"text": " Yoda Learning"
},
{
"code": null,
"e": 75317,
"s": 75284,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 75339,
"s": 75317,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 75346,
"s": 75339,
"text": " Print"
},
{
"code": null,
"e": 75357,
"s": 75346,
"text": " Add Notes"
}
] |
Difference between Transfer Time and Disk Access Time in Disk Scheduling - GeeksforGeeks | 28 Apr, 2020
1. Transfer Time :Time required to transfer the required amount of data. It can be calculated by the given formula
Transfer time,
= Data to be transfer / transfer rate
Data to be transfer is given in the question and transfer rate is sometimes given and sometimes it may not be given.
It can be calculated by the given formula.
Transfer Rate,
= {(Number of heads or number of surfaces in the disk)
*(capacity of one track or number of sectors in each track)
*(Number of rotations in each track to reach the required sector)}
2. Data Access Time:It is the total time required to access the data.It means total time required to read/write the data from the disk.Following is the formula to calculated the data access time:
Data access time,
= {(Seek time) + (Rotational Latency) + (Data Transfer Time)}
Note:
Seek time – The time required by R/W head to move to the desired track from the current position.
Rotational Latency – Time required by sector to come under R/W head.
Difference between Transfer Time and Disk Access Time in Disk Scheduling :
Picked
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems | [
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n28 Apr, 2020"
},
{
"code": null,
"e": 24973,
"s": 24858,
"text": "1. Transfer Time :Time required to transfer the required amount of data. It can be calculated by the given formula"
},
{
"code": null,
"e": 25027,
"s": 24973,
"text": "Transfer time,\n= Data to be transfer / transfer rate "
},
{
"code": null,
"e": 25144,
"s": 25027,
"text": "Data to be transfer is given in the question and transfer rate is sometimes given and sometimes it may not be given."
},
{
"code": null,
"e": 25187,
"s": 25144,
"text": "It can be calculated by the given formula."
},
{
"code": null,
"e": 25396,
"s": 25187,
"text": "Transfer Rate,\n= {(Number of heads or number of surfaces in the disk)\n *(capacity of one track or number of sectors in each track)\n *(Number of rotations in each track to reach the required sector)}"
},
{
"code": null,
"e": 25592,
"s": 25396,
"text": "2. Data Access Time:It is the total time required to access the data.It means total time required to read/write the data from the disk.Following is the formula to calculated the data access time:"
},
{
"code": null,
"e": 25673,
"s": 25592,
"text": "Data access time,\n= {(Seek time) + (Rotational Latency) + (Data Transfer Time)} "
},
{
"code": null,
"e": 25679,
"s": 25673,
"text": "Note:"
},
{
"code": null,
"e": 25777,
"s": 25679,
"text": "Seek time – The time required by R/W head to move to the desired track from the current position."
},
{
"code": null,
"e": 25846,
"s": 25777,
"text": "Rotational Latency – Time required by sector to come under R/W head."
},
{
"code": null,
"e": 25921,
"s": 25846,
"text": "Difference between Transfer Time and Disk Access Time in Disk Scheduling :"
},
{
"code": null,
"e": 25928,
"s": 25921,
"text": "Picked"
},
{
"code": null,
"e": 25947,
"s": 25928,
"text": "Difference Between"
},
{
"code": null,
"e": 25955,
"s": 25947,
"text": "GATE CS"
},
{
"code": null,
"e": 25973,
"s": 25955,
"text": "Operating Systems"
},
{
"code": null,
"e": 25991,
"s": 25973,
"text": "Operating Systems"
},
{
"code": null,
"e": 26089,
"s": 25991,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26098,
"s": 26089,
"text": "Comments"
},
{
"code": null,
"e": 26111,
"s": 26098,
"text": "Old Comments"
},
{
"code": null,
"e": 26172,
"s": 26111,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26240,
"s": 26172,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26296,
"s": 26240,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 26354,
"s": 26296,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 26409,
"s": 26354,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 26429,
"s": 26409,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 26453,
"s": 26429,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 26474,
"s": 26453,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 26501,
"s": 26474,
"text": "Types of Operating Systems"
}
] |
Output of C++ programs | Set 46 (If-else statements) - GeeksforGeeks | 11 Sep, 2017
Prerequisite : Decision Making in C++
Question 1. What is the output of following program?
#include <iostream>#include <stdio.h>int main(){ if (!(std::cout << "hello")) std::cout << "world"; else std::cout << " else part"; return 0;}
Output: hello else part
Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed. Since, std::cout<<"hello" returns a reference to std::cout, therefore, if condition becomes true and if block is executed.
Question 2. What is the output of following program?
#include <iostream>using namespace std;int main(){ int a = 014; std::cout << a << std::endl; ; return 0;}
Output: 12
Explanation : Reason for the output: A 0 in the beginning of an integer makes it octal. Therefore, 12 is getting printed instead of 14.
Question 3. What is the output of following program?
#include <stdio.h>#include <iostream>int main(){ if (int q = 0) std::cout << "if part"; else std::cout << "else part"; return 0;}
Output: else part
Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, int q = 0 results in initializing the variable q as 0, therefore, the condition becomes false, and hence else block is executed.
Question 4. What is the output of following program?
#include <iostream>using namespace std;int main(){ int a = 0xC; std::cout << a << std::endl; ; return 0;}
Output: 12
Explanation : A 0x or 0X in the beginning of an integer makes it hexadecimal. Therefore, 12 which is hexadecimal equivalent of C.
Question 5. What is the output of following program?
#include <stdio.h>#include <iostream> int main(){ if (float q = 10.0) std::cout << "if part"; else std::cout << "else part"; return 0;}
Output: if partExplanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, float q = 10.0 results in initializing the variable q as 10.0, therefore, the condition becomes true, and hence if block is executed.
Question 6. What is the output of following program?
#include <stdio.h>#include <iostream> int main(){ int a, b; if ((a = 5) || (b = 0)) std::cout << "if part"; else std::cout << "else part"; return 0;}
Output: if part
Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, ((a = 5) || (b = 0)) evaluates to be true (because 5 OR 0 is 5 i.e., true), therefore, the if block is executed.
Question 7. What is the output of following program?
#include <iostream>#include <stdio.h>int main(){ int n = -1; if (n + 1) std::cout << "if part"; else std::cout << " else part"; return 0;}
Output: else part
Explanation : -1 + 1 = 0 = false
Question 8. What is the output of following program?
#include <iostream>using namespace std;int main(){ int i; for (std::cout << "hello" << std::endl; i < 5; i++) { std::cout << "hi" << std::endl; } return 0;}
Output: hello
hi
hi
hi
hi
hi
Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, (n+1) evaluates to be false (because 0 is false), therefore, the else block is executed.
This article is contributed by Palak Jain. 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.
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
unsigned specifier (%u) in C with Examples
How to show full column content in a PySpark Dataframe ?
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Output of Java Programs | Set 12
Discrete Fourier Transform and its Inverse using MATLAB
Output of Java Programs | Set 14 (Constructors)
Output of Python program | Set 6 (Lists)
Output of Java Programs | Set 34 (Collections)
Output of C programs | Set 31 (Pointers)
Output of Java Program | Set 8 | [
{
"code": null,
"e": 24340,
"s": 24312,
"text": "\n11 Sep, 2017"
},
{
"code": null,
"e": 24378,
"s": 24340,
"text": "Prerequisite : Decision Making in C++"
},
{
"code": null,
"e": 24431,
"s": 24378,
"text": "Question 1. What is the output of following program?"
},
{
"code": "#include <iostream>#include <stdio.h>int main(){ if (!(std::cout << \"hello\")) std::cout << \"world\"; else std::cout << \" else part\"; return 0;}",
"e": 24599,
"s": 24431,
"text": null
},
{
"code": null,
"e": 24623,
"s": 24599,
"text": "Output: hello else part"
},
{
"code": null,
"e": 24918,
"s": 24623,
"text": "Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed. Since, std::cout<<\"hello\" returns a reference to std::cout, therefore, if condition becomes true and if block is executed."
},
{
"code": null,
"e": 24971,
"s": 24918,
"text": "Question 2. What is the output of following program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int a = 014; std::cout << a << std::endl; ; return 0;}",
"e": 25089,
"s": 24971,
"text": null
},
{
"code": null,
"e": 25100,
"s": 25089,
"text": "Output: 12"
},
{
"code": null,
"e": 25236,
"s": 25100,
"text": "Explanation : Reason for the output: A 0 in the beginning of an integer makes it octal. Therefore, 12 is getting printed instead of 14."
},
{
"code": null,
"e": 25289,
"s": 25236,
"text": "Question 3. What is the output of following program?"
},
{
"code": "#include <stdio.h>#include <iostream>int main(){ if (int q = 0) std::cout << \"if part\"; else std::cout << \"else part\"; return 0;}",
"e": 25442,
"s": 25289,
"text": null
},
{
"code": null,
"e": 25460,
"s": 25442,
"text": "Output: else part"
},
{
"code": null,
"e": 25767,
"s": 25460,
"text": "Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, int q = 0 results in initializing the variable q as 0, therefore, the condition becomes false, and hence else block is executed."
},
{
"code": null,
"e": 25820,
"s": 25767,
"text": "Question 4. What is the output of following program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int a = 0xC; std::cout << a << std::endl; ; return 0;}",
"e": 25938,
"s": 25820,
"text": null
},
{
"code": null,
"e": 25949,
"s": 25938,
"text": "Output: 12"
},
{
"code": null,
"e": 26079,
"s": 25949,
"text": "Explanation : A 0x or 0X in the beginning of an integer makes it hexadecimal. Therefore, 12 which is hexadecimal equivalent of C."
},
{
"code": null,
"e": 26132,
"s": 26079,
"text": "Question 5. What is the output of following program?"
},
{
"code": "#include <stdio.h>#include <iostream> int main(){ if (float q = 10.0) std::cout << \"if part\"; else std::cout << \"else part\"; return 0;}",
"e": 26292,
"s": 26132,
"text": null
},
{
"code": null,
"e": 26619,
"s": 26292,
"text": "Output: if partExplanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, float q = 10.0 results in initializing the variable q as 10.0, therefore, the condition becomes true, and hence if block is executed."
},
{
"code": null,
"e": 26672,
"s": 26619,
"text": "Question 6. What is the output of following program?"
},
{
"code": "#include <stdio.h>#include <iostream> int main(){ int a, b; if ((a = 5) || (b = 0)) std::cout << \"if part\"; else std::cout << \"else part\"; return 0;}",
"e": 26849,
"s": 26672,
"text": null
},
{
"code": null,
"e": 26865,
"s": 26849,
"text": "Output: if part"
},
{
"code": null,
"e": 27156,
"s": 26865,
"text": "Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, ((a = 5) || (b = 0)) evaluates to be true (because 5 OR 0 is 5 i.e., true), therefore, the if block is executed."
},
{
"code": null,
"e": 27209,
"s": 27156,
"text": "Question 7. What is the output of following program?"
},
{
"code": "#include <iostream>#include <stdio.h>int main(){ int n = -1; if (n + 1) std::cout << \"if part\"; else std::cout << \" else part\"; return 0;}",
"e": 27376,
"s": 27209,
"text": null
},
{
"code": null,
"e": 27394,
"s": 27376,
"text": "Output: else part"
},
{
"code": null,
"e": 27427,
"s": 27394,
"text": "Explanation : -1 + 1 = 0 = false"
},
{
"code": null,
"e": 27480,
"s": 27427,
"text": "Question 8. What is the output of following program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int i; for (std::cout << \"hello\" << std::endl; i < 5; i++) { std::cout << \"hi\" << std::endl; } return 0;}",
"e": 27658,
"s": 27480,
"text": null
},
{
"code": null,
"e": 27688,
"s": 27658,
"text": "Output: hello\nhi\nhi\nhi\nhi\nhi\n"
},
{
"code": null,
"e": 27955,
"s": 27688,
"text": "Explanation : Since if-else works on the principle that if the condition provided in the if statement is true, if block is executed otherwise, else block will be executed.Since, (n+1) evaluates to be false (because 0 is false), therefore, the else block is executed."
},
{
"code": null,
"e": 28253,
"s": 27955,
"text": "This article is contributed by Palak Jain. 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": 28378,
"s": 28253,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28389,
"s": 28378,
"text": "CPP-Output"
},
{
"code": null,
"e": 28404,
"s": 28389,
"text": "Program Output"
},
{
"code": null,
"e": 28502,
"s": 28404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28545,
"s": 28502,
"text": "unsigned specifier (%u) in C with Examples"
},
{
"code": null,
"e": 28602,
"s": 28545,
"text": "How to show full column content in a PySpark Dataframe ?"
},
{
"code": null,
"e": 28698,
"s": 28602,
"text": "error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++"
},
{
"code": null,
"e": 28731,
"s": 28698,
"text": "Output of Java Programs | Set 12"
},
{
"code": null,
"e": 28787,
"s": 28731,
"text": "Discrete Fourier Transform and its Inverse using MATLAB"
},
{
"code": null,
"e": 28835,
"s": 28787,
"text": "Output of Java Programs | Set 14 (Constructors)"
},
{
"code": null,
"e": 28876,
"s": 28835,
"text": "Output of Python program | Set 6 (Lists)"
},
{
"code": null,
"e": 28923,
"s": 28876,
"text": "Output of Java Programs | Set 34 (Collections)"
},
{
"code": null,
"e": 28964,
"s": 28923,
"text": "Output of C programs | Set 31 (Pointers)"
}
] |
Automate the Conversion from Python2 to Python3 - GeeksforGeeks | 16 Jul, 2020
We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3.
This module does not come built-in with Python. To install this type the below command in the terminal.
pip install 2to3
Syntax:
2to3 [file or folder] -w
If we want to change all files in the currently open folder and all the files in the subfolder from Python2 to Python3 type the below command.
2to3.-w
If we want to change a particular file in the current folder from Python2 to Python3 then enter the following command.
2to3 gfg.py -w
Example: Consider a simple Python2 file.
To convert this file from Python2 to Python3 open the terminal in the directory containing the file and type the below command.
The Python file will now be converted to Python3. Let’s see the file.
Python-projects
python-utility
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24485,
"s": 24292,
"text": "We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3."
},
{
"code": null,
"e": 24589,
"s": 24485,
"text": "This module does not come built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 24606,
"s": 24589,
"text": "pip install 2to3"
},
{
"code": null,
"e": 24614,
"s": 24606,
"text": "Syntax:"
},
{
"code": null,
"e": 24639,
"s": 24614,
"text": "2to3 [file or folder] -w"
},
{
"code": null,
"e": 24782,
"s": 24639,
"text": "If we want to change all files in the currently open folder and all the files in the subfolder from Python2 to Python3 type the below command."
},
{
"code": null,
"e": 24790,
"s": 24782,
"text": "2to3.-w"
},
{
"code": null,
"e": 24909,
"s": 24790,
"text": "If we want to change a particular file in the current folder from Python2 to Python3 then enter the following command."
},
{
"code": null,
"e": 24924,
"s": 24909,
"text": "2to3 gfg.py -w"
},
{
"code": null,
"e": 24965,
"s": 24924,
"text": "Example: Consider a simple Python2 file."
},
{
"code": null,
"e": 25093,
"s": 24965,
"text": "To convert this file from Python2 to Python3 open the terminal in the directory containing the file and type the below command."
},
{
"code": null,
"e": 25163,
"s": 25093,
"text": "The Python file will now be converted to Python3. Let’s see the file."
},
{
"code": null,
"e": 25179,
"s": 25163,
"text": "Python-projects"
},
{
"code": null,
"e": 25194,
"s": 25179,
"text": "python-utility"
},
{
"code": null,
"e": 25201,
"s": 25194,
"text": "Python"
},
{
"code": null,
"e": 25299,
"s": 25201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25308,
"s": 25299,
"text": "Comments"
},
{
"code": null,
"e": 25321,
"s": 25308,
"text": "Old Comments"
},
{
"code": null,
"e": 25353,
"s": 25321,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25409,
"s": 25353,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25464,
"s": 25409,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25506,
"s": 25464,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25548,
"s": 25506,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25579,
"s": 25548,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25618,
"s": 25579,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25647,
"s": 25618,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 25669,
"s": 25647,
"text": "Defaultdict in Python"
}
] |
How to validate decimal numbers in JavaScript? | To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.
You can try to run the following code to validate decimal numbers −
<html>
<body>
<script>
var str = "1.5";
var re = /^[-+]?[0-9]+\.[0-9]+$/;
var found = str.match( re );
document.write("decimal" );
</script>
</body>
</html> | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression."
},
{
"code": null,
"e": 1275,
"s": 1207,
"text": "You can try to run the following code to validate decimal numbers −"
},
{
"code": null,
"e": 1486,
"s": 1275,
"text": "<html>\n <body>\n <script>\n var str = \"1.5\";\n var re = /^[-+]?[0-9]+\\.[0-9]+$/;\n var found = str.match( re );\n document.write(\"decimal\" );\n </script>\n </body>\n</html>"
}
] |
How to create a pie chart with percentage labels using ggplot2 in R ? - GeeksforGeeks | 24 Oct, 2021
In this article, we are going to see how to create a pie chart with percentage labels using ggplot2 in R Programming Language.
The dplyr package in R programming can be used to perform data manipulations and statistics. The package can be downloaded and installed using the following command in R.
install.packages("dplyr")
The ggplot2 package in R programming is used to plots graphs to visualize data and depict it using various kinds of charts. The package is used as a library after running the following command.
install.packages("ggplot2")
The ggplot method in R programming is used to do graph visualizations using the specified data frame. It is used to instantiate a ggplot object. Aesthetic mappings can be created to the plot object to determine the relationship between the x and y-axis respectively. Additional components can be added to the created ggplot object.
Syntax: ggplot(data = NULL, mapping = aes(), fill = )
Arguments :
data – Default dataset to use for plot.
mapping – List of aesthetic mappings to use for plot.
Geoms can be added to the plot using various methods. The geom_line() method in R programming can be used to add graphical lines in the plots made. It is added as a component to the existing plot. Aesthetic mappings can also contain color attributes which is assigned differently based on different data frames.
The geom_bar() method is used to construct the height of the bar proportional to the number of cases in each group.
Syntax: geom_bar ( width, stat)
Arguments :
width – Bar width
The coord_polar() component is then added in addition to the geoms so that we ensure that we are constructing a stacked bar chart in polar coordinates.
Syntax: coord_polar(theta = “x”, start = 0)
Arguments :
theta – variable to map angle to (x or y)
start – Offset of starting point from 12 o’clock in radians.
This is followed by the application of geom_text() method which is used to do textual annotations.
geom_text(aes() , label, size)
Below is the implementation:
R
# importing the required librarieslibrary(dplyr)library(ggplot2)library(ggrepel)library(forcats)library(scales) # creating a data framedata_frame <- data.frame(col1 = letters[1:3], col2 = c(46,24,12))print("Original DataFrame")print(data_frame)sum_of_obsrv <- 82 # computing the pie chart pie_chart <- ggplot(data_frame, aes(x="", y=col2, fill=col1)) + geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0) + geom_text(aes(y = col2/2 + c(0, cumsum(col2)[-length(col2)]), label = percent(col2/sum_of_obsrv )), size=5)# printing the percentageprint(pie_chart)
Output
[1] "Original DataFrame"
col1 col2
1 a 46
2 b 24
3 c 12
In order to accommodate the index inside the par chart along with levels, we can perform mutations on the data frame itself to avoid carrying out the calculations of the cumulative frequency and its corresponding midpoints during the graph plotting. This method is less cumbersome than the previous method. In this approach, the three required data properties are appended in the form of columns to the data frame, which are :
cumulative frequency, calculated by the cumsum() method taking as argument the column name.
mid point which is computed as the half of difference of cumulative frequency with column value.
label which is used to compute labeling in the form of textual annotations.
This is followed by the application of the method theme_nothing which simply strips all thematic elements in ggplot2.
R
# importing required librarieslibrary(dplyr)library(ggplot2)library(ggmap) # creating a data framedata_frame <- data.frame(col1 = c(28,69,80,40), col2 = LETTERS[1:4]) %>% mutate(col2 = factor(col2, levels = LETTERS[1:4]), # computing the column values cf = cumsum(col1), mid = cf - col1 / 2, label = paste0(col2, " ", round(col1 / sum(col1) * 100, 1), "%")) # printing the data frameprint("Original DataFrame")print(data_frame) # creating a plotggplot(data_frame, aes(x = 1, weight = col1, fill =col2)) + geom_bar(width = 1) + coord_polar(theta = "y") + geom_text(aes(x = 1.3, y = mid, label = label)) + theme_nothing()
Output
[1] "Original DataFrame"
col1 col2 cf mid label
1 28 A 28 14.0 A 12.9%
2 69 B 97 62.5 B 31.8%
3 80 C 177 137.0 C 36.9%
4 40 D 217 197.0 D 18.4%
Picked
R-ggplot
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 ?
How to change the order of bars in bar chart in R ? | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 24978,
"s": 24851,
"text": "In this article, we are going to see how to create a pie chart with percentage labels using ggplot2 in R Programming Language."
},
{
"code": null,
"e": 25149,
"s": 24978,
"text": "The dplyr package in R programming can be used to perform data manipulations and statistics. The package can be downloaded and installed using the following command in R."
},
{
"code": null,
"e": 25175,
"s": 25149,
"text": "install.packages(\"dplyr\")"
},
{
"code": null,
"e": 25370,
"s": 25175,
"text": "The ggplot2 package in R programming is used to plots graphs to visualize data and depict it using various kinds of charts. The package is used as a library after running the following command. "
},
{
"code": null,
"e": 25398,
"s": 25370,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 25730,
"s": 25398,
"text": "The ggplot method in R programming is used to do graph visualizations using the specified data frame. It is used to instantiate a ggplot object. Aesthetic mappings can be created to the plot object to determine the relationship between the x and y-axis respectively. Additional components can be added to the created ggplot object."
},
{
"code": null,
"e": 25784,
"s": 25730,
"text": "Syntax: ggplot(data = NULL, mapping = aes(), fill = )"
},
{
"code": null,
"e": 25796,
"s": 25784,
"text": "Arguments :"
},
{
"code": null,
"e": 25836,
"s": 25796,
"text": "data – Default dataset to use for plot."
},
{
"code": null,
"e": 25890,
"s": 25836,
"text": "mapping – List of aesthetic mappings to use for plot."
},
{
"code": null,
"e": 26202,
"s": 25890,
"text": "Geoms can be added to the plot using various methods. The geom_line() method in R programming can be used to add graphical lines in the plots made. It is added as a component to the existing plot. Aesthetic mappings can also contain color attributes which is assigned differently based on different data frames."
},
{
"code": null,
"e": 26318,
"s": 26202,
"text": "The geom_bar() method is used to construct the height of the bar proportional to the number of cases in each group."
},
{
"code": null,
"e": 26350,
"s": 26318,
"text": "Syntax: geom_bar ( width, stat)"
},
{
"code": null,
"e": 26362,
"s": 26350,
"text": "Arguments :"
},
{
"code": null,
"e": 26380,
"s": 26362,
"text": "width – Bar width"
},
{
"code": null,
"e": 26532,
"s": 26380,
"text": "The coord_polar() component is then added in addition to the geoms so that we ensure that we are constructing a stacked bar chart in polar coordinates."
},
{
"code": null,
"e": 26576,
"s": 26532,
"text": "Syntax: coord_polar(theta = “x”, start = 0)"
},
{
"code": null,
"e": 26589,
"s": 26576,
"text": "Arguments : "
},
{
"code": null,
"e": 26631,
"s": 26589,
"text": "theta – variable to map angle to (x or y)"
},
{
"code": null,
"e": 26692,
"s": 26631,
"text": "start – Offset of starting point from 12 o’clock in radians."
},
{
"code": null,
"e": 26792,
"s": 26692,
"text": "This is followed by the application of geom_text() method which is used to do textual annotations. "
},
{
"code": null,
"e": 26823,
"s": 26792,
"text": "geom_text(aes() , label, size)"
},
{
"code": null,
"e": 26852,
"s": 26823,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 26854,
"s": 26852,
"text": "R"
},
{
"code": "# importing the required librarieslibrary(dplyr)library(ggplot2)library(ggrepel)library(forcats)library(scales) # creating a data framedata_frame <- data.frame(col1 = letters[1:3], col2 = c(46,24,12))print(\"Original DataFrame\")print(data_frame)sum_of_obsrv <- 82 # computing the pie chart pie_chart <- ggplot(data_frame, aes(x=\"\", y=col2, fill=col1)) + geom_bar(width = 1, stat = \"identity\") + coord_polar(\"y\", start=0) + geom_text(aes(y = col2/2 + c(0, cumsum(col2)[-length(col2)]), label = percent(col2/sum_of_obsrv )), size=5)# printing the percentageprint(pie_chart)",
"e": 27470,
"s": 26854,
"text": null
},
{
"code": null,
"e": 27477,
"s": 27470,
"text": "Output"
},
{
"code": null,
"e": 27552,
"s": 27477,
"text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 a 46 \n2 b 24 \n3 c 12"
},
{
"code": null,
"e": 27980,
"s": 27552,
"text": "In order to accommodate the index inside the par chart along with levels, we can perform mutations on the data frame itself to avoid carrying out the calculations of the cumulative frequency and its corresponding midpoints during the graph plotting. This method is less cumbersome than the previous method. In this approach, the three required data properties are appended in the form of columns to the data frame, which are : "
},
{
"code": null,
"e": 28072,
"s": 27980,
"text": "cumulative frequency, calculated by the cumsum() method taking as argument the column name."
},
{
"code": null,
"e": 28169,
"s": 28072,
"text": "mid point which is computed as the half of difference of cumulative frequency with column value."
},
{
"code": null,
"e": 28245,
"s": 28169,
"text": "label which is used to compute labeling in the form of textual annotations."
},
{
"code": null,
"e": 28363,
"s": 28245,
"text": "This is followed by the application of the method theme_nothing which simply strips all thematic elements in ggplot2."
},
{
"code": null,
"e": 28365,
"s": 28363,
"text": "R"
},
{
"code": "# importing required librarieslibrary(dplyr)library(ggplot2)library(ggmap) # creating a data framedata_frame <- data.frame(col1 = c(28,69,80,40), col2 = LETTERS[1:4]) %>% mutate(col2 = factor(col2, levels = LETTERS[1:4]), # computing the column values cf = cumsum(col1), mid = cf - col1 / 2, label = paste0(col2, \" \", round(col1 / sum(col1) * 100, 1), \"%\")) # printing the data frameprint(\"Original DataFrame\")print(data_frame) # creating a plotggplot(data_frame, aes(x = 1, weight = col1, fill =col2)) + geom_bar(width = 1) + coord_polar(theta = \"y\") + geom_text(aes(x = 1.3, y = mid, label = label)) + theme_nothing() ",
"e": 29057,
"s": 28365,
"text": null
},
{
"code": null,
"e": 29064,
"s": 29057,
"text": "Output"
},
{
"code": null,
"e": 29242,
"s": 29064,
"text": "[1] \"Original DataFrame\" \ncol1 col2 cf mid label \n1 28 A 28 14.0 A 12.9% \n2 69 B 97 62.5 B 31.8% \n3 80 C 177 137.0 C 36.9% \n4 40 D 217 197.0 D 18.4%"
},
{
"code": null,
"e": 29249,
"s": 29242,
"text": "Picked"
},
{
"code": null,
"e": 29258,
"s": 29249,
"text": "R-ggplot"
},
{
"code": null,
"e": 29269,
"s": 29258,
"text": "R Language"
},
{
"code": null,
"e": 29367,
"s": 29269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29376,
"s": 29367,
"text": "Comments"
},
{
"code": null,
"e": 29389,
"s": 29376,
"text": "Old Comments"
},
{
"code": null,
"e": 29441,
"s": 29389,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29479,
"s": 29441,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29514,
"s": 29479,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29572,
"s": 29514,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29621,
"s": 29572,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29664,
"s": 29621,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29714,
"s": 29664,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29731,
"s": 29714,
"text": "R - if statement"
},
{
"code": null,
"e": 29768,
"s": 29731,
"text": "How to import an Excel File into R ?"
}
] |
Angular PrimeNG SlideMenu Component - GeeksforGeeks | 08 Sep, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the SlideMenu component in Angular PrimeNG. We will also learn about the properties, methods, styling along with their syntaxes that will be used in the code.
SlideMenu component: It is used to display the menu list in the form of the sliding animation which helps to see the menu items in a stepwise manner.
Properties:
model: It is an array of menu items. It accepts the array data type & the default value is null.
popup: It defines if the menu would be displayed as a popup. It is of the boolean data type & the default value is false.
style: It is an inline style of the component. It accepts the string data type & the default value is null.
styleClass: It is the style class of the component. It accepts the string data type & the default value is null.
easing: It is the animation to use for sliding. It accepts the string data type & the default value is ease-out.
effectDuration: It is the duration of the sliding animation in milliseconds. It accepts any data type as input & the default value is 250.
backLabel: It is the label of an element to navigate back. It accepts the string data type & the default value is back.
menuWidth: It is the width of the submenus. It accepts the number data type as input & the default value is 180.
viewportHeight: It is the height of the scrollable area, a scrollbar appears if a menu height is longer than this value. It accepts the number data type as input & the default value is 175.
appendTo: It is the target element to attach the overlay, the valid values are “body” or a local ng-template variable of another element. It accepts any data type as input & the default value is null.
baseZIndex: It is the base zIndex value to use in layering. It accepts the number data type as input & the default value is 0.
autoZIndex: It specifies whether to automatically manage the layering. It is of the boolean data type & the default value is true.
showTransitionOptions: These are the transition options to show the animation. It accepts the string data type & the default value is .12s cubic-bezier(0, 0, 0.2, 1).
hideTransitionOptions: These are the transition options to hide the animation. It accepts the string data type & the default value is .1s linear.
Method:
toggle: It is used to toggle the visibility of the popup menu.
show: It is used to displays the popup menu.
hide: It is used to hides the popup menu.
Styling:
p-slidemenu: It is a container element.
p-slidemenu-wrapper: It is a wrapper of content.
p-slidemenu-content: It is a content element.
p-slidemenu-backward: It is an element to navigate to the previous menu on click.
p-menu-list: It is a list element.
p-menuitem: It is a menu item element.
p-menuitem-text: It is a label of a menu item.
p-menuitem-icon: It is an icon of a menu item.
p-submenu-icon: It is the arrow icon of a submenu.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: After the complete installation, it will look like the following:
Example 1: This is the basic example that shows how to use the SlideMenu component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG PanelMenu Component</h5><p-slideMenu [model]="gfg" ></p-slideMenu>
app.component.ts
import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { SlideMenuModule } from 'primeng/slidemenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, SlideMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
Output:
Example 2: In this example, we will make a slidemenu component using a popup.
app.component.html
<h5>PrimeNG SlideMenu Component</h5><button #btn type="button" pButton label="Click Here" (click)="menu.toggle($event)"></button> <p-slideMenu #menu [model]="gfg" [popup]="true" [viewportHeight]="250"></p-slideMenu>
app.component.ts
import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { SlideMenuModule } from 'primeng/slidemenu';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SlideMenuModule, ButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/slidemenu
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25029,
"s": 25001,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 25429,
"s": 25029,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the SlideMenu component in Angular PrimeNG. We will also learn about the properties, methods, styling along with their syntaxes that will be used in the code. "
},
{
"code": null,
"e": 25579,
"s": 25429,
"text": "SlideMenu component: It is used to display the menu list in the form of the sliding animation which helps to see the menu items in a stepwise manner."
},
{
"code": null,
"e": 25591,
"s": 25579,
"text": "Properties:"
},
{
"code": null,
"e": 25688,
"s": 25591,
"text": "model: It is an array of menu items. It accepts the array data type & the default value is null."
},
{
"code": null,
"e": 25810,
"s": 25688,
"text": "popup: It defines if the menu would be displayed as a popup. It is of the boolean data type & the default value is false."
},
{
"code": null,
"e": 25918,
"s": 25810,
"text": "style: It is an inline style of the component. It accepts the string data type & the default value is null."
},
{
"code": null,
"e": 26031,
"s": 25918,
"text": "styleClass: It is the style class of the component. It accepts the string data type & the default value is null."
},
{
"code": null,
"e": 26144,
"s": 26031,
"text": "easing: It is the animation to use for sliding. It accepts the string data type & the default value is ease-out."
},
{
"code": null,
"e": 26283,
"s": 26144,
"text": "effectDuration: It is the duration of the sliding animation in milliseconds. It accepts any data type as input & the default value is 250."
},
{
"code": null,
"e": 26403,
"s": 26283,
"text": "backLabel: It is the label of an element to navigate back. It accepts the string data type & the default value is back."
},
{
"code": null,
"e": 26516,
"s": 26403,
"text": "menuWidth: It is the width of the submenus. It accepts the number data type as input & the default value is 180."
},
{
"code": null,
"e": 26706,
"s": 26516,
"text": "viewportHeight: It is the height of the scrollable area, a scrollbar appears if a menu height is longer than this value. It accepts the number data type as input & the default value is 175."
},
{
"code": null,
"e": 26907,
"s": 26706,
"text": "appendTo: It is the target element to attach the overlay, the valid values are “body” or a local ng-template variable of another element. It accepts any data type as input & the default value is null."
},
{
"code": null,
"e": 27034,
"s": 26907,
"text": "baseZIndex: It is the base zIndex value to use in layering. It accepts the number data type as input & the default value is 0."
},
{
"code": null,
"e": 27165,
"s": 27034,
"text": "autoZIndex: It specifies whether to automatically manage the layering. It is of the boolean data type & the default value is true."
},
{
"code": null,
"e": 27332,
"s": 27165,
"text": "showTransitionOptions: These are the transition options to show the animation. It accepts the string data type & the default value is .12s cubic-bezier(0, 0, 0.2, 1)."
},
{
"code": null,
"e": 27478,
"s": 27332,
"text": "hideTransitionOptions: These are the transition options to hide the animation. It accepts the string data type & the default value is .1s linear."
},
{
"code": null,
"e": 27486,
"s": 27478,
"text": "Method:"
},
{
"code": null,
"e": 27549,
"s": 27486,
"text": "toggle: It is used to toggle the visibility of the popup menu."
},
{
"code": null,
"e": 27594,
"s": 27549,
"text": "show: It is used to displays the popup menu."
},
{
"code": null,
"e": 27636,
"s": 27594,
"text": "hide: It is used to hides the popup menu."
},
{
"code": null,
"e": 27647,
"s": 27638,
"text": "Styling:"
},
{
"code": null,
"e": 27687,
"s": 27647,
"text": "p-slidemenu: It is a container element."
},
{
"code": null,
"e": 27736,
"s": 27687,
"text": "p-slidemenu-wrapper: It is a wrapper of content."
},
{
"code": null,
"e": 27782,
"s": 27736,
"text": "p-slidemenu-content: It is a content element."
},
{
"code": null,
"e": 27864,
"s": 27782,
"text": "p-slidemenu-backward: It is an element to navigate to the previous menu on click."
},
{
"code": null,
"e": 27899,
"s": 27864,
"text": "p-menu-list: It is a list element."
},
{
"code": null,
"e": 27938,
"s": 27899,
"text": "p-menuitem: It is a menu item element."
},
{
"code": null,
"e": 27985,
"s": 27938,
"text": "p-menuitem-text: It is a label of a menu item."
},
{
"code": null,
"e": 28032,
"s": 27985,
"text": "p-menuitem-icon: It is an icon of a menu item."
},
{
"code": null,
"e": 28083,
"s": 28032,
"text": "p-submenu-icon: It is the arrow icon of a submenu."
},
{
"code": null,
"e": 28135,
"s": 28083,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 28202,
"s": 28135,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 28217,
"s": 28202,
"text": "ng new appname"
},
{
"code": null,
"e": 28314,
"s": 28217,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 28325,
"s": 28314,
"text": "cd appname"
},
{
"code": null,
"e": 28374,
"s": 28325,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 28431,
"s": 28374,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 28516,
"s": 28431,
"text": "Project Structure: After the complete installation, it will look like the following:"
},
{
"code": null,
"e": 28602,
"s": 28518,
"text": "Example 1: This is the basic example that shows how to use the SlideMenu component."
},
{
"code": null,
"e": 28621,
"s": 28602,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG PanelMenu Component</h5><p-slideMenu [model]=\"gfg\" ></p-slideMenu>",
"e": 28722,
"s": 28621,
"text": null
},
{
"code": null,
"e": 28739,
"s": 28722,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}",
"e": 29314,
"s": 28739,
"text": null
},
{
"code": null,
"e": 29328,
"s": 29314,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { SlideMenuModule } from 'primeng/slidemenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, SlideMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 29805,
"s": 29328,
"text": null
},
{
"code": null,
"e": 29813,
"s": 29805,
"text": "Output:"
},
{
"code": null,
"e": 29891,
"s": 29813,
"text": "Example 2: In this example, we will make a slidemenu component using a popup."
},
{
"code": null,
"e": 29910,
"s": 29891,
"text": "app.component.html"
},
{
"code": "<h5>PrimeNG SlideMenu Component</h5><button #btn type=\"button\" pButton label=\"Click Here\" (click)=\"menu.toggle($event)\"></button> <p-slideMenu #menu [model]=\"gfg\" [popup]=\"true\" [viewportHeight]=\"250\"></p-slideMenu>",
"e": 30138,
"s": 29910,
"text": null
},
{
"code": null,
"e": 30155,
"s": 30138,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}",
"e": 30730,
"s": 30155,
"text": null
},
{
"code": null,
"e": 30744,
"s": 30730,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { SlideMenuModule } from 'primeng/slidemenu';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SlideMenuModule, ButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 31270,
"s": 30744,
"text": null
},
{
"code": null,
"e": 31278,
"s": 31270,
"text": "Output:"
},
{
"code": null,
"e": 31341,
"s": 31278,
"text": "Reference: https://primefaces.org/primeng/showcase/#/slidemenu"
},
{
"code": null,
"e": 31357,
"s": 31341,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 31367,
"s": 31357,
"text": "AngularJS"
},
{
"code": null,
"e": 31384,
"s": 31367,
"text": "Web Technologies"
},
{
"code": null,
"e": 31482,
"s": 31384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31491,
"s": 31482,
"text": "Comments"
},
{
"code": null,
"e": 31504,
"s": 31491,
"text": "Old Comments"
},
{
"code": null,
"e": 31548,
"s": 31504,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 31612,
"s": 31548,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 31665,
"s": 31612,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 31700,
"s": 31665,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31724,
"s": 31700,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 31766,
"s": 31724,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31799,
"s": 31766,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31861,
"s": 31799,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31904,
"s": 31861,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Guide to Advanced CNNs in tensorflow | Towards Data Science | The first ConvNet model I built was to identify dogs or cats and had a basic structure of a sequential model having Conv2d layers along with a mix of batch normalization and max-pooling layers here and there and not to forget a dropout layer to counter overfitting😏. All this was followed by a flattening layer which ultimately led to a Dense layer. They were added to the model using add. It worked well and gave a good enough accuracy. Then I tried the famous MNIST dataset and used the same architecture. All I had to do was to change the loss in my dense layer from binary cross-entropy to categorical cross-entropy and tada I felt I had mastered CNNs. But, boy, was I wrong! There is a lot more to it like making sparsely connected architectures with different types of Conv2d layers, applying different techniques for overfitting and lots more.
Advanced Conv2D layers
Advanced Conv2D layers
Depthwise Separable Convolutions
Dilated Convolutions
2. Counter Overfitting
Spatial Dropout
Gaussian Dropout
Activity Regularization
3. Complex Architectures
Sparsely Connected Architectures
Skip Connections
4. Conclusion
They are more efficient, require less memory and less computation and can even provide better results in some cases. Due to these characteristics, they are generally used when our model has to be deployed on Edge/IoT devices because they have limited CPU and RAM. It divides the process of a normal convolution layer into two processes i.e. depthwise convolution and pointwise convolution. In depthwise convolution, the kernel iterates over one channel at a time. The pointwise convolution uses a 1x1 kernel to increase the number of channels. This way the total number of multiplications required is reduced and that makes our network faster. This is a great article to learn more about it.
tensorflow.keras.layers.SeparableConv2D(32, (3, 3), padding="same"))
Dilated convolutions can be implemented in normal convolution layers as well as depthwise separable convolution layers. It is a normal convolution operation with gaps. Along with providing a larger receptive field, efficient computation and lesser memory consumption it also preserves the resolution and order of data. Hence it generally improves the performance of the model.
#In Normal Conv2Dtf.keras.layers.Conv2D(32, (3, 3), padding='same', dilation_rate=(2, 2))#In Seperable Conv2Dtf.keras.layers.SeparableConv2D(no_of_filters, (3, 3), padding='same', dilation_rate=(2, 2))
In normal dropout, some randomly selected neurons are ignored during training. Those neurons do not contribute in the forward pass and their weights are not updated during backward pass. This leads the network to learn multiple independent internal representations and it makes it less probable to overfit on the training data. In spatial dropout instead of dropping neurons, we drop out entire feature maps. As stated in the Keras documentation for spatial documentation:
If adjacent pixels within feature maps are strongly correlated (as is normally the case in early convolution layers) then regular dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease. In this case, spatial dropout will help promote independence between feature maps and should be used instead.
tf.keras.layers.SpatialDropout2D(0.5)
It is a combination of dropout and Gaussian noise. That means that this layer along with dropping some neurons also applies multiplicative 1-centered Gaussian noise. Like the normal dropout, it also takes the argument rate. From its documentation:
Float, drop probability (as with dropout). The multiplicative noise will have standard deviation sqrt(rate / (1 — rate)).
For more in-depth reading about it, you can refer to this article here.
tf.keras.layers.GaussianDropout(0.5)
Regularization makes slight changes to networks so that they generalize better. It encourages a neural network to learn sparse features or internal representations of raw observations which makes the model perform better on unseen data. There are three types of regularization techniques supported:
l1: Activity is calculated as the sum of absolute values.
l2: Activity is calculated as the sum of the squared values.
l1_l2: Activity is calculated as the sum of absolute and sum of the squared values.
The value of weight matrices decreases due to the addition of the regularization term and it leads to simpler models which reduces overfitting. For more information about regularization techniques refer here.
#L1 regularizationtf.keras.layers.ActivityRegularization(l1=0.001)#L2 regularizatontf.keras.layers.ActivityRegularization(l2=0.001)#L1_L2 regularizationtf.keras.layers.ActivityRegularization(l1=0.001, l2=0.001)
There are two types of architectures, densely connected and sparsely connected.
It was popularised by the Inception network. So what was the need for these types of architectures? Can’t we just keep on adding layers and the deeper the network the better the result? Well, not at all. The bigger the model, the more prone is it to overfitting especially with smaller datasets and it also increases the amount of computation power required to train it. Sometimes even the training error even becomes worse. Sparsely connected architectures help us in increasing the depth and width of our models while not overshooting the computation power needed. They can have different sizes of kernels for convolutions which also helps the model when the test objects are of different sizes.
Generally, we use tf.keras.layers.add to make densely connected architectures. We can visualize our models using tf.keras.utils.plot_model.
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Conv2D, add, Inputfrom tensorflow.keras.utils import plot_modelmodel = Sequential()model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same', input_shape=(128, 128, 3)))model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same'))model.add(Conv2D(128, (3, 3), activation = 'relu', padding='same'))plot_model(model)
We can also create models like these by assigning them to variables and placing them the variable name to the layer it is connected to at the end. Input shape is specified in tf.keras.layers.Input and tf.keras.models.Model is used to underline the inputs and outputs i.e. the first and last layer of our model.
from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Conv2D, Inputfrom tensorflow.keras.utils import plot_modelinput_flow = Input(shape=(128, 128, 3))x = Conv2D(64, (3, 3), activation = 'relu', padding='same')(input_flow)x = Conv2D(64, (3, 3), activation = 'relu', padding='same')(x)x = Conv2D(128, (3, 3), activation = 'relu', padding='same')(x)model = Model(inputs=input_flow, outputs=x)plot_model(model)
Now, to make sparsely connected architectures we just need to assign some layer to multiple layers and then use tf.keras.layers.concatenate to join them.
from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Conv2D, Input, concatenatefrom tensorflow.keras.utils import plot_modelinput_flow = Input(shape=(128, 128, 3))x = Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(128, 128, 3))(input_flow)one = Conv2D(64, (3, 3), activation='relu', padding='same')(x)two = Conv2D(64, (5, 5), activation='relu', padding='same')(x)three = Conv2D(64, (7, 7), activation='relu', padding='same')(x)x = concatenate([one, two, three])x = Conv2D(128, (3, 3), activation = 'relu', padding='same')(x)model = Model(inputs=input_flow, outputs=x)plot_model(model)
This was popularised by the network ResNet50. The main idea behind skip connections was to solve this problem given below by Microsoft Research as given in their paper Deep Residual Learning for Image Recognition.
When deeper networks are able to start converging, a degradation problem has been exposed: with the network depth increasing, accuracy gets saturated (which might be unsurprising) and then degrades rapidly. Unexpectedly, such degradation is not caused by overfitting, and adding more layers to a suitably deep model leads to higher training error...
Its advantage is that it makes estimating good values for the weights easier and the model generalizes better.
If you understood how to make sparsely connected architectures, you can easily guess how this will work but in this case to join them we will use tf.keras.layers.Add.
from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Conv2D, Input, Addfrom tensorflow.keras.utils import plot_modelinput_flow = Input(shape=(128, 128, 3))x = Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(128, 128, 3))(input_flow)one = Conv2D(64, (3, 3), activation='relu', padding='same')(x)two = Conv2D(64, (5, 5), activation='relu', padding='same')(one)three = Conv2D(64, (7, 7), activation='relu', padding='same')(two)x = Add()([x, three])x = Conv2D(128, (3, 3), activation = 'relu', padding='same')(x)model = Model(inputs=input_flow, outputs=x)plot_model(model)
Using these techniques might improve our model, but that’s not always the case. They might even perform worse than a simple densely connected architecture with normal Conv2D layers. You will need to try and see which strategy gives the best results.
For revision purposes, I have created a model using the concepts provided above. This is just for revision purpose and I do not garuntee that this model will give better results. | [
{
"code": null,
"e": 1023,
"s": 172,
"text": "The first ConvNet model I built was to identify dogs or cats and had a basic structure of a sequential model having Conv2d layers along with a mix of batch normalization and max-pooling layers here and there and not to forget a dropout layer to counter overfitting😏. All this was followed by a flattening layer which ultimately led to a Dense layer. They were added to the model using add. It worked well and gave a good enough accuracy. Then I tried the famous MNIST dataset and used the same architecture. All I had to do was to change the loss in my dense layer from binary cross-entropy to categorical cross-entropy and tada I felt I had mastered CNNs. But, boy, was I wrong! There is a lot more to it like making sparsely connected architectures with different types of Conv2d layers, applying different techniques for overfitting and lots more."
},
{
"code": null,
"e": 1046,
"s": 1023,
"text": "Advanced Conv2D layers"
},
{
"code": null,
"e": 1069,
"s": 1046,
"text": "Advanced Conv2D layers"
},
{
"code": null,
"e": 1102,
"s": 1069,
"text": "Depthwise Separable Convolutions"
},
{
"code": null,
"e": 1123,
"s": 1102,
"text": "Dilated Convolutions"
},
{
"code": null,
"e": 1146,
"s": 1123,
"text": "2. Counter Overfitting"
},
{
"code": null,
"e": 1162,
"s": 1146,
"text": "Spatial Dropout"
},
{
"code": null,
"e": 1179,
"s": 1162,
"text": "Gaussian Dropout"
},
{
"code": null,
"e": 1203,
"s": 1179,
"text": "Activity Regularization"
},
{
"code": null,
"e": 1228,
"s": 1203,
"text": "3. Complex Architectures"
},
{
"code": null,
"e": 1261,
"s": 1228,
"text": "Sparsely Connected Architectures"
},
{
"code": null,
"e": 1278,
"s": 1261,
"text": "Skip Connections"
},
{
"code": null,
"e": 1292,
"s": 1278,
"text": "4. Conclusion"
},
{
"code": null,
"e": 1984,
"s": 1292,
"text": "They are more efficient, require less memory and less computation and can even provide better results in some cases. Due to these characteristics, they are generally used when our model has to be deployed on Edge/IoT devices because they have limited CPU and RAM. It divides the process of a normal convolution layer into two processes i.e. depthwise convolution and pointwise convolution. In depthwise convolution, the kernel iterates over one channel at a time. The pointwise convolution uses a 1x1 kernel to increase the number of channels. This way the total number of multiplications required is reduced and that makes our network faster. This is a great article to learn more about it."
},
{
"code": null,
"e": 2053,
"s": 1984,
"text": "tensorflow.keras.layers.SeparableConv2D(32, (3, 3), padding=\"same\"))"
},
{
"code": null,
"e": 2430,
"s": 2053,
"text": "Dilated convolutions can be implemented in normal convolution layers as well as depthwise separable convolution layers. It is a normal convolution operation with gaps. Along with providing a larger receptive field, efficient computation and lesser memory consumption it also preserves the resolution and order of data. Hence it generally improves the performance of the model."
},
{
"code": null,
"e": 2632,
"s": 2430,
"text": "#In Normal Conv2Dtf.keras.layers.Conv2D(32, (3, 3), padding='same', dilation_rate=(2, 2))#In Seperable Conv2Dtf.keras.layers.SeparableConv2D(no_of_filters, (3, 3), padding='same', dilation_rate=(2, 2))"
},
{
"code": null,
"e": 3105,
"s": 2632,
"text": "In normal dropout, some randomly selected neurons are ignored during training. Those neurons do not contribute in the forward pass and their weights are not updated during backward pass. This leads the network to learn multiple independent internal representations and it makes it less probable to overfit on the training data. In spatial dropout instead of dropping neurons, we drop out entire feature maps. As stated in the Keras documentation for spatial documentation:"
},
{
"code": null,
"e": 3460,
"s": 3105,
"text": "If adjacent pixels within feature maps are strongly correlated (as is normally the case in early convolution layers) then regular dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease. In this case, spatial dropout will help promote independence between feature maps and should be used instead."
},
{
"code": null,
"e": 3498,
"s": 3460,
"text": "tf.keras.layers.SpatialDropout2D(0.5)"
},
{
"code": null,
"e": 3746,
"s": 3498,
"text": "It is a combination of dropout and Gaussian noise. That means that this layer along with dropping some neurons also applies multiplicative 1-centered Gaussian noise. Like the normal dropout, it also takes the argument rate. From its documentation:"
},
{
"code": null,
"e": 3868,
"s": 3746,
"text": "Float, drop probability (as with dropout). The multiplicative noise will have standard deviation sqrt(rate / (1 — rate))."
},
{
"code": null,
"e": 3940,
"s": 3868,
"text": "For more in-depth reading about it, you can refer to this article here."
},
{
"code": null,
"e": 3977,
"s": 3940,
"text": "tf.keras.layers.GaussianDropout(0.5)"
},
{
"code": null,
"e": 4276,
"s": 3977,
"text": "Regularization makes slight changes to networks so that they generalize better. It encourages a neural network to learn sparse features or internal representations of raw observations which makes the model perform better on unseen data. There are three types of regularization techniques supported:"
},
{
"code": null,
"e": 4334,
"s": 4276,
"text": "l1: Activity is calculated as the sum of absolute values."
},
{
"code": null,
"e": 4395,
"s": 4334,
"text": "l2: Activity is calculated as the sum of the squared values."
},
{
"code": null,
"e": 4479,
"s": 4395,
"text": "l1_l2: Activity is calculated as the sum of absolute and sum of the squared values."
},
{
"code": null,
"e": 4688,
"s": 4479,
"text": "The value of weight matrices decreases due to the addition of the regularization term and it leads to simpler models which reduces overfitting. For more information about regularization techniques refer here."
},
{
"code": null,
"e": 4899,
"s": 4688,
"text": "#L1 regularizationtf.keras.layers.ActivityRegularization(l1=0.001)#L2 regularizatontf.keras.layers.ActivityRegularization(l2=0.001)#L1_L2 regularizationtf.keras.layers.ActivityRegularization(l1=0.001, l2=0.001)"
},
{
"code": null,
"e": 4979,
"s": 4899,
"text": "There are two types of architectures, densely connected and sparsely connected."
},
{
"code": null,
"e": 5677,
"s": 4979,
"text": "It was popularised by the Inception network. So what was the need for these types of architectures? Can’t we just keep on adding layers and the deeper the network the better the result? Well, not at all. The bigger the model, the more prone is it to overfitting especially with smaller datasets and it also increases the amount of computation power required to train it. Sometimes even the training error even becomes worse. Sparsely connected architectures help us in increasing the depth and width of our models while not overshooting the computation power needed. They can have different sizes of kernels for convolutions which also helps the model when the test objects are of different sizes."
},
{
"code": null,
"e": 5817,
"s": 5677,
"text": "Generally, we use tf.keras.layers.add to make densely connected architectures. We can visualize our models using tf.keras.utils.plot_model."
},
{
"code": null,
"e": 6226,
"s": 5817,
"text": "from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Conv2D, add, Inputfrom tensorflow.keras.utils import plot_modelmodel = Sequential()model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same', input_shape=(128, 128, 3)))model.add(Conv2D(64, (3, 3), activation = 'relu', padding='same'))model.add(Conv2D(128, (3, 3), activation = 'relu', padding='same'))plot_model(model)"
},
{
"code": null,
"e": 6537,
"s": 6226,
"text": "We can also create models like these by assigning them to variables and placing them the variable name to the layer it is connected to at the end. Input shape is specified in tf.keras.layers.Input and tf.keras.models.Model is used to underline the inputs and outputs i.e. the first and last layer of our model."
},
{
"code": null,
"e": 6968,
"s": 6537,
"text": "from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Conv2D, Inputfrom tensorflow.keras.utils import plot_modelinput_flow = Input(shape=(128, 128, 3))x = Conv2D(64, (3, 3), activation = 'relu', padding='same')(input_flow)x = Conv2D(64, (3, 3), activation = 'relu', padding='same')(x)x = Conv2D(128, (3, 3), activation = 'relu', padding='same')(x)model = Model(inputs=input_flow, outputs=x)plot_model(model)"
},
{
"code": null,
"e": 7122,
"s": 6968,
"text": "Now, to make sparsely connected architectures we just need to assign some layer to multiple layers and then use tf.keras.layers.concatenate to join them."
},
{
"code": null,
"e": 7751,
"s": 7122,
"text": "from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Conv2D, Input, concatenatefrom tensorflow.keras.utils import plot_modelinput_flow = Input(shape=(128, 128, 3))x = Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(128, 128, 3))(input_flow)one = Conv2D(64, (3, 3), activation='relu', padding='same')(x)two = Conv2D(64, (5, 5), activation='relu', padding='same')(x)three = Conv2D(64, (7, 7), activation='relu', padding='same')(x)x = concatenate([one, two, three])x = Conv2D(128, (3, 3), activation = 'relu', padding='same')(x)model = Model(inputs=input_flow, outputs=x)plot_model(model)"
},
{
"code": null,
"e": 7965,
"s": 7751,
"text": "This was popularised by the network ResNet50. The main idea behind skip connections was to solve this problem given below by Microsoft Research as given in their paper Deep Residual Learning for Image Recognition."
},
{
"code": null,
"e": 8315,
"s": 7965,
"text": "When deeper networks are able to start converging, a degradation problem has been exposed: with the network depth increasing, accuracy gets saturated (which might be unsurprising) and then degrades rapidly. Unexpectedly, such degradation is not caused by overfitting, and adding more layers to a suitably deep model leads to higher training error..."
},
{
"code": null,
"e": 8426,
"s": 8315,
"text": "Its advantage is that it makes estimating good values for the weights easier and the model generalizes better."
},
{
"code": null,
"e": 8593,
"s": 8426,
"text": "If you understood how to make sparsely connected architectures, you can easily guess how this will work but in this case to join them we will use tf.keras.layers.Add."
},
{
"code": null,
"e": 9205,
"s": 8593,
"text": "from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Conv2D, Input, Addfrom tensorflow.keras.utils import plot_modelinput_flow = Input(shape=(128, 128, 3))x = Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(128, 128, 3))(input_flow)one = Conv2D(64, (3, 3), activation='relu', padding='same')(x)two = Conv2D(64, (5, 5), activation='relu', padding='same')(one)three = Conv2D(64, (7, 7), activation='relu', padding='same')(two)x = Add()([x, three])x = Conv2D(128, (3, 3), activation = 'relu', padding='same')(x)model = Model(inputs=input_flow, outputs=x)plot_model(model)"
},
{
"code": null,
"e": 9455,
"s": 9205,
"text": "Using these techniques might improve our model, but that’s not always the case. They might even perform worse than a simple densely connected architecture with normal Conv2D layers. You will need to try and see which strategy gives the best results."
}
] |
How to change the color of a plot frame in Matplotlib? | To change the color of a plot frame, we can set axes ticklines and spine value into a specific color.
Create a figure and add a set of subplots, using subplots method with value 4.
Create a figure and add a set of subplots, using subplots method with value 4.
Zip colors with axes and iterate them together.
Zip colors with axes and iterate them together.
In the iteration, set the color for spines values and ticklines (x, y).
In the iteration, set the color for spines values and ticklines (x, y).
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4)
for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'red', 'yellow', 'blue']):
plt.setp(ax.spines.values(), color=color)
ax.plot([8, 3], c=color)
plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)
plt.show() | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To change the color of a plot frame, we can set axes ticklines and spine value into a specific color."
},
{
"code": null,
"e": 1243,
"s": 1164,
"text": "Create a figure and add a set of subplots, using subplots method with value 4."
},
{
"code": null,
"e": 1322,
"s": 1243,
"text": "Create a figure and add a set of subplots, using subplots method with value 4."
},
{
"code": null,
"e": 1370,
"s": 1322,
"text": "Zip colors with axes and iterate them together."
},
{
"code": null,
"e": 1418,
"s": 1370,
"text": "Zip colors with axes and iterate them together."
},
{
"code": null,
"e": 1490,
"s": 1418,
"text": "In the iteration, set the color for spines values and ticklines (x, y)."
},
{
"code": null,
"e": 1562,
"s": 1490,
"text": "In the iteration, set the color for spines values and ticklines (x, y)."
},
{
"code": null,
"e": 1614,
"s": 1562,
"text": "Adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1666,
"s": 1614,
"text": "Adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1708,
"s": 1666,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1750,
"s": 1708,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2146,
"s": 1750,
"text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig, (ax1, ax2, ax3, ax4) = plt.subplots(4)\nfor ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'red', 'yellow', 'blue']):\n plt.setp(ax.spines.values(), color=color)\n ax.plot([8, 3], c=color)\n plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)\nplt.show()"
}
] |
Default values of static variables in C | When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.
Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program.
Here is the syntax of static variables in C language,
static datatype variable_name;
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
value − Any value to initialize the variable. By default, it is zero.
Here is an example of static variables in C language,
Live Demo
#include <stdio.h>
int main() {
static int a;
int b;
printf("Default value of static variable : %d\n", a);
printf("Default value of non-static variable : %d\n", b);
return 0;
}
Default value of static variable : 0
Default value of non-static variable : 0
In the above program, two variables are declared, one is static and another is non-static. The default values of both variables are displayed as follows −
static int a;
int b;
printf("Default value of static variable : %d\n", a);
printf("Default value of non-static variable : %d\n", b); | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name."
},
{
"code": null,
"e": 1569,
"s": 1262,
"text": "Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program."
},
{
"code": null,
"e": 1623,
"s": 1569,
"text": "Here is the syntax of static variables in C language,"
},
{
"code": null,
"e": 1654,
"s": 1623,
"text": "static datatype variable_name;"
},
{
"code": null,
"e": 1660,
"s": 1654,
"text": "Here,"
},
{
"code": null,
"e": 1723,
"s": 1660,
"text": "datatype − The datatype of variable like int, char, float etc."
},
{
"code": null,
"e": 1783,
"s": 1723,
"text": "variable_name − This is the name of variable given by user."
},
{
"code": null,
"e": 1853,
"s": 1783,
"text": "value − Any value to initialize the variable. By default, it is zero."
},
{
"code": null,
"e": 1907,
"s": 1853,
"text": "Here is an example of static variables in C language,"
},
{
"code": null,
"e": 1918,
"s": 1907,
"text": " Live Demo"
},
{
"code": null,
"e": 2110,
"s": 1918,
"text": "#include <stdio.h>\nint main() {\n static int a;\n int b;\n printf(\"Default value of static variable : %d\\n\", a);\n printf(\"Default value of non-static variable : %d\\n\", b);\n return 0;\n}"
},
{
"code": null,
"e": 2188,
"s": 2110,
"text": "Default value of static variable : 0\nDefault value of non-static variable : 0"
},
{
"code": null,
"e": 2343,
"s": 2188,
"text": "In the above program, two variables are declared, one is static and another is non-static. The default values of both variables are displayed as follows −"
},
{
"code": null,
"e": 2476,
"s": 2343,
"text": "static int a;\nint b;\nprintf(\"Default value of static variable : %d\\n\", a);\nprintf(\"Default value of non-static variable : %d\\n\", b);"
}
] |
Python How to sort a list of strings | In this tutorial, we are going to see how to sort a list of strings. We'll sort the given list of strings with sort method and sorted function. And then we'll see how to sort the list of strings based on different criteria like length, value, etc.,
Let's see how to sort a list of strings using list.sort() method. The sort method list is an insort. It'll directly sort the original list. Let's see the code.
Live Demo
# list of strings
strings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']
# sorting the list in ascending order
strings.sort()
# printing the sorted list
print(strings)
If you execute the above program, then you will get the following result.
['C', 'Django', 'Java', 'Javascript', 'Python', 'React', 'Spring']
We can sort the list in descending order with the argument reverse as True to the sort Let's see the code to sort the list in descending order.
Live Demo
# list of strings
strings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']
# sorting the list in descending order
strings.sort(reverse=True)
# printing the sorted list
print(strings)
If you execute the above program, then you will get the following result.
['Spring', 'React', 'Python', 'Javascript', 'Java', 'Django', 'C']
We have seen how to sort the list of strings using sort method. Let's see how to sort the list of strings using sorted built-in function.
Live Demo
# list of strings
strings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']
# sorting the list in ascending order
sorted_strings = sorted(strings)
# printing the sorted list
print(sorted_strings)
If you execute the above program, then you will get the following result.
['C', 'Django', 'Java', 'Javascript', 'Python', 'React', 'Spring']
We can also sort the list in descending order using sorted function by passing reverse as True to the function as a second argument. Let's see the code.
Live Demo
# list of strings
strings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']
# sorting the list in descending order
sorted_strings = sorted(strings, reverse=True)
# printing the sorted list
print(sorted_strings)
If you execute the above program, then you will get the following result.
['Spring', 'React', 'Python', 'Javascript', 'Java', 'Django', 'C']
What if we want to sort the list of strings based on the length? Yeah, we can sort based on length using the sort method and sorted function by passing a key as an argument.Let's see how to sort the list of strings based on their length.
Live Demo
# list of strings
strings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']
# sorting the list in ascending order - length
strings.sort(key=len)
# printing the sorted list
print(strings)
If you execute the above program, then you will get the following result.
['C', 'Java', 'React', 'Python', 'Django', 'Spring', 'Javascript']
We can pass any function to the key argument. The sort method will sort the list based on the return value of the function given to the key argument. The same thing will work in the sorted
function as well.
Let's see an example using the sorted function by sorting the list of strings based on their
value.
Live Demo
# list of strings
strings = ['7', '34', '3', '23', '454', '12', '9']
# sorting the list in ascending order - int value
sorted_strings = sorted(strings, key=int)
# printing the sorted list
print(sorted_strings)
If you execute the above program, then you will get the following result.
['3', '7', '9', '12', '23', '34', '454']
We can pass key and reverse arguments at a time to the sort method and sorted function to achieve whatever we want. Try and explore them. If you have any doubts regarding the tutorial, mention them in the comment section | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "In this tutorial, we are going to see how to sort a list of strings. We'll sort the given list of strings with sort method and sorted function. And then we'll see how to sort the list of strings based on different criteria like length, value, etc.,"
},
{
"code": null,
"e": 1471,
"s": 1311,
"text": "Let's see how to sort a list of strings using list.sort() method. The sort method list is an insort. It'll directly sort the original list. Let's see the code."
},
{
"code": null,
"e": 1482,
"s": 1471,
"text": " Live Demo"
},
{
"code": null,
"e": 1672,
"s": 1482,
"text": "# list of strings\nstrings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']\n# sorting the list in ascending order\nstrings.sort()\n# printing the sorted list\nprint(strings)"
},
{
"code": null,
"e": 1746,
"s": 1672,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 1813,
"s": 1746,
"text": "['C', 'Django', 'Java', 'Javascript', 'Python', 'React', 'Spring']"
},
{
"code": null,
"e": 1957,
"s": 1813,
"text": "We can sort the list in descending order with the argument reverse as True to the sort Let's see the code to sort the list in descending order."
},
{
"code": null,
"e": 1968,
"s": 1957,
"text": " Live Demo"
},
{
"code": null,
"e": 2171,
"s": 1968,
"text": "# list of strings\nstrings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']\n# sorting the list in descending order\nstrings.sort(reverse=True)\n# printing the sorted list\nprint(strings)"
},
{
"code": null,
"e": 2245,
"s": 2171,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 2312,
"s": 2245,
"text": "['Spring', 'React', 'Python', 'Javascript', 'Java', 'Django', 'C']"
},
{
"code": null,
"e": 2450,
"s": 2312,
"text": "We have seen how to sort the list of strings using sort method. Let's see how to sort the list of strings using sorted built-in function."
},
{
"code": null,
"e": 2461,
"s": 2450,
"text": " Live Demo"
},
{
"code": null,
"e": 2676,
"s": 2461,
"text": "# list of strings\nstrings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']\n# sorting the list in ascending order\nsorted_strings = sorted(strings)\n# printing the sorted list\nprint(sorted_strings)"
},
{
"code": null,
"e": 2750,
"s": 2676,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 2817,
"s": 2750,
"text": "['C', 'Django', 'Java', 'Javascript', 'Python', 'React', 'Spring']"
},
{
"code": null,
"e": 2970,
"s": 2817,
"text": "We can also sort the list in descending order using sorted function by passing reverse as True to the function as a second argument. Let's see the code."
},
{
"code": null,
"e": 2981,
"s": 2970,
"text": " Live Demo"
},
{
"code": null,
"e": 3211,
"s": 2981,
"text": "# list of strings\nstrings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']\n# sorting the list in descending order\nsorted_strings = sorted(strings, reverse=True)\n# printing the sorted list\nprint(sorted_strings)"
},
{
"code": null,
"e": 3285,
"s": 3211,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 3352,
"s": 3285,
"text": "['Spring', 'React', 'Python', 'Javascript', 'Java', 'Django', 'C']"
},
{
"code": null,
"e": 3590,
"s": 3352,
"text": "What if we want to sort the list of strings based on the length? Yeah, we can sort based on length using the sort method and sorted function by passing a key as an argument.Let's see how to sort the list of strings based on their length."
},
{
"code": null,
"e": 3601,
"s": 3590,
"text": " Live Demo"
},
{
"code": null,
"e": 3807,
"s": 3601,
"text": "# list of strings\nstrings = ['Python', 'C', 'Java', 'Javascript', 'React', 'Django', 'Spring']\n# sorting the list in ascending order - length\nstrings.sort(key=len)\n# printing the sorted list\nprint(strings)"
},
{
"code": null,
"e": 3881,
"s": 3807,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 3948,
"s": 3881,
"text": "['C', 'Java', 'React', 'Python', 'Django', 'Spring', 'Javascript']"
},
{
"code": null,
"e": 4155,
"s": 3948,
"text": "We can pass any function to the key argument. The sort method will sort the list based on the return value of the function given to the key argument. The same thing will work in the sorted\nfunction as well."
},
{
"code": null,
"e": 4255,
"s": 4155,
"text": "Let's see an example using the sorted function by sorting the list of strings based on their\nvalue."
},
{
"code": null,
"e": 4266,
"s": 4255,
"text": " Live Demo"
},
{
"code": null,
"e": 4476,
"s": 4266,
"text": "# list of strings\nstrings = ['7', '34', '3', '23', '454', '12', '9']\n# sorting the list in ascending order - int value\nsorted_strings = sorted(strings, key=int)\n# printing the sorted list\nprint(sorted_strings)"
},
{
"code": null,
"e": 4550,
"s": 4476,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 4591,
"s": 4550,
"text": "['3', '7', '9', '12', '23', '34', '454']"
},
{
"code": null,
"e": 4812,
"s": 4591,
"text": "We can pass key and reverse arguments at a time to the sort method and sorted function to achieve whatever we want. Try and explore them. If you have any doubts regarding the tutorial, mention them in the comment section"
}
] |
CSS Responsive Table | A responsive table will display a horizontal scroll bar if the screen is too
small to display the full content:
Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though "overflow:scroll" is set).
Make a fancy table
This example demonstrates how to create a fancy table.
Set the position of the table caption
This example demonstrates how to position the table caption.
Set the border to "2px solid green" for table, th and td elements.
<style>
{
: 2px solid green;
}
</style>
<body>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>Peter</td>
<td>Griffin</td>
</tr>
<tr>
<td>Lois</td>
<td>Griffin</td>
</tr>
</table>
</body>
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": 113,
"s": 0,
"text": "A responsive table will display a horizontal scroll bar if the screen is too \nsmall to display the full content:"
},
{
"code": null,
"e": 221,
"s": 113,
"text": "Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:"
},
{
"code": null,
"e": 354,
"s": 221,
"text": "Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though \"overflow:scroll\" is set)."
},
{
"code": null,
"e": 428,
"s": 354,
"text": "Make a fancy table\nThis example demonstrates how to create a fancy table."
},
{
"code": null,
"e": 527,
"s": 428,
"text": "Set the position of the table caption\nThis example demonstrates how to position the table caption."
},
{
"code": null,
"e": 594,
"s": 527,
"text": "Set the border to \"2px solid green\" for table, th and td elements."
},
{
"code": null,
"e": 840,
"s": 594,
"text": "<style>\n {\n : 2px solid green;\n}\n</style>\n\n<body>\n<table>\n <tr>\n <th>Firstname</th>\n <th>Lastname</th>\n </tr>\n <tr>\n <td>Peter</td>\n <td>Griffin</td>\n </tr>\n <tr>\n <td>Lois</td>\n <td>Griffin</td>\n </tr>\n</table>\n</body>\n"
},
{
"code": null,
"e": 859,
"s": 840,
"text": "Start the Exercise"
},
{
"code": null,
"e": 892,
"s": 859,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 934,
"s": 892,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1041,
"s": 934,
"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": 1060,
"s": 1041,
"text": "[email protected]"
}
] |
\raise - Tex Command | \raise - Used to raises the argument by the amount specified in <dimen>
{ \raise <dimen> #1 }
\raise command is used to raises the argument by the amount specified in <dimen>
h\raise 2pt {ighe} r
higher
h\raise 2pt {ighe} r
higher
h\raise 2pt {ighe} r
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8058,
"s": 7986,
"text": "\\raise - Used to raises the argument by the amount specified in <dimen>"
},
{
"code": null,
"e": 8080,
"s": 8058,
"text": "{ \\raise <dimen> #1 }"
},
{
"code": null,
"e": 8161,
"s": 8080,
"text": "\\raise command is used to raises the argument by the amount specified in <dimen>"
},
{
"code": null,
"e": 8194,
"s": 8161,
"text": "\nh\\raise 2pt {ighe} r\n\nhigher\n\n\n"
},
{
"code": null,
"e": 8225,
"s": 8194,
"text": "h\\raise 2pt {ighe} r\n\nhigher\n\n"
},
{
"code": null,
"e": 8246,
"s": 8225,
"text": "h\\raise 2pt {ighe} r"
},
{
"code": null,
"e": 8278,
"s": 8246,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8291,
"s": 8278,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8324,
"s": 8291,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8337,
"s": 8324,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8369,
"s": 8337,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8405,
"s": 8369,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8440,
"s": 8405,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8457,
"s": 8440,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8490,
"s": 8457,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8504,
"s": 8490,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8536,
"s": 8504,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8551,
"s": 8536,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8558,
"s": 8551,
"text": " Print"
},
{
"code": null,
"e": 8569,
"s": 8558,
"text": " Add Notes"
}
] |
Kotlin While Loop | Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as
the counter variable (i) is less than 5:
var i = 0
while (i < 5) {
println(i)
i++
}
Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end.
The do..while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code block
is executed before the condition is tested:
var i = 0
do {
println(i)
i++
}
while (i < 5)
Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
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": 79,
"s": 0,
"text": "Loops can execute a block of code as long as a specified condition is reached."
},
{
"code": null,
"e": 168,
"s": 79,
"text": "Loops are handy because they save time, reduce errors, and they make code more readable."
},
{
"code": null,
"e": 255,
"s": 168,
"text": "The while loop loops through a block of code as long as a specified condition is true:"
},
{
"code": null,
"e": 308,
"s": 255,
"text": "while (condition) {\n // code block to be executed\n}"
},
{
"code": null,
"e": 435,
"s": 308,
"text": "In the example below, the code in the loop will run, over and over again, as long as \nthe counter variable (i) is less than 5:"
},
{
"code": null,
"e": 483,
"s": 435,
"text": "var i = 0\nwhile (i < 5) {\n println(i)\n i++\n} "
},
{
"code": null,
"e": 587,
"s": 483,
"text": "Note: Do not forget to increase the variable used in the condition, otherwise \nthe loop will never end."
},
{
"code": null,
"e": 788,
"s": 587,
"text": "The do..while loop is a variant of the while loop. This loop will \nexecute the code block once, before checking if the condition is true, then it will\nrepeat the loop as long as the condition is true."
},
{
"code": null,
"e": 846,
"s": 788,
"text": "do {\n // code block to be executed\n}\nwhile (condition);\n"
},
{
"code": null,
"e": 1035,
"s": 846,
"text": "The example below uses a do/while loop. The loop will always be \nexecuted at least once, even if the condition is false, because the code block \nis executed before the condition is tested:"
},
{
"code": null,
"e": 1088,
"s": 1035,
"text": "var i = 0\ndo {\n println(i)\n i++\n }\nwhile (i < 5) "
},
{
"code": null,
"e": 1186,
"s": 1088,
"text": "Do not forget to increase the variable used in the condition, otherwise \nthe loop will never end!"
},
{
"code": null,
"e": 1219,
"s": 1186,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1261,
"s": 1219,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1368,
"s": 1261,
"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": 1387,
"s": 1368,
"text": "[email protected]"
}
] |
How to prepare for eLitmus Hiring Potential Test (pH Test) - GeeksforGeeks | 23 Aug, 2021
eLitmus is one of the biggest online hiring platforms and a national level assessment for all those out there looking out for entry level engineering jobs. eLitmus pH test Score card is used by companies to shortlist students for Interviews in Off Campus and On Campus Placements. Candidates can also use this score to apply to all participating (around 210) companies from across India for a period of two years and freshers can get entry-level job(s).
eLitmus Hiring Potential Test (pH Test) –Hiring Potential Test (pH Test). Companies call test-takers for interviews on the basis of pH score and their own criteria. Many top IT companies such as Accenture, Collabera, McAfee and Novell,IBM,CGI, among others have used the eLitmus pH score on numerous occasions to recruit candidates. You need more than 80% in all the sections to get called by companies for Interviews.
Eligibility for pH Test –Though there is no eligibility criteria to take the pH test, but companies hiring through eLitmus may have their own academic criteria. However companies which use the eLitmus pH Test scores may set their own eligibility. Typically companies which hire through eLitmus look for candidates from BE/B.Tech, MCA, ME/Mtech or M.Sc (CS/IT/Electronics). Additionally they may ask for minimum marks or grades. The criteria is published with each job ad. The pH test is majorly used by IT / automobile/infrastructure companies for their fresher hiring in technology.
pH Test exam time table –You can visit elitmus website for login and apply anytime for upcoming pH tests. You need to pay ? 850.00 for pH test. The validity of Score card will be 2 years.
pH Test Syllabus –pH test is offline test. The test is designed to be completed in 2 hours, and often has 3 sections – quantitative, verbal and analytical. Each section currently has 20 questions making it a total of 60 questions and each question carries 10 marks. The maximum marks is 600. The questions in each section are multiple choice objective (MCQ) questions. All required formulae are provided in the question paper.
Number System ( Learn | Practice )
Geometry
Probability ( Learn | Practice )
Algebra ( Learn | Practice )
Permutation and Combination ( Learn | Practice )
Ratio and Proportions ( Learn | Practice )
Speed ( Learn | Practice )
Time and Distance ( Learn | Practice )
Time and Work ( Learn | Practice )
AP GP and HP ( Learn | Practice )
Logical ReasoningSeries : Missing Numbers, Odd One Out ( Learn | Practice )Data Sufficiency ( Learn | Practice )Assumptions and Conclusions, Courses of Action ( Learn | Practice )Puzzles ( Learn | Practice )Syllogism ( Learn | Practice )Cubes(Placement | Cubes)
Series : Missing Numbers, Odd One Out ( Learn | Practice )Data Sufficiency ( Learn | Practice )Assumptions and Conclusions, Courses of Action ( Learn | Practice )Puzzles ( Learn | Practice )Syllogism ( Learn | Practice )Cubes(Placement | Cubes)
Series : Missing Numbers, Odd One Out ( Learn | Practice )
Data Sufficiency ( Learn | Practice )
Assumptions and Conclusions, Courses of Action ( Learn | Practice )
Puzzles ( Learn | Practice )
Syllogism ( Learn | Practice )
Cubes(Placement | Cubes)
Cryptarithmetic
Data Interpretation (Bar charts, Pie charts and Line Graphs) ( Learn | Practice )
Data Sufficiency (Algebra, Arithmetic, Geometry, Logic and Misc) ( Learn | Practice )
Reading Comprehension ( Learn )
Grammatical Errors based Questions ( Learn )
Para Jumbles
Sentence Completion (Subject Verb, Vocabulary, Tenses) ( Learn )
There will be negative marking if a candidate gets more than 25% questions wrong of their total attempt then for every wrong answer half a mark will be deducted.For each section –
Max Score: 200 Marks
Number of Questions: 20 Questions
Each Question Carries: 10 Marks
Time for Sections: no sectional timing
Percentile range –
Quantitative Aptitude: 50 – 80 marks = 75 – 95 percentile
Logical Reasoning: 35 – 90 marks = 75 – 95 percentile
Verbal English: 95 – 160 marks = 65 – 90 percentile
Total: 150 – 240 marks = 75 – 90 percentile
You need to solve for good percentile –
Quantitative Aptitude: solve 5-8 questions
Logical Reasoning: solve 5-7 questions
Verbal English: solve 11-15 questions
These are high weighate important topics in the pH test:
Numeric System
Time, Work, Speed & Distance
Permutation and Combination(P&C)
Probability (problem)
Elementary Geometry
Data Interpretation-Data in tabular form
Questions of Arrangement
Cryptic Multiplication -Coding/Decoding
Reading Comprehension
Paragraph Formation/ Para-jumbles
Fill in the appropriate words
English Grammar
You need more than 80% in all the sections to get called by companies for Interviews. Since pH test is very tough, so you need to prepare very well.
vivek5252
Akanksha_Rai
Interview Tips
interview-preparation
placement preparation
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | Views
Mutex vs Semaphore
Time Complexity and Space Complexity
SQL Interview Questions
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
SQL | GROUP BY
Recursive Practice Problems with Solutions
Little and Big Endian Mystery | [
{
"code": null,
"e": 24762,
"s": 24734,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 25216,
"s": 24762,
"text": "eLitmus is one of the biggest online hiring platforms and a national level assessment for all those out there looking out for entry level engineering jobs. eLitmus pH test Score card is used by companies to shortlist students for Interviews in Off Campus and On Campus Placements. Candidates can also use this score to apply to all participating (around 210) companies from across India for a period of two years and freshers can get entry-level job(s)."
},
{
"code": null,
"e": 25635,
"s": 25216,
"text": "eLitmus Hiring Potential Test (pH Test) –Hiring Potential Test (pH Test). Companies call test-takers for interviews on the basis of pH score and their own criteria. Many top IT companies such as Accenture, Collabera, McAfee and Novell,IBM,CGI, among others have used the eLitmus pH score on numerous occasions to recruit candidates. You need more than 80% in all the sections to get called by companies for Interviews."
},
{
"code": null,
"e": 26219,
"s": 25635,
"text": "Eligibility for pH Test –Though there is no eligibility criteria to take the pH test, but companies hiring through eLitmus may have their own academic criteria. However companies which use the eLitmus pH Test scores may set their own eligibility. Typically companies which hire through eLitmus look for candidates from BE/B.Tech, MCA, ME/Mtech or M.Sc (CS/IT/Electronics). Additionally they may ask for minimum marks or grades. The criteria is published with each job ad. The pH test is majorly used by IT / automobile/infrastructure companies for their fresher hiring in technology."
},
{
"code": null,
"e": 26407,
"s": 26219,
"text": "pH Test exam time table –You can visit elitmus website for login and apply anytime for upcoming pH tests. You need to pay ? 850.00 for pH test. The validity of Score card will be 2 years."
},
{
"code": null,
"e": 26834,
"s": 26407,
"text": "pH Test Syllabus –pH test is offline test. The test is designed to be completed in 2 hours, and often has 3 sections – quantitative, verbal and analytical. Each section currently has 20 questions making it a total of 60 questions and each question carries 10 marks. The maximum marks is 600. The questions in each section are multiple choice objective (MCQ) questions. All required formulae are provided in the question paper."
},
{
"code": null,
"e": 26869,
"s": 26834,
"text": "Number System ( Learn | Practice )"
},
{
"code": null,
"e": 26878,
"s": 26869,
"text": "Geometry"
},
{
"code": null,
"e": 26911,
"s": 26878,
"text": "Probability ( Learn | Practice )"
},
{
"code": null,
"e": 26940,
"s": 26911,
"text": "Algebra ( Learn | Practice )"
},
{
"code": null,
"e": 26989,
"s": 26940,
"text": "Permutation and Combination ( Learn | Practice )"
},
{
"code": null,
"e": 27032,
"s": 26989,
"text": "Ratio and Proportions ( Learn | Practice )"
},
{
"code": null,
"e": 27059,
"s": 27032,
"text": "Speed ( Learn | Practice )"
},
{
"code": null,
"e": 27098,
"s": 27059,
"text": "Time and Distance ( Learn | Practice )"
},
{
"code": null,
"e": 27133,
"s": 27098,
"text": "Time and Work ( Learn | Practice )"
},
{
"code": null,
"e": 27167,
"s": 27133,
"text": "AP GP and HP ( Learn | Practice )"
},
{
"code": null,
"e": 27429,
"s": 27167,
"text": "Logical ReasoningSeries : Missing Numbers, Odd One Out ( Learn | Practice )Data Sufficiency ( Learn | Practice )Assumptions and Conclusions, Courses of Action ( Learn | Practice )Puzzles ( Learn | Practice )Syllogism ( Learn | Practice )Cubes(Placement | Cubes)"
},
{
"code": null,
"e": 27674,
"s": 27429,
"text": "Series : Missing Numbers, Odd One Out ( Learn | Practice )Data Sufficiency ( Learn | Practice )Assumptions and Conclusions, Courses of Action ( Learn | Practice )Puzzles ( Learn | Practice )Syllogism ( Learn | Practice )Cubes(Placement | Cubes)"
},
{
"code": null,
"e": 27733,
"s": 27674,
"text": "Series : Missing Numbers, Odd One Out ( Learn | Practice )"
},
{
"code": null,
"e": 27771,
"s": 27733,
"text": "Data Sufficiency ( Learn | Practice )"
},
{
"code": null,
"e": 27839,
"s": 27771,
"text": "Assumptions and Conclusions, Courses of Action ( Learn | Practice )"
},
{
"code": null,
"e": 27868,
"s": 27839,
"text": "Puzzles ( Learn | Practice )"
},
{
"code": null,
"e": 27899,
"s": 27868,
"text": "Syllogism ( Learn | Practice )"
},
{
"code": null,
"e": 27924,
"s": 27899,
"text": "Cubes(Placement | Cubes)"
},
{
"code": null,
"e": 27940,
"s": 27924,
"text": "Cryptarithmetic"
},
{
"code": null,
"e": 28022,
"s": 27940,
"text": "Data Interpretation (Bar charts, Pie charts and Line Graphs) ( Learn | Practice )"
},
{
"code": null,
"e": 28108,
"s": 28022,
"text": "Data Sufficiency (Algebra, Arithmetic, Geometry, Logic and Misc) ( Learn | Practice )"
},
{
"code": null,
"e": 28140,
"s": 28108,
"text": "Reading Comprehension ( Learn )"
},
{
"code": null,
"e": 28185,
"s": 28140,
"text": "Grammatical Errors based Questions ( Learn )"
},
{
"code": null,
"e": 28198,
"s": 28185,
"text": "Para Jumbles"
},
{
"code": null,
"e": 28263,
"s": 28198,
"text": "Sentence Completion (Subject Verb, Vocabulary, Tenses) ( Learn )"
},
{
"code": null,
"e": 28443,
"s": 28263,
"text": "There will be negative marking if a candidate gets more than 25% questions wrong of their total attempt then for every wrong answer half a mark will be deducted.For each section –"
},
{
"code": null,
"e": 28570,
"s": 28443,
"text": "Max Score: 200 Marks\nNumber of Questions: 20 Questions\nEach Question Carries: 10 Marks\nTime for Sections: no sectional timing "
},
{
"code": null,
"e": 28589,
"s": 28570,
"text": "Percentile range –"
},
{
"code": null,
"e": 28798,
"s": 28589,
"text": "Quantitative Aptitude: 50 – 80 marks = 75 – 95 percentile\nLogical Reasoning: 35 – 90 marks = 75 – 95 percentile\nVerbal English: 95 – 160 marks = 65 – 90 percentile\nTotal: 150 – 240 marks = 75 – 90 percentile "
},
{
"code": null,
"e": 28838,
"s": 28798,
"text": "You need to solve for good percentile –"
},
{
"code": null,
"e": 28959,
"s": 28838,
"text": "Quantitative Aptitude: solve 5-8 questions\nLogical Reasoning: solve 5-7 questions\nVerbal English: solve 11-15 questions "
},
{
"code": null,
"e": 29016,
"s": 28959,
"text": "These are high weighate important topics in the pH test:"
},
{
"code": null,
"e": 29031,
"s": 29016,
"text": "Numeric System"
},
{
"code": null,
"e": 29060,
"s": 29031,
"text": "Time, Work, Speed & Distance"
},
{
"code": null,
"e": 29093,
"s": 29060,
"text": "Permutation and Combination(P&C)"
},
{
"code": null,
"e": 29115,
"s": 29093,
"text": "Probability (problem)"
},
{
"code": null,
"e": 29135,
"s": 29115,
"text": "Elementary Geometry"
},
{
"code": null,
"e": 29176,
"s": 29135,
"text": "Data Interpretation-Data in tabular form"
},
{
"code": null,
"e": 29201,
"s": 29176,
"text": "Questions of Arrangement"
},
{
"code": null,
"e": 29241,
"s": 29201,
"text": "Cryptic Multiplication -Coding/Decoding"
},
{
"code": null,
"e": 29263,
"s": 29241,
"text": "Reading Comprehension"
},
{
"code": null,
"e": 29297,
"s": 29263,
"text": "Paragraph Formation/ Para-jumbles"
},
{
"code": null,
"e": 29327,
"s": 29297,
"text": "Fill in the appropriate words"
},
{
"code": null,
"e": 29343,
"s": 29327,
"text": "English Grammar"
},
{
"code": null,
"e": 29492,
"s": 29343,
"text": "You need more than 80% in all the sections to get called by companies for Interviews. Since pH test is very tough, so you need to prepare very well."
},
{
"code": null,
"e": 29502,
"s": 29492,
"text": "vivek5252"
},
{
"code": null,
"e": 29515,
"s": 29502,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29530,
"s": 29515,
"text": "Interview Tips"
},
{
"code": null,
"e": 29552,
"s": 29530,
"text": "interview-preparation"
},
{
"code": null,
"e": 29574,
"s": 29552,
"text": "placement preparation"
},
{
"code": null,
"e": 29583,
"s": 29574,
"text": "Articles"
},
{
"code": null,
"e": 29681,
"s": 29583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29690,
"s": 29681,
"text": "Comments"
},
{
"code": null,
"e": 29703,
"s": 29690,
"text": "Old Comments"
},
{
"code": null,
"e": 29715,
"s": 29703,
"text": "SQL | Views"
},
{
"code": null,
"e": 29734,
"s": 29715,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 29771,
"s": 29734,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 29795,
"s": 29771,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 29858,
"s": 29795,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
},
{
"code": null,
"e": 29873,
"s": 29858,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 29916,
"s": 29873,
"text": "Recursive Practice Problems with Solutions"
}
] |
Behind The Models: Dirichlet — How Does It Add To 1? | by Guido Vivaldi | Towards Data Science | In a previous article I presented the Dirichlet distribution as a combination of many Beta-distributed variables which add to 1.0 — this can be useful for applications where you need a “random” classifier, which is the subject of an article still in the works. Sebastian Bruijns asked the obvious question I skirted around in the original article:
Very nice and understandable article. I just don’t understand the connection between Dirichlet and Beta, you wrote that the variates of the Dirichlet follow a Beta dist., but how does that work, how is it guaranteed to add up to one?
Here’s the nitty-gritty:
This section is mostly review of the previous article — skip over it if you’re familiar with those details.
The Dirichlet distribution is a multivariate generalization of the Beta. The input is a vector of 2 or more parameters, and the output is a distribution in which the sum of the variables always equals 1.0 and each individual variable is Beta-distributed. The “Stick Breaking” in the image below will unite these two ideas.
The intuitive way of generating the Dirichlet after reading the above is to generate random Betas and sum them up, but that clearly won’t work. In the simulation below we show that the sum of 5 Beta(3, 7)’s is something normal-looking (it’s not exactly normal, in part because the Beta is bound at [0, 1], so the sum is bound at [0, 5]).
import numpy as npfrom matplotlib import pyplot as pltn = 100000z = [np.random.beta(3,7,n) for i in range(5)]for i in range(5): plt.hist(z[i], histtype = u’step’, bins = 300) plt.show()z_sum = [sum([z[x][i] for x in range(5)]) for i in range(n)]plt.hist(z_sum, histtype = u’step’, bins = 300)plt.show()
The PDF for the Dirichlet distribution is below. Here θ is the multinomial category, and α is the vector or β parameters. The Betas are always Beta(α, 1) — there is no second parameter. Note that the resulting Beta-distributed variates will not follow a Beta(α, 1) — the β paramater is a function of the α vector. That may start to give some intuition about why the Dirichlet adds to 1 — as the alphas grow bigger. The resulting Beta-distributed variates follow Beta(α, (K-1)*α) where K is the number of values in the α vector. Have a go at it yourself:
x = np.random.dirichlet((1, 1, 1), 100000)for n in range(3): a, b, l, s = beta.fit(x[:,n], floc = 0, fscale = 1) print(a) print(b)
The form of the PDF for the Dirichlet gives a first glimpse at how it ensures that the Betas add up to 1.0. Here θ is the multinomial category, and α is the vector we’ve been working with.
A practical implementation uses the Gamma distribution (recall that relationship between the Beta/Gamma: B(α,β)=Γ(α)Γ(β) / Γ(α+β)) and is easy to intuit. First draw an independent Gamma(α, 1) for each Dirichlet variate, then average them out to 1.0 to produce Dirichlet-distributed variables.
a = 3n_ = 5y = [np.random.gamma(a, 1, 100000) for i in range(n_)]y_sum = [sum([y[x][i] for x in range(n_)]) for i in range(100000)]x = [[y[x][i] / y_sum[i] for x in range(n_)] for i in range(100000)]x = [[x[i][n] for i in range(100000)] for n in range(n_)]for i in range(n_): plt.hist(x[i], histtype = u'step', bins = 300, normed = True)a, b, l, s = beta.fit(x[0], floc = 0, fscale = 1)
As an aside, this also affords a great opportunity to use some robust list-comprehension: I’ve been salivating over this article for about a month.
In the previous article we arrived at a Dirichlet process, which is slightly different than Dirichlet distribution. A Dirichlet distribution can be expanded to have an infinite number of variates via a Dirichlet process.This is another fact that I waved my hands about that might have offended your intuitions.
The way to think about a Dirichlet process is that each pull from it is itself Dirichlet-distributed (not Beta distributed, though of course draws from a Dirichlet distribution are Beta distributed). So unlike the Dirichlet distribution above where each variate
The process is possible because we can iteratively generate a new variate, so we don’t actually generate infinite variates, but we create a framework where we could always create more variates if needed. In this case we can’t use the Gamma trick from above because we can’t divide by the total sum, but we can be assured that if we went onto infinity we’d never end up with variates adding up to more than 1.The formula is reproduced below — p(i) is the Dirichlet variate — V(i) is an intermediary variable.
Below we generate the first 3 variates in a Dirichlet process:
k = 3z = [np.random.beta(1,1,100000) for i in range(k)]p = [[np.prod([1 - z[x][n] for x in range(i)]) * z[i][n] for i in range(k)] for n in range(100000)]p = [[p[i][x] for i in range(100000)] for x in range(k)]for i in range(k): plt.hist(p[i], histtype = u'step', bins = 300, normed = True) a, b, l, s = beta.fit(p[i], floc = 0, fscale = 1) print(a) print(b)plt.show()p_sum = [sum([p[x][i] for x in range(k)]) for i in range(100000)]plt.hist(p_sum, histtype = u'step', bins = 300, normed = True)plt.show()
The first Beta draw is in blue in the left graph: Beta(1,1). In the second draw in orange, we use Beta(1,1), but then multiply it by (1-V(1)), so the final variable is Beta-looking. The green line is the third draw — Beta continues to increase as we shift more mass into the left hand tail. This makes intuitive sense — using α = 1 we’re allowing relatively high values to come out early in the draws, so the remaining draws get forced into lower numbers. The right graph tells us that with only three draws we’re already hugging pretty close to 1.0, so remaining draws are going to have very small margins to fit into.
If we use α = 0.5 above we force the early draws to stick to lower values, and so have more freedom for later
Conclusion
Like the past article, this article was theory heavy. Hopefully it helped fill in some gaps that I glossed over in the previous article. In future articles I will use these models in application heavy examples. | [
{
"code": null,
"e": 520,
"s": 172,
"text": "In a previous article I presented the Dirichlet distribution as a combination of many Beta-distributed variables which add to 1.0 — this can be useful for applications where you need a “random” classifier, which is the subject of an article still in the works. Sebastian Bruijns asked the obvious question I skirted around in the original article:"
},
{
"code": null,
"e": 754,
"s": 520,
"text": "Very nice and understandable article. I just don’t understand the connection between Dirichlet and Beta, you wrote that the variates of the Dirichlet follow a Beta dist., but how does that work, how is it guaranteed to add up to one?"
},
{
"code": null,
"e": 779,
"s": 754,
"text": "Here’s the nitty-gritty:"
},
{
"code": null,
"e": 887,
"s": 779,
"text": "This section is mostly review of the previous article — skip over it if you’re familiar with those details."
},
{
"code": null,
"e": 1210,
"s": 887,
"text": "The Dirichlet distribution is a multivariate generalization of the Beta. The input is a vector of 2 or more parameters, and the output is a distribution in which the sum of the variables always equals 1.0 and each individual variable is Beta-distributed. The “Stick Breaking” in the image below will unite these two ideas."
},
{
"code": null,
"e": 1548,
"s": 1210,
"text": "The intuitive way of generating the Dirichlet after reading the above is to generate random Betas and sum them up, but that clearly won’t work. In the simulation below we show that the sum of 5 Beta(3, 7)’s is something normal-looking (it’s not exactly normal, in part because the Beta is bound at [0, 1], so the sum is bound at [0, 5])."
},
{
"code": null,
"e": 1851,
"s": 1548,
"text": "import numpy as npfrom matplotlib import pyplot as pltn = 100000z = [np.random.beta(3,7,n) for i in range(5)]for i in range(5): plt.hist(z[i], histtype = u’step’, bins = 300) plt.show()z_sum = [sum([z[x][i] for x in range(5)]) for i in range(n)]plt.hist(z_sum, histtype = u’step’, bins = 300)plt.show()"
},
{
"code": null,
"e": 2405,
"s": 1851,
"text": "The PDF for the Dirichlet distribution is below. Here θ is the multinomial category, and α is the vector or β parameters. The Betas are always Beta(α, 1) — there is no second parameter. Note that the resulting Beta-distributed variates will not follow a Beta(α, 1) — the β paramater is a function of the α vector. That may start to give some intuition about why the Dirichlet adds to 1 — as the alphas grow bigger. The resulting Beta-distributed variates follow Beta(α, (K-1)*α) where K is the number of values in the α vector. Have a go at it yourself:"
},
{
"code": null,
"e": 2545,
"s": 2405,
"text": "x = np.random.dirichlet((1, 1, 1), 100000)for n in range(3): a, b, l, s = beta.fit(x[:,n], floc = 0, fscale = 1) print(a) print(b)"
},
{
"code": null,
"e": 2734,
"s": 2545,
"text": "The form of the PDF for the Dirichlet gives a first glimpse at how it ensures that the Betas add up to 1.0. Here θ is the multinomial category, and α is the vector we’ve been working with."
},
{
"code": null,
"e": 3027,
"s": 2734,
"text": "A practical implementation uses the Gamma distribution (recall that relationship between the Beta/Gamma: B(α,β)=Γ(α)Γ(β) / Γ(α+β)) and is easy to intuit. First draw an independent Gamma(α, 1) for each Dirichlet variate, then average them out to 1.0 to produce Dirichlet-distributed variables."
},
{
"code": null,
"e": 3417,
"s": 3027,
"text": "a = 3n_ = 5y = [np.random.gamma(a, 1, 100000) for i in range(n_)]y_sum = [sum([y[x][i] for x in range(n_)]) for i in range(100000)]x = [[y[x][i] / y_sum[i] for x in range(n_)] for i in range(100000)]x = [[x[i][n] for i in range(100000)] for n in range(n_)]for i in range(n_): plt.hist(x[i], histtype = u'step', bins = 300, normed = True)a, b, l, s = beta.fit(x[0], floc = 0, fscale = 1)"
},
{
"code": null,
"e": 3565,
"s": 3417,
"text": "As an aside, this also affords a great opportunity to use some robust list-comprehension: I’ve been salivating over this article for about a month."
},
{
"code": null,
"e": 3876,
"s": 3565,
"text": "In the previous article we arrived at a Dirichlet process, which is slightly different than Dirichlet distribution. A Dirichlet distribution can be expanded to have an infinite number of variates via a Dirichlet process.This is another fact that I waved my hands about that might have offended your intuitions."
},
{
"code": null,
"e": 4138,
"s": 3876,
"text": "The way to think about a Dirichlet process is that each pull from it is itself Dirichlet-distributed (not Beta distributed, though of course draws from a Dirichlet distribution are Beta distributed). So unlike the Dirichlet distribution above where each variate"
},
{
"code": null,
"e": 4646,
"s": 4138,
"text": "The process is possible because we can iteratively generate a new variate, so we don’t actually generate infinite variates, but we create a framework where we could always create more variates if needed. In this case we can’t use the Gamma trick from above because we can’t divide by the total sum, but we can be assured that if we went onto infinity we’d never end up with variates adding up to more than 1.The formula is reproduced below — p(i) is the Dirichlet variate — V(i) is an intermediary variable."
},
{
"code": null,
"e": 4709,
"s": 4646,
"text": "Below we generate the first 3 variates in a Dirichlet process:"
},
{
"code": null,
"e": 5227,
"s": 4709,
"text": "k = 3z = [np.random.beta(1,1,100000) for i in range(k)]p = [[np.prod([1 - z[x][n] for x in range(i)]) * z[i][n] for i in range(k)] for n in range(100000)]p = [[p[i][x] for i in range(100000)] for x in range(k)]for i in range(k): plt.hist(p[i], histtype = u'step', bins = 300, normed = True) a, b, l, s = beta.fit(p[i], floc = 0, fscale = 1) print(a) print(b)plt.show()p_sum = [sum([p[x][i] for x in range(k)]) for i in range(100000)]plt.hist(p_sum, histtype = u'step', bins = 300, normed = True)plt.show()"
},
{
"code": null,
"e": 5847,
"s": 5227,
"text": "The first Beta draw is in blue in the left graph: Beta(1,1). In the second draw in orange, we use Beta(1,1), but then multiply it by (1-V(1)), so the final variable is Beta-looking. The green line is the third draw — Beta continues to increase as we shift more mass into the left hand tail. This makes intuitive sense — using α = 1 we’re allowing relatively high values to come out early in the draws, so the remaining draws get forced into lower numbers. The right graph tells us that with only three draws we’re already hugging pretty close to 1.0, so remaining draws are going to have very small margins to fit into."
},
{
"code": null,
"e": 5957,
"s": 5847,
"text": "If we use α = 0.5 above we force the early draws to stick to lower values, and so have more freedom for later"
},
{
"code": null,
"e": 5968,
"s": 5957,
"text": "Conclusion"
}
] |
Go - Quick Guide | Go is a general-purpose language designed with systems programming in mind. It was initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection, and supports concurrent programming.
Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries. The Go programming language was announced in November 2009 and is used in some of the Google's production systems.
The most important features of Go programming are listed below −
Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int)
Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int)
Compilation time is fast.
Compilation time is fast.
Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement.
Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement.
Go programs are simple, concise, and safe.
Go programs are simple, concise, and safe.
Support for Interfaces and Type embedding.
Support for Interfaces and Type embedding.
Production of statically linked native binaries without external dependencies.
Production of statically linked native binaries without external dependencies.
To keep the language simple and concise, the following features commonly available in other similar languages are omitted in Go −
Support for type inheritance
Support for type inheritance
Support for method or operator overloading
Support for method or operator overloading
Support for circular dependencies among packages
Support for circular dependencies among packages
Support for pointer arithmetic
Support for pointer arithmetic
Support for assertions
Support for assertions
Support for generic programming
Support for generic programming
A Go program can vary in length from 3 lines to millions of lines and it should be written into one or more text files with the extension ".go". For example, hello.go.
You can use "vi", "vim" or any other text editor to write your Go program into a file.
If you are still willing to set up your environment for Go programming language, you need the following two software available on your computer −
A text editor
Go compiler
You will require a text editor to type your programs. Examples of text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example, Notepad is used on Windows, and vim or vi is used on Windows as well as Linux or UNIX.
The files you create with the text editor are called source files. They contain program source code. The source files for Go programs are typically named with the extension ".go".
Before starting your programming, make sure you have a text editor in place and you have enough experience to write a computer program, save it in a file, compile it, and finally execute it.
The source code written in source file is the human readable source for your program. It needs to be compiled and turned into machine language so that your CPU can actually execute the program as per the instructions given. The Go programming language compiler compiles the source code into its final executable program.
Go distribution comes as a binary installable for FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems with 32-bit (386) and 64-bit (amd64) x86 processor architectures.
The following section explains how to install Go binary distribution on various OS.
Download the latest version of Go installable archive file from Go Downloads. The following version is used in this tutorial: go1.4.windows-amd64.msi.
It is copied it into C:\>go folder.
Extract the download archive into the folder /usr/local, creating a Go tree in /usr/local/go. For example −
tar -C /usr/local -xzf go1.4.linux-amd64.tar.gz
Add /usr/local/go/bin to the PATH environment variable.
Use the MSI file and follow the prompts to install the Go tools. By default, the installer uses the Go distribution in c:\Go. The installer should set the c:\Go\bin directory in Window's PATH environment variable. Restart any open command prompts for the change to take effect.
Create a go file named test.go in C:\>Go_WorkSpace.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Now run test.go to see the result −
C:\Go_WorkSpace>go run test.go
Hello, World!
Before we study the basic building blocks of Go programming language, let us first discuss the bare minimum structure of Go programs so that we can take it as a reference in subsequent chapters.
A Go program basically consists of the following parts −
Package Declaration
Import Packages
Functions
Variables
Statements and Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
package main
import "fmt"
func main() {
/* This is my first sample program. */
fmt.Println("Hello, World!")
}
Let us take a look at the various parts of the above program −
The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it.
The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it.
The next line import "fmt" is a preprocessor command which tells the Go compiler to include the files lying in the package fmt.
The next line import "fmt" is a preprocessor command which tells the Go compiler to include the files lying in the package fmt.
The next line func main() is the main function where the program execution begins.
The next line func main() is the main function where the program execution begins.
The next line /*...*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments.
The next line /*...*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments.
The next line fmt.Println(...) is another function available in Go which causes the message "Hello, World!" to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen.
The next line fmt.Println(...) is another function available in Go which causes the message "Hello, World!" to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen.
Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package.
Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package.
Let us discuss how to save the source code in a file, compile it, and finally execute the program. Please follow the steps given below −
Open a text editor and add the above-mentioned code.
Open a text editor and add the above-mentioned code.
Save the file as hello.go
Save the file as hello.go
Open the command prompt.
Open the command prompt.
Go to the directory where you saved the file.
Go to the directory where you saved the file.
Type go run hello.go and press enter to run your code.
Type go run hello.go and press enter to run your code.
If there are no errors in your code, then you will see "Hello World!" printed on the screen.
If there are no errors in your code, then you will see "Hello World!" printed on the screen.
$ go run hello.go
Hello, World!
Make sure the Go compiler is in your path and that you are running it in the directory containing the source file hello.go.
We discussed the basic structure of a Go program in the previous chapter. Now it will be easy to understand the other basic building blocks of the Go programming language.
A Go program consists of various tokens. A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −
fmt.Println("Hello, World!")
The individual tokens are −
fmt
.
Println
(
"Hello, World!"
)
In a Go program, the line separator key is a statement terminator. That is, individual statements don't need a special separator like “;” in C. The Go compiler internally places “;” as the statement terminator to indicate the end of one logical entity.
For example, take a look at the following statements −
fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")
Comments are like helping texts in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below −
/* my first program in Go */
You cannot have comments within comments and they do not occur within a string or character literals.
A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
identifier = letter { letter | unicode_digit }.
Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers −
mahesh kumar abc move_name a_123
myname50 _temp j a23b9 retVal
The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names.
Whitespace is the term used in Go to describe blanks, tabs, newline characters, and comments. A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it.
Whitespaces separate one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
var age int;
There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges; // get the total fruit
No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
The types in Go can be classified as follows −
Boolean types
They are boolean types and consists of the two predefined constants: (a) true (b) false
Numeric types
They are again arithmetic types and they represents a) integer types or b) floating point values throughout the program.
String types
A string type represents the set of string values. Its value is a sequence of bytes. Strings are immutable types that is once created, it is not possible to change the contents of a string. The predeclared string type is string.
Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types f) Slice types g) Interface types h) Map types i) Channel Types
Array types and structure types are collectively referred to as aggregate types. The type of a function specifies the set of all functions with the same parameter and result types. We will discuss the basic types in the following section, whereas other types will be covered in the upcoming chapters.
The predefined architecture-independent integer types are −
uint8
Unsigned 8-bit integers (0 to 255)
uint16
Unsigned 16-bit integers (0 to 65535)
uint32
Unsigned 32-bit integers (0 to 4294967295)
uint64
Unsigned 64-bit integers (0 to 18446744073709551615)
int8
Signed 8-bit integers (-128 to 127)
int16
Signed 16-bit integers (-32768 to 32767)
int32
Signed 32-bit integers (-2147483648 to 2147483647)
int64
Signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
The predefined architecture-independent float types are −
float32
IEEE-754 32-bit floating-point numbers
float64
IEEE-754 64-bit floating-point numbers
complex64
Complex numbers with float32 real and imaginary parts
complex128
Complex numbers with float64 real and imaginary parts
The value of an n-bit integer is n bits and is represented using two's complement arithmetic operations.
There is also a set of numeric types with implementation-specific sizes −
byte
same as uint8
rune
same as int32
uint
32 or 64 bits
int
same size as uint
uintptr
an unsigned integer to store the uninterpreted bits of a pointer value
A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −
byte
Typically a single octet(one byte). This is an byte type.
int
The most natural size of integer for the machine.
float32
A single-precision floating point value.
Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types.
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −
var variable_list optional_data_type;
Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
var i, j, k int;
var c, ch byte;
var f, salary float32;
d = 42;
The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows −
variable_name = value;
For example,
d = 3, f = 5; // declaration of d and f. Here d and f are int
For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type.
A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program.
Try the following example, where the variable has been declared with a type and initialized inside the main function −
package main
import "fmt"
func main() {
var x float64
x = 20.0
fmt.Println(x)
fmt.Printf("x is of type %T\n", x)
}
When the above code is compiled and executed, it produces the following result −
20
x is of type float64
A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement.
Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator.
package main
import "fmt"
func main() {
var x float64 = 20.0
y := 42
fmt.Println(x)
fmt.Println(y)
fmt.Printf("x is of type %T\n", x)
fmt.Printf("y is of type %T\n", y)
}
When the above code is compiled and executed, it produces the following result −
20
42
x is of type float64
y is of type int
Variables of different types can be declared in one go using type inference.
package main
import "fmt"
func main() {
var a, b, c = 3, 4, "foo"
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Printf("a is of type %T\n", a)
fmt.Printf("b is of type %T\n", b)
fmt.Printf("c is of type %T\n", c)
}
When the above code is compiled and executed, it produces the following result −
3
4
foo
a is of type int
b is of type int
c is of type string
There are two kinds of expressions in Go −
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side.
The following statement is valid −
x = 20.0
The following statement is not valid. It would generate compile-time error −
10 = 20
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after their definition.
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various type of Integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
When certain characters are preceded by a backslash, they will have a special meaning in Go. These are known as Escape Sequence codes which are used to represent newline (\n), tab (\t), backspace, etc. Here, you have a list of some of such escape sequence codes −
The following example shows how to use \t in a program −
package main
import "fmt"
func main() {
fmt.Printf("Hello\tWorld!")
}
When the above code is compiled and executed, it produces the following result −
Hello World!
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
You can use const prefix to declare constants with a specific type as follows −
const variable type = value;
The following example shows how to use the const keyword −
package main
import "fmt"
func main() {
const LENGTH int = 10
const WIDTH int = 5
var area int
area = LENGTH * WIDTH
fmt.Printf("value of area : %d", area)
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Miscellaneous Operators
This tutorial explains arithmetic, relational, logical, bitwise, assignment, and other operators one by one.
Following table shows all the arithmetic operators supported by Go language. Assume variable A holds 10 and variable B holds 20 then −
Show Examples
The following table lists all the relational operators supported by Go language. Assume variable A holds 10 and variable B holds 20, then −
Show Examples
The following table lists all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then −
Show Examples
The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then −
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
Assume A = 60; and B = 13. In binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Show Examples
The following table lists all the assignment operators supported by Go language −
Show Examples
There are a few other important operators supported by Go Language including sizeof and ?:.
Show Examples
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
Go programming language provides the following types of decision making statements. Click the following links to check their detail.
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
You can use one if or else if statement inside another if or else if statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
A select statement is similar to switch statement with difference that case statements refers to channel communications.
There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
Go programming language provides the following types of loop to handle looping requirements.
It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
These are one or multiple loops inside any for loop.
Loop control statements change an execution from its normal sequence. When an execution leaves its scope, all automatic objects that were created in that scope are destroyed.
Go supports the following control statements −
It terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.
It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
It transfers control to the labeled statement.
A loop becomes an infinite loop if its condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or by passing true to it.
package main
import "fmt"
func main() {
for true {
fmt.Printf("This loop will run forever.\n");
}
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
Note − You can terminate an infinite loop by pressing Ctrl + C keys.
A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(). You can divide your code into separate functions. How you divide your code among different functions is up to you, but logically, the division should be such that each function performs a specific task.
A function declaration tells the compiler about a function name, return type, and parameters. A function definition provides the actual body of the function.
The Go standard library provides numerous built-in functions that your program can call. For example, the function len() takes arguments of various types and returns the length of the type. If a string is passed to it, the function returns the length of the string in bytes. If an array is passed to it, the function returns the length of the array.
Functions are also known as method, sub-routine, or procedure.
The general form of a function definition in Go programming language is as follows −
func function_name( [parameter list] ) [return_types]
{
body of the function
}
A function definition in Go programming language consists of a function header and a function body. Here are all the parts of a function −
Func − It starts the declaration of a function.
Func − It starts the declaration of a function.
Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature.
Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required.
Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required.
Function Body − It contains a collection of statements that define what the function does.
Function Body − It contains a collection of statements that define what the function does.
The following source code shows a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two −
/* function returning the max between two numbers */
func max(num1, num2 int) int {
/* local variable declaration */
result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
While creating a Go function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with its function name. If the function returns a value, then you can store the returned value. For example −
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int = 200
var ret int
/* calling a function to get max value */
ret = max(a, b)
fmt.Printf( "Max value is : %d\n", ret )
}
/* function returning the max between two numbers */
func max(num1, num2 int) int {
/* local variable declaration */
var result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
We have kept the max() function along with the main() function and compiled the source code. While running the final executable, it would produce the following result −
Max value is : 200
A Go function can return multiple values. For example −
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("Mahesh", "Kumar")
fmt.Println(a, b)
}
When the above code is compiled and executed, it produces the following result −
Kumar Mahesh
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function −
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
By default, Go uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. The above program, while calling the max() function, used the same method.
A function can be used in the following ways:
Functions can be created on the fly and can be used as values.
Functions closures are anonymous functions and can be used in dynamic programming.
Methods are special functions with a receiver.
A scope in any programming is a region of the program where a defined variable can exist and beyond that the variable cannot be accessed. There are three places where variables can be declared in Go programming language −
Inside a function or a block (local variables)
Inside a function or a block (local variables)
Outside of all functions (global variables)
Outside of all functions (global variables)
In the definition of function parameters (formal parameters)
In the definition of function parameters (formal parameters)
Let us find out what are local and global variables and what are formal parameters.
Variables that are declared inside a function or a block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example uses local variables. Here all the variables a, b, and c are local to the main() function.
package main
import "fmt"
func main() {
/* local variable declaration */
var a, b, c int
/* actual initialization */
a = 10
b = 20
c = a + b
fmt.Printf ("value of a = %d, b = %d and c = %d\n", a, b, c)
}
When the above code is compiled and executed, it produces the following result −
value of a = 10, b = 20 and c = 30
Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout the program after its declaration. The following example uses both global and local variables −
package main
import "fmt"
/* global variable declaration */
var g int
func main() {
/* local variable declaration */
var a, b int
/* actual initialization */
a = 10
b = 20
g = a + b
fmt.Printf("value of a = %d, b = %d and g = %d\n", a, b, g)
}
When the above code is compiled and executed, it produces the following result −
value of a = 10, b = 20 and g = 30
A program can have the same name for local and global variables but the value of the local variable inside a function takes preference. For example −
package main
import "fmt"
/* global variable declaration */
var g int = 20
func main() {
/* local variable declaration */
var g int = 10
fmt.Printf ("value of g = %d\n", g)
}
When the above code is compiled and executed, it produces the following result −
value of g = 10
Formal parameters are treated as local variables with-in that function and they take preference over the global variables. For example −
package main
import "fmt"
/* global variable declaration */
var a int = 20;
func main() {
/* local variable declaration in main function */
var a int = 10
var b int = 20
var c int = 0
fmt.Printf("value of a in main() = %d\n", a);
c = sum( a, b);
fmt.Printf("value of c in main() = %d\n", c);
}
/* function to add two integers */
func sum(a, b int) int {
fmt.Printf("value of a in sum() = %d\n", a);
fmt.Printf("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Local and global variables are initialized to their default value, which is 0; while pointers are initialized to nil.
Strings, which are widely used in Go programming, are a readonly slice of bytes. In the Go programming language, strings are slices. The Go platform provides various libraries to manipulate strings.
unicode
regexp
strings
The most direct way to create a string is to write −
var greeting = "Hello world!"
Whenever it encounters a string literal in your code, the compiler creates a string object with its value in this case, "Hello world!'.
A string literal holds a valid UTF-8 sequences called runes. A String holds arbitrary bytes.
package main
import "fmt"
func main() {
var greeting = "Hello world!"
fmt.Printf("normal string: ")
fmt.Printf("%s", greeting)
fmt.Printf("\n")
fmt.Printf("hex bytes: ")
for i := 0; i < len(greeting); i++ {
fmt.Printf("%x ", greeting[i])
}
fmt.Printf("\n")
const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"
/*q flag escapes unprintable characters, with + flag it escapses non-ascii
characters as well to make output unambigous
*/
fmt.Printf("quoted string: ")
fmt.Printf("%+q", sampleText)
fmt.Printf("\n")
}
This would produce the following result −
normal string: Hello world!
hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21
quoted string: "\xbd\xb2=\xbc \u2318"
Note − The string literal is immutable, so that once it is created a string literal cannot be changed.
len(str) method returns the number of bytes contained in the string literal.
package main
import "fmt"
func main() {
var greeting = "Hello world!"
fmt.Printf("String Length is: ")
fmt.Println(len(greeting))
}
This would produce the following result −
String Length is : 12
The strings package includes a method join for concatenating multiple strings −
strings.Join(sample, " ")
Join concatenates the elements of an array to create a single string. Second parameter is seperator which is placed between element of the array.
Let us look at the following example −
package main
import ("fmt" "math" )"fmt" "strings")
func main() {
greetings := []string{"Hello","world!"}
fmt.Println(strings.Join(greetings, " "))
}
This would produce the following result −
Hello world!
Go programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array in Go, a programmer specifies the type of the elements and the number of elements required by an array as follows −
var variable_name [SIZE] variable_type
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Go data type. For example, to declare a 10-element array called balance of type float32, use this statement −
var balance [10] float32
Here, balance is a variable array that can hold up to 10 float numbers.
You can initialize array in Go either one by one or using a single statement as follows −
var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}
You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −
balance[4] = 50.0
The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above −
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
float32 salary = balance[9]
The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays −
package main
import "fmt"
func main() {
var n [10]int /* n is an array of 10 integers */
var i,j int
/* initialize elements of array n to 0 */
for i = 0; i < 10; i++ {
n[i] = i + 100 /* set element at location i to i + 100 */
}
/* output each array element's value */
for j = 0; j < 10; j++ {
fmt.Printf("Element[%d] = %d\n", j, n[j] )
}
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
There are important concepts related to array which should be clear to a Go programmer −
Go supports multidimensional arrays. The simplest form of a multidimensional array is the two-dimensional array.
You can pass to the function a pointer to an array by specifying the array's name without an index.
Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Go programmer.
As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined −
package main
import "fmt"
func main() {
var a int = 10
fmt.Printf("Address of a variable: %x\n", &a )
}
When the above code is compiled and executed, it produces the following result −
Address of a variable: 10328000
So you understood what is memory address and how to access it. Now let us see what pointers are.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is −
var var_name *var-type
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −
var ip *int /* pointer to an integer */
var fp *float32 /* pointer to a float */
The actual data type of the value of all pointers, whether integer, float, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
There are a few important operations, which we frequently perform with pointers: (a) we define pointer variables, (b) assign the address of a variable to a pointer, and (c) access the value at the address stored in the pointer variable.
All these operations are carried out using the unary operator * that returns the value of the variable located at the address specified by its operand. The following example demonstrates how to perform these operations −
package main
import "fmt"
func main() {
var a int = 20 /* actual variable declaration */
var ip *int /* pointer variable declaration */
ip = &a /* store address of a in pointer variable*/
fmt.Printf("Address of a variable: %x\n", &a )
/* address stored in pointer variable */
fmt.Printf("Address stored in ip variable: %x\n", ip )
/* access the value using the pointer */
fmt.Printf("Value of *ip variable: %d\n", *ip )
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: 10328000
Address stored in ip variable: 10328000
Value of *ip variable: 20
Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer.
The nil pointer is a constant with a value of zero defined in several standard libraries. Consider the following program −
package main
import "fmt"
func main() {
var ptr *int
fmt.Printf("The value of ptr is : %x\n", ptr )
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the nil (zero) value, it is assumed to point to nothing.
To check for a nil pointer you can use an if statement as follows −
if(ptr != nil) /* succeeds if p is not nil */
if(ptr == nil) /* succeeds if p is null */
Pointers have many but easy concepts and they are very important to Go programming. The following concepts of pointers should be clear to a Go programmer −
You can define arrays to hold a number of pointers.
Go allows you to have pointer on a pointer and so on.
Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
Go arrays allow you to define variables that can hold several data items of the same kind. Structure is another user-defined data type available in Go programming, which allows you to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of the books in a library. You might want to track the following attributes of each book −
Title
Author
Subject
Book ID
In such a scenario, structures are highly useful.
To define a structure, you must use type and struct statements. The struct statement defines a new data type, with multiple members for your program. The type statement binds a name with the type which is struct in our case. The format of the struct statement is as follows −
type struct_variable_type struct {
member definition;
member definition;
...
member definition;
}
Once a structure type is defined, it can be used to declare variables of that type using the following syntax.
variable_name := structure_variable_type {value1, value2...valuen}
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. The following example explains how to use a structure −
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
/* print Book1 info */
fmt.Printf( "Book 1 title : %s\n", Book1.title)
fmt.Printf( "Book 1 author : %s\n", Book1.author)
fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)
/* print Book2 info */
fmt.Printf( "Book 2 title : %s\n", Book2.title)
fmt.Printf( "Book 2 author : %s\n", Book2.author)
fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Go Programming
Book 1 author : Mahesh Kumar
Book 1 subject : Go Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the same way as you did in the above example −
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
/* print Book1 info */
printBook(Book1)
/* print Book2 info */
printBook(Book2)
}
func printBook( book Books ) {
fmt.Printf( "Book title : %s\n", book.title);
fmt.Printf( "Book author : %s\n", book.author);
fmt.Printf( "Book subject : %s\n", book.subject);
fmt.Printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : Go Programming
Book author : Mahesh Kumar
Book subject : Go Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
You can define pointers to structures in the same way as you define pointer to any other variable as follows −
var struct_pointer *Books
Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the "." operator as follows −
struct_pointer.title;
Let us re-write the above example using structure pointer −
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
/* print Book1 info */
printBook(&Book1)
/* print Book2 info */
printBook(&Book2)
}
func printBook( book *Books ) {
fmt.Printf( "Book title : %s\n", book.title);
fmt.Printf( "Book author : %s\n", book.author);
fmt.Printf( "Book subject : %s\n", book.subject);
fmt.Printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : Go Programming
Book author : Mahesh Kumar
Book subject : Go Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
Go Slice is an abstraction over Go Array. Go Array allows you to define variables that can hold several data items of the same kind but it does not provide any inbuilt method to increase its size dynamically or get a sub-array of its own. Slices overcome this limitation. It provides many utility functions required on Array and is widely used in Go programming.
To define a slice, you can declare it as an array without specifying its size. Alternatively, you can use make function to create a slice.
var numbers []int /* a slice of unspecified size */
/* numbers == []int{0,0,0,0,0}*/
numbers = make([]int,5,5) /* a slice of length 5 and capacity 5*/
A slice is an abstraction over array. It actually uses arrays as an underlying structure. The len() function returns the elements presents in the slice where cap() function returns the capacity of the slice (i.e., how many elements it can be accommodate). The following example explains the usage of slice −
package main
import "fmt"
func main() {
var numbers = make([]int,3,5)
printSlice(numbers)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 3 cap = 5 slice = [0 0 0]
If a slice is declared with no inputs, then by default, it is initialized as nil. Its length and capacity are zero. For example −
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
if(numbers == nil){
fmt.Printf("slice is nil")
}
}
func printSlice(x []int){
fmt.Printf("len = %d cap = %d slice = %v\n", len(x), cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 0 cap = 0 slice = []
slice is nil
Slice allows lower-bound and upper bound to be specified to get the subslice of it using[lower-bound:upper-bound]. For example −
package main
import "fmt"
func main() {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
printSlice(numbers)
/* print the original slice */
fmt.Println("numbers ==", numbers)
/* print the sub slice starting from index 1(included) to index 4(excluded)*/
fmt.Println("numbers[1:4] ==", numbers[1:4])
/* missing lower bound implies 0*/
fmt.Println("numbers[:3] ==", numbers[:3])
/* missing upper bound implies len(s)*/
fmt.Println("numbers[4:] ==", numbers[4:])
numbers1 := make([]int,0,5)
printSlice(numbers1)
/* print the sub slice starting from index 0(included) to index 2(excluded) */
number2 := numbers[:2]
printSlice(number2)
/* print the sub slice starting from index 2(included) to index 5(excluded) */
number3 := numbers[2:5]
printSlice(number3)
}
func printSlice(x []int){
fmt.Printf("len = %d cap = %d slice = %v\n", len(x), cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 9 cap = 9 slice = [0 1 2 3 4 5 6 7 8]
numbers == [0 1 2 3 4 5 6 7 8]
numbers[1:4] == [1 2 3]
numbers[:3] == [0 1 2]
numbers[4:] == [4 5 6 7 8]
len = 0 cap = 5 slice = []
len = 2 cap = 9 slice = [0 1]
len = 3 cap = 7 slice = [2 3 4]
One can increase the capacity of a slice using the append() function. Using copy()function, the contents of a source slice are copied to a destination slice. For example −
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
/* append allows nil slice */
numbers = append(numbers, 0)
printSlice(numbers)
/* add one element to slice*/
numbers = append(numbers, 1)
printSlice(numbers)
/* add more than one element at a time*/
numbers = append(numbers, 2,3,4)
printSlice(numbers)
/* create a slice numbers1 with double the capacity of earlier slice*/
numbers1 := make([]int, len(numbers), (cap(numbers))*2)
/* copy content of numbers to numbers1 */
copy(numbers1,numbers)
printSlice(numbers1)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 0 cap = 0 slice = []
len = 1 cap = 2 slice = [0]
len = 2 cap = 2 slice = [0 1]
len = 5 cap = 8 slice = [0 1 2 3 4]
len = 5 cap = 16 slice = [0 1 2 3 4]
The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.
The following paragraph shows how to use range −
package main
import "fmt"
func main() {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
/* print the numbers */
for i:= range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}
/* create a map*/
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* print map using key-value*/
for country,capital := range countryCapitalMap {
fmt.Println("Capital of",country,"is",capital)
}
}
When the above code is compiled and executed, it produces the following result −
Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
You must use make function to create a map.
/* declare a variable, by default map will be nil*/
var map_variable map[key_data_type]value_data_type
/* define the map as nil map can not be assigned any value*/
map_variable = make(map[key_data_type]value_data_type)
The following example illustrates how to create and use a map −
package main
import "fmt"
func main() {
var countryCapitalMap map[string]string
/* create a map*/
countryCapitalMap = make(map[string]string)
/* insert key-value pairs in the map*/
countryCapitalMap["France"] = "Paris"
countryCapitalMap["Italy"] = "Rome"
countryCapitalMap["Japan"] = "Tokyo"
countryCapitalMap["India"] = "New Delhi"
/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* test if entry is present in the map or not*/
capital, ok := countryCapitalMap["United States"]
/* if ok is true, entry is present otherwise entry is absent*/
if(ok){
fmt.Println("Capital of United States is", capital)
} else {
fmt.Println("Capital of United States is not present")
}
}
When the above code is compiled and executed, it produces the following result −
Capital of India is New Delhi
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of United States is not present
delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example −
package main
import "fmt"
func main() {
/* create a map*/
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
fmt.Println("Original map")
/* print map */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* delete an entry */
delete(countryCapitalMap,"France");
fmt.Println("Entry for France is deleted")
fmt.Println("Updated map")
/* print map */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
}
When the above code is compiled and executed, it produces the following result −
Original Map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
Updated Map
Capital of India is New Delhi
Capital of Italy is Rome
Capital of Japan is Tokyo
Recursion is the process of repeating items in a self-similar way. The same concept applies in programming languages as well. If a program allows to call a function inside the same function, then it is called a recursive function call. Take a look at the following example −
func recursion() {
recursion() /* function calls itself */
}
func main() {
recursion()
}
The Go programming language supports recursion. That is, it allows a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go on to become an infinite loop.
Recursive functions are very useful to solve many mathematical problems such as calculating factorial of a number, generating a Fibonacci series, etc.
The following example calculates the factorial of a given number using a recursive function −
package main
import "fmt"
func factorial(i int)int {
if(i <= 1) {
return 1
}
return i * factorial(i - 1)
}
func main() {
var i int = 15
fmt.Printf("Factorial of %d is %d", i, factorial(i))
}
When the above code is compiled and executed, it produces the following result −
Factorial of 15 is 1307674368000
The following example shows how to generate a Fibonacci series of a given number using a recursive function −
package main
import "fmt"
func fibonaci(i int) (ret int) {
if i == 0 {
return 0
}
if i == 1 {
return 1
}
return fibonaci(i-1) + fibonaci(i-2)
}
func main() {
var i int
for i = 0; i < 10; i++ {
fmt.Printf("%d ", fibonaci(i))
}
}
When the above code is compiled and executed, it produces the following result −
0 1 1 2 3 5 8 13 21 34
Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator. Its syntax is as follows −
type_name(expression)
Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating number operation.
package main
import "fmt"
func main() {
var sum int = 17
var count int = 5
var mean float32
mean = float32(sum)/float32(count)
fmt.Printf("Value of mean : %f\n",mean)
}
When the above code is compiled and executed, it produces the following result −
Value of mean : 3.400000
Go programming provides another data type called interfaces which represents a set of method signatures. The struct data type implements these interfaces to have method definitions for the method signature of the interfaces.
/* define an interface */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
/* define a struct */
type struct_name struct {
/* variables */
}
/* implement interface methods*/
func (struct_name_variable struct_name) method_name1() [return_type] {
/* method implementation */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* method implementation */
}
package main
import (
"fmt"
"math"
)
/* define an interface */
type Shape interface {
area() float64
}
/* define a circle */
type Circle struct {
x,y,radius float64
}
/* define a rectangle */
type Rectangle struct {
width, height float64
}
/* define a method for circle (implementation of Shape.area())*/
func(circle Circle) area() float64 {
return math.Pi * circle.radius * circle.radius
}
/* define a method for rectangle (implementation of Shape.area())*/
func(rect Rectangle) area() float64 {
return rect.width * rect.height
}
/* define a method for shape */
func getArea(shape Shape) float64 {
return shape.area()
}
func main() {
circle := Circle{x:0,y:0,radius:5}
rectangle := Rectangle {width:10, height:5}
fmt.Printf("Circle area: %f\n",getArea(circle))
fmt.Printf("Rectangle area: %f\n",getArea(rectangle))
}
When the above code is compiled and executed, it produces the following result −
Circle area: 78.539816
Rectangle area: 50.000000
Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration −
type error interface {
Error() string
}
Functions normally return error as last return value. Use errors.New to construct a basic error message as following −
func Sqrt(value float64)(float64, error) {
if(value < 0){
return 0, errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value), nil
}
Use return value and error message.
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
}
package main
import "errors"
import "fmt"
import "math"
func Sqrt(value float64)(float64, error) {
if(value < 0){
return 0, errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value), nil
}
func main() {
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
result, err = Sqrt(9)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
When the above code is compiled and executed, it produces the following result −
Math: negative number passed to Sqrt
3
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2239,
"s": 1937,
"text": "Go is a general-purpose language designed with systems programming in mind. It was initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection, and supports concurrent programming."
},
{
"code": null,
"e": 2542,
"s": 2239,
"text": "Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries. The Go programming language was announced in November 2009 and is used in some of the Google's production systems."
},
{
"code": null,
"e": 2607,
"s": 2542,
"text": "The most important features of Go programming are listed below −"
},
{
"code": null,
"e": 2765,
"s": 2607,
"text": "Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int)"
},
{
"code": null,
"e": 2923,
"s": 2765,
"text": "Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int)"
},
{
"code": null,
"e": 2949,
"s": 2923,
"text": "Compilation time is fast."
},
{
"code": null,
"e": 2975,
"s": 2949,
"text": "Compilation time is fast."
},
{
"code": null,
"e": 3073,
"s": 2975,
"text": "Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement."
},
{
"code": null,
"e": 3171,
"s": 3073,
"text": "Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement."
},
{
"code": null,
"e": 3214,
"s": 3171,
"text": "Go programs are simple, concise, and safe."
},
{
"code": null,
"e": 3257,
"s": 3214,
"text": "Go programs are simple, concise, and safe."
},
{
"code": null,
"e": 3300,
"s": 3257,
"text": "Support for Interfaces and Type embedding."
},
{
"code": null,
"e": 3343,
"s": 3300,
"text": "Support for Interfaces and Type embedding."
},
{
"code": null,
"e": 3422,
"s": 3343,
"text": "Production of statically linked native binaries without external dependencies."
},
{
"code": null,
"e": 3501,
"s": 3422,
"text": "Production of statically linked native binaries without external dependencies."
},
{
"code": null,
"e": 3631,
"s": 3501,
"text": "To keep the language simple and concise, the following features commonly available in other similar languages are omitted in Go −"
},
{
"code": null,
"e": 3660,
"s": 3631,
"text": "Support for type inheritance"
},
{
"code": null,
"e": 3689,
"s": 3660,
"text": "Support for type inheritance"
},
{
"code": null,
"e": 3732,
"s": 3689,
"text": "Support for method or operator overloading"
},
{
"code": null,
"e": 3775,
"s": 3732,
"text": "Support for method or operator overloading"
},
{
"code": null,
"e": 3824,
"s": 3775,
"text": "Support for circular dependencies among packages"
},
{
"code": null,
"e": 3873,
"s": 3824,
"text": "Support for circular dependencies among packages"
},
{
"code": null,
"e": 3904,
"s": 3873,
"text": "Support for pointer arithmetic"
},
{
"code": null,
"e": 3935,
"s": 3904,
"text": "Support for pointer arithmetic"
},
{
"code": null,
"e": 3958,
"s": 3935,
"text": "Support for assertions"
},
{
"code": null,
"e": 3981,
"s": 3958,
"text": "Support for assertions"
},
{
"code": null,
"e": 4013,
"s": 3981,
"text": "Support for generic programming"
},
{
"code": null,
"e": 4045,
"s": 4013,
"text": "Support for generic programming"
},
{
"code": null,
"e": 4213,
"s": 4045,
"text": "A Go program can vary in length from 3 lines to millions of lines and it should be written into one or more text files with the extension \".go\". For example, hello.go."
},
{
"code": null,
"e": 4300,
"s": 4213,
"text": "You can use \"vi\", \"vim\" or any other text editor to write your Go program into a file."
},
{
"code": null,
"e": 4446,
"s": 4300,
"text": "If you are still willing to set up your environment for Go programming language, you need the following two software available on your computer −"
},
{
"code": null,
"e": 4461,
"s": 4446,
"text": "A text editor "
},
{
"code": null,
"e": 4473,
"s": 4461,
"text": "Go compiler"
},
{
"code": null,
"e": 4632,
"s": 4473,
"text": "You will require a text editor to type your programs. Examples of text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi."
},
{
"code": null,
"e": 4810,
"s": 4632,
"text": "The name and version of text editors can vary on different operating systems. For example, Notepad is used on Windows, and vim or vi is used on Windows as well as Linux or UNIX."
},
{
"code": null,
"e": 4990,
"s": 4810,
"text": "The files you create with the text editor are called source files. They contain program source code. The source files for Go programs are typically named with the extension \".go\"."
},
{
"code": null,
"e": 5181,
"s": 4990,
"text": "Before starting your programming, make sure you have a text editor in place and you have enough experience to write a computer program, save it in a file, compile it, and finally execute it."
},
{
"code": null,
"e": 5502,
"s": 5181,
"text": "The source code written in source file is the human readable source for your program. It needs to be compiled and turned into machine language so that your CPU can actually execute the program as per the instructions given. The Go programming language compiler compiles the source code into its final executable program."
},
{
"code": null,
"e": 5721,
"s": 5502,
"text": "Go distribution comes as a binary installable for FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems with 32-bit (386) and 64-bit (amd64) x86 processor architectures."
},
{
"code": null,
"e": 5805,
"s": 5721,
"text": "The following section explains how to install Go binary distribution on various OS."
},
{
"code": null,
"e": 5956,
"s": 5805,
"text": "Download the latest version of Go installable archive file from Go Downloads. The following version is used in this tutorial: go1.4.windows-amd64.msi."
},
{
"code": null,
"e": 5992,
"s": 5956,
"text": "It is copied it into C:\\>go folder."
},
{
"code": null,
"e": 6100,
"s": 5992,
"text": "Extract the download archive into the folder /usr/local, creating a Go tree in /usr/local/go. For example −"
},
{
"code": null,
"e": 6148,
"s": 6100,
"text": "tar -C /usr/local -xzf go1.4.linux-amd64.tar.gz"
},
{
"code": null,
"e": 6204,
"s": 6148,
"text": "Add /usr/local/go/bin to the PATH environment variable."
},
{
"code": null,
"e": 6482,
"s": 6204,
"text": "Use the MSI file and follow the prompts to install the Go tools. By default, the installer uses the Go distribution in c:\\Go. The installer should set the c:\\Go\\bin directory in Window's PATH environment variable. Restart any open command prompts for the change to take effect."
},
{
"code": null,
"e": 6534,
"s": 6482,
"text": "Create a go file named test.go in C:\\>Go_WorkSpace."
},
{
"code": null,
"e": 6610,
"s": 6534,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"Hello, World!\")\n}"
},
{
"code": null,
"e": 6646,
"s": 6610,
"text": "Now run test.go to see the result −"
},
{
"code": null,
"e": 6678,
"s": 6646,
"text": "C:\\Go_WorkSpace>go run test.go\n"
},
{
"code": null,
"e": 6693,
"s": 6678,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 6888,
"s": 6693,
"text": "Before we study the basic building blocks of Go programming language, let us first discuss the bare minimum structure of Go programs so that we can take it as a reference in subsequent chapters."
},
{
"code": null,
"e": 6945,
"s": 6888,
"text": "A Go program basically consists of the following parts −"
},
{
"code": null,
"e": 6965,
"s": 6945,
"text": "Package Declaration"
},
{
"code": null,
"e": 6981,
"s": 6965,
"text": "Import Packages"
},
{
"code": null,
"e": 6991,
"s": 6981,
"text": "Functions"
},
{
"code": null,
"e": 7001,
"s": 6991,
"text": "Variables"
},
{
"code": null,
"e": 7028,
"s": 7001,
"text": "Statements and Expressions"
},
{
"code": null,
"e": 7037,
"s": 7028,
"text": "Comments"
},
{
"code": null,
"e": 7109,
"s": 7037,
"text": "Let us look at a simple code that would print the words \"Hello World\" −"
},
{
"code": null,
"e": 7227,
"s": 7109,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* This is my first sample program. */\n fmt.Println(\"Hello, World!\")\n}"
},
{
"code": null,
"e": 7290,
"s": 7227,
"text": "Let us take a look at the various parts of the above program −"
},
{
"code": null,
"e": 7565,
"s": 7290,
"text": "The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it."
},
{
"code": null,
"e": 7840,
"s": 7565,
"text": "The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it."
},
{
"code": null,
"e": 7968,
"s": 7840,
"text": "The next line import \"fmt\" is a preprocessor command which tells the Go compiler to include the files lying in the package fmt."
},
{
"code": null,
"e": 8096,
"s": 7968,
"text": "The next line import \"fmt\" is a preprocessor command which tells the Go compiler to include the files lying in the package fmt."
},
{
"code": null,
"e": 8179,
"s": 8096,
"text": "The next line func main() is the main function where the program execution begins."
},
{
"code": null,
"e": 8262,
"s": 8179,
"text": "The next line func main() is the main function where the program execution begins."
},
{
"code": null,
"e": 8431,
"s": 8262,
"text": "The next line /*...*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments."
},
{
"code": null,
"e": 8600,
"s": 8431,
"text": "The next line /*...*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments."
},
{
"code": null,
"e": 8836,
"s": 8600,
"text": "The next line fmt.Println(...) is another function available in Go which causes the message \"Hello, World!\" to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen."
},
{
"code": null,
"e": 9072,
"s": 8836,
"text": "The next line fmt.Println(...) is another function available in Go which causes the message \"Hello, World!\" to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen."
},
{
"code": null,
"e": 9287,
"s": 9072,
"text": "Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package."
},
{
"code": null,
"e": 9502,
"s": 9287,
"text": "Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package."
},
{
"code": null,
"e": 9639,
"s": 9502,
"text": "Let us discuss how to save the source code in a file, compile it, and finally execute the program. Please follow the steps given below −"
},
{
"code": null,
"e": 9692,
"s": 9639,
"text": "Open a text editor and add the above-mentioned code."
},
{
"code": null,
"e": 9745,
"s": 9692,
"text": "Open a text editor and add the above-mentioned code."
},
{
"code": null,
"e": 9771,
"s": 9745,
"text": "Save the file as hello.go"
},
{
"code": null,
"e": 9797,
"s": 9771,
"text": "Save the file as hello.go"
},
{
"code": null,
"e": 9822,
"s": 9797,
"text": "Open the command prompt."
},
{
"code": null,
"e": 9847,
"s": 9822,
"text": "Open the command prompt."
},
{
"code": null,
"e": 9893,
"s": 9847,
"text": "Go to the directory where you saved the file."
},
{
"code": null,
"e": 9939,
"s": 9893,
"text": "Go to the directory where you saved the file."
},
{
"code": null,
"e": 9994,
"s": 9939,
"text": "Type go run hello.go and press enter to run your code."
},
{
"code": null,
"e": 10049,
"s": 9994,
"text": "Type go run hello.go and press enter to run your code."
},
{
"code": null,
"e": 10142,
"s": 10049,
"text": "If there are no errors in your code, then you will see \"Hello World!\" printed on the screen."
},
{
"code": null,
"e": 10235,
"s": 10142,
"text": "If there are no errors in your code, then you will see \"Hello World!\" printed on the screen."
},
{
"code": null,
"e": 10268,
"s": 10235,
"text": "$ go run hello.go\nHello, World!\n"
},
{
"code": null,
"e": 10392,
"s": 10268,
"text": "Make sure the Go compiler is in your path and that you are running it in the directory containing the source file hello.go."
},
{
"code": null,
"e": 10564,
"s": 10392,
"text": "We discussed the basic structure of a Go program in the previous chapter. Now it will be easy to understand the other basic building blocks of the Go programming language."
},
{
"code": null,
"e": 10757,
"s": 10564,
"text": "A Go program consists of various tokens. A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −"
},
{
"code": null,
"e": 10787,
"s": 10757,
"text": "fmt.Println(\"Hello, World!\")\n"
},
{
"code": null,
"e": 10815,
"s": 10787,
"text": "The individual tokens are −"
},
{
"code": null,
"e": 10852,
"s": 10815,
"text": "fmt\n.\nPrintln\n(\n \"Hello, World!\"\n)"
},
{
"code": null,
"e": 11105,
"s": 10852,
"text": "In a Go program, the line separator key is a statement terminator. That is, individual statements don't need a special separator like “;” in C. The Go compiler internally places “;” as the statement terminator to indicate the end of one logical entity."
},
{
"code": null,
"e": 11160,
"s": 11105,
"text": "For example, take a look at the following statements −"
},
{
"code": null,
"e": 11235,
"s": 11160,
"text": "fmt.Println(\"Hello, World!\")\nfmt.Println(\"I am in Go Programming World!\")\n"
},
{
"code": null,
"e": 11398,
"s": 11235,
"text": "Comments are like helping texts in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below −"
},
{
"code": null,
"e": 11428,
"s": 11398,
"text": "/* my first program in Go */\n"
},
{
"code": null,
"e": 11530,
"s": 11428,
"text": "You cannot have comments within comments and they do not occur within a string or character literals."
},
{
"code": null,
"e": 11766,
"s": 11530,
"text": "A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9)."
},
{
"code": null,
"e": 11814,
"s": 11766,
"text": "identifier = letter { letter | unicode_digit }."
},
{
"code": null,
"e": 12056,
"s": 11814,
"text": "Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers −"
},
{
"code": null,
"e": 12146,
"s": 12056,
"text": "mahesh kumar abc move_name a_123\nmyname50 _temp j a23b9 retVal\n"
},
{
"code": null,
"e": 12289,
"s": 12146,
"text": "The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names."
},
{
"code": null,
"e": 12507,
"s": 12289,
"text": "Whitespace is the term used in Go to describe blanks, tabs, newline characters, and comments. A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it."
},
{
"code": null,
"e": 12723,
"s": 12507,
"text": "Whitespaces separate one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −"
},
{
"code": null,
"e": 12737,
"s": 12723,
"text": "var age int;\n"
},
{
"code": null,
"e": 12920,
"s": 12737,
"text": "There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −"
},
{
"code": null,
"e": 12972,
"s": 12920,
"text": "fruit = apples + oranges; // get the total fruit\n"
},
{
"code": null,
"e": 13132,
"s": 12972,
"text": "No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose."
},
{
"code": null,
"e": 13385,
"s": 13132,
"text": "In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted."
},
{
"code": null,
"e": 13432,
"s": 13385,
"text": "The types in Go can be classified as follows −"
},
{
"code": null,
"e": 13446,
"s": 13432,
"text": "Boolean types"
},
{
"code": null,
"e": 13534,
"s": 13446,
"text": "They are boolean types and consists of the two predefined constants: (a) true (b) false"
},
{
"code": null,
"e": 13548,
"s": 13534,
"text": "Numeric types"
},
{
"code": null,
"e": 13669,
"s": 13548,
"text": "They are again arithmetic types and they represents a) integer types or b) floating point values throughout the program."
},
{
"code": null,
"e": 13682,
"s": 13669,
"text": "String types"
},
{
"code": null,
"e": 13911,
"s": 13682,
"text": "A string type represents the set of string values. Its value is a sequence of bytes. Strings are immutable types that is once created, it is not possible to change the contents of a string. The predeclared string type is string."
},
{
"code": null,
"e": 13925,
"s": 13911,
"text": "Derived types"
},
{
"code": null,
"e": 14098,
"s": 13925,
"text": "They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types f) Slice types g) Interface types h) Map types i) Channel Types"
},
{
"code": null,
"e": 14399,
"s": 14098,
"text": "Array types and structure types are collectively referred to as aggregate types. The type of a function specifies the set of all functions with the same parameter and result types. We will discuss the basic types in the following section, whereas other types will be covered in the upcoming chapters."
},
{
"code": null,
"e": 14459,
"s": 14399,
"text": "The predefined architecture-independent integer types are −"
},
{
"code": null,
"e": 14465,
"s": 14459,
"text": "uint8"
},
{
"code": null,
"e": 14501,
"s": 14465,
"text": "Unsigned 8-bit integers (0 to 255)"
},
{
"code": null,
"e": 14508,
"s": 14501,
"text": "uint16"
},
{
"code": null,
"e": 14546,
"s": 14508,
"text": "Unsigned 16-bit integers (0 to 65535)"
},
{
"code": null,
"e": 14553,
"s": 14546,
"text": "uint32"
},
{
"code": null,
"e": 14596,
"s": 14553,
"text": "Unsigned 32-bit integers (0 to 4294967295)"
},
{
"code": null,
"e": 14603,
"s": 14596,
"text": "uint64"
},
{
"code": null,
"e": 14656,
"s": 14603,
"text": "Unsigned 64-bit integers (0 to 18446744073709551615)"
},
{
"code": null,
"e": 14661,
"s": 14656,
"text": "int8"
},
{
"code": null,
"e": 14697,
"s": 14661,
"text": "Signed 8-bit integers (-128 to 127)"
},
{
"code": null,
"e": 14703,
"s": 14697,
"text": "int16"
},
{
"code": null,
"e": 14744,
"s": 14703,
"text": "Signed 16-bit integers (-32768 to 32767)"
},
{
"code": null,
"e": 14750,
"s": 14744,
"text": "int32"
},
{
"code": null,
"e": 14801,
"s": 14750,
"text": "Signed 32-bit integers (-2147483648 to 2147483647)"
},
{
"code": null,
"e": 14807,
"s": 14801,
"text": "int64"
},
{
"code": null,
"e": 14876,
"s": 14807,
"text": "Signed 64-bit integers (-9223372036854775808 to 9223372036854775807)"
},
{
"code": null,
"e": 14934,
"s": 14876,
"text": "The predefined architecture-independent float types are −"
},
{
"code": null,
"e": 14942,
"s": 14934,
"text": "float32"
},
{
"code": null,
"e": 14981,
"s": 14942,
"text": "IEEE-754 32-bit floating-point numbers"
},
{
"code": null,
"e": 14989,
"s": 14981,
"text": "float64"
},
{
"code": null,
"e": 15028,
"s": 14989,
"text": "IEEE-754 64-bit floating-point numbers"
},
{
"code": null,
"e": 15038,
"s": 15028,
"text": "complex64"
},
{
"code": null,
"e": 15092,
"s": 15038,
"text": "Complex numbers with float32 real and imaginary parts"
},
{
"code": null,
"e": 15103,
"s": 15092,
"text": "complex128"
},
{
"code": null,
"e": 15157,
"s": 15103,
"text": "Complex numbers with float64 real and imaginary parts"
},
{
"code": null,
"e": 15262,
"s": 15157,
"text": "The value of an n-bit integer is n bits and is represented using two's complement arithmetic operations."
},
{
"code": null,
"e": 15336,
"s": 15262,
"text": "There is also a set of numeric types with implementation-specific sizes −"
},
{
"code": null,
"e": 15341,
"s": 15336,
"text": "byte"
},
{
"code": null,
"e": 15355,
"s": 15341,
"text": "same as uint8"
},
{
"code": null,
"e": 15360,
"s": 15355,
"text": "rune"
},
{
"code": null,
"e": 15374,
"s": 15360,
"text": "same as int32"
},
{
"code": null,
"e": 15379,
"s": 15374,
"text": "uint"
},
{
"code": null,
"e": 15393,
"s": 15379,
"text": "32 or 64 bits"
},
{
"code": null,
"e": 15397,
"s": 15393,
"text": "int"
},
{
"code": null,
"e": 15415,
"s": 15397,
"text": "same size as uint"
},
{
"code": null,
"e": 15423,
"s": 15415,
"text": "uintptr"
},
{
"code": null,
"e": 15494,
"s": 15423,
"text": "an unsigned integer to store the uninterpreted bits of a pointer value"
},
{
"code": null,
"e": 15811,
"s": 15494,
"text": "A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 16135,
"s": 15811,
"text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −"
},
{
"code": null,
"e": 16140,
"s": 16135,
"text": "byte"
},
{
"code": null,
"e": 16198,
"s": 16140,
"text": "Typically a single octet(one byte). This is an byte type."
},
{
"code": null,
"e": 16202,
"s": 16198,
"text": "int"
},
{
"code": null,
"e": 16252,
"s": 16202,
"text": "The most natural size of integer for the machine."
},
{
"code": null,
"e": 16260,
"s": 16252,
"text": "float32"
},
{
"code": null,
"e": 16301,
"s": 16260,
"text": "A single-precision floating point value."
},
{
"code": null,
"e": 16543,
"s": 16301,
"text": "Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types."
},
{
"code": null,
"e": 16754,
"s": 16543,
"text": "A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −"
},
{
"code": null,
"e": 16793,
"s": 16754,
"text": "var variable_list optional_data_type;\n"
},
{
"code": null,
"e": 17049,
"s": 16793,
"text": "Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −"
},
{
"code": null,
"e": 17118,
"s": 17049,
"text": "var i, j, k int;\nvar c, ch byte;\nvar f, salary float32;\nd = 42;\n"
},
{
"code": null,
"e": 17274,
"s": 17118,
"text": "The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int."
},
{
"code": null,
"e": 17536,
"s": 17274,
"text": "Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows −"
},
{
"code": null,
"e": 17560,
"s": 17536,
"text": "variable_name = value;\n"
},
{
"code": null,
"e": 17573,
"s": 17560,
"text": "For example,"
},
{
"code": null,
"e": 17640,
"s": 17573,
"text": "d = 3, f = 5; // declaration of d and f. Here d and f are int \n"
},
{
"code": null,
"e": 17859,
"s": 17640,
"text": "For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type."
},
{
"code": null,
"e": 18269,
"s": 17859,
"text": "A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program."
},
{
"code": null,
"e": 18388,
"s": 18269,
"text": "Try the following example, where the variable has been declared with a type and initialized inside the main function −"
},
{
"code": null,
"e": 18517,
"s": 18388,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var x float64\n x = 20.0\n fmt.Println(x)\n fmt.Printf(\"x is of type %T\\n\", x)\n}"
},
{
"code": null,
"e": 18598,
"s": 18517,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 18623,
"s": 18598,
"text": "20\nx is of type float64\n"
},
{
"code": null,
"e": 18845,
"s": 18623,
"text": "A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement."
},
{
"code": null,
"e": 19055,
"s": 18845,
"text": "Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator."
},
{
"code": null,
"e": 19249,
"s": 19055,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var x float64 = 20.0\n\n y := 42 \n fmt.Println(x)\n fmt.Println(y)\n fmt.Printf(\"x is of type %T\\n\", x)\n fmt.Printf(\"y is of type %T\\n\", y)\t\n}"
},
{
"code": null,
"e": 19330,
"s": 19249,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 19375,
"s": 19330,
"text": "20\n42\nx is of type float64\ny is of type int\n"
},
{
"code": null,
"e": 19453,
"s": 19375,
"text": "Variables of different types can be declared in one go using type inference. "
},
{
"code": null,
"e": 19698,
"s": 19453,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a, b, c = 3, 4, \"foo\" \n\t\n fmt.Println(a)\n fmt.Println(b)\n fmt.Println(c)\n fmt.Printf(\"a is of type %T\\n\", a)\n fmt.Printf(\"b is of type %T\\n\", b)\n fmt.Printf(\"c is of type %T\\n\", c)\n}"
},
{
"code": null,
"e": 19779,
"s": 19698,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 19842,
"s": 19779,
"text": "3\n4\nfoo\na is of type int\nb is of type int\nc is of type string\n"
},
{
"code": null,
"e": 19885,
"s": 19842,
"text": "There are two kinds of expressions in Go −"
},
{
"code": null,
"e": 20052,
"s": 19885,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 20219,
"s": 20052,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 20464,
"s": 20219,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 20709,
"s": 20464,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 20887,
"s": 20709,
"text": "Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side."
},
{
"code": null,
"e": 20922,
"s": 20887,
"text": "The following statement is valid −"
},
{
"code": null,
"e": 20932,
"s": 20922,
"text": "x = 20.0\n"
},
{
"code": null,
"e": 21009,
"s": 20932,
"text": "The following statement is not valid. It would generate compile-time error −"
},
{
"code": null,
"e": 21018,
"s": 21009,
"text": "10 = 20\n"
},
{
"code": null,
"e": 21148,
"s": 21018,
"text": "Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals."
},
{
"code": null,
"e": 21332,
"s": 21148,
"text": "Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well."
},
{
"code": null,
"e": 21450,
"s": 21332,
"text": "Constants are treated just like regular variables except that their values cannot be modified after their definition."
},
{
"code": null,
"e": 21621,
"s": 21450,
"text": "An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal."
},
{
"code": null,
"e": 21800,
"s": 21621,
"text": "An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order."
},
{
"code": null,
"e": 21845,
"s": 21800,
"text": "Here are some examples of integer literals −"
},
{
"code": null,
"e": 22019,
"s": 21845,
"text": "212 /* Legal */\n215u /* Legal */\n0xFeeL /* Legal */\n078 /* Illegal: 8 is not an octal digit */\n032UU /* Illegal: cannot repeat a suffix */\n"
},
{
"code": null,
"e": 22086,
"s": 22019,
"text": "Following are other examples of various type of Integer literals −"
},
{
"code": null,
"e": 22268,
"s": 22086,
"text": "85 /* decimal */\n0213 /* octal */\n0x4b /* hexadecimal */\n30 /* int */\n30u /* unsigned int */\n30l /* long */\n30ul /* unsigned long */\n"
},
{
"code": null,
"e": 22458,
"s": 22268,
"text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form."
},
{
"code": null,
"e": 22712,
"s": 22458,
"text": "While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E."
},
{
"code": null,
"e": 22764,
"s": 22712,
"text": "Here are some examples of floating-point literals −"
},
{
"code": null,
"e": 22975,
"s": 22764,
"text": "3.14159 /* Legal */\n314159E-5L /* Legal */\n510E /* Illegal: incomplete exponent */\n210f /* Illegal: no decimal or exponent */\n.e55 /* Illegal: missing integer or fraction */\n"
},
{
"code": null,
"e": 23239,
"s": 22975,
"text": "When certain characters are preceded by a backslash, they will have a special meaning in Go. These are known as Escape Sequence codes which are used to represent newline (\\n), tab (\\t), backspace, etc. Here, you have a list of some of such escape sequence codes −"
},
{
"code": null,
"e": 23296,
"s": 23239,
"text": "The following example shows how to use \\t in a program −"
},
{
"code": null,
"e": 23371,
"s": 23296,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Printf(\"Hello\\tWorld!\")\n}"
},
{
"code": null,
"e": 23452,
"s": 23371,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 23466,
"s": 23452,
"text": "Hello World!\n"
},
{
"code": null,
"e": 23660,
"s": 23466,
"text": "String literals or constants are enclosed in double quotes \"\". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters."
},
{
"code": null,
"e": 23767,
"s": 23660,
"text": "You can break a long line into multiple lines using string literals and separating them using whitespaces."
},
{
"code": null,
"e": 23853,
"s": 23767,
"text": "Here are some examples of string literals. All the three forms are identical strings."
},
{
"code": null,
"e": 23907,
"s": 23853,
"text": "\"hello, dear\"\n\n\"hello, \\\n\ndear\"\n\n\"hello, \" \"d\" \"ear\"\n"
},
{
"code": null,
"e": 23987,
"s": 23907,
"text": "You can use const prefix to declare constants with a specific type as follows −"
},
{
"code": null,
"e": 24017,
"s": 23987,
"text": "const variable type = value;\n"
},
{
"code": null,
"e": 24076,
"s": 24017,
"text": "The following example shows how to use the const keyword −"
},
{
"code": null,
"e": 24258,
"s": 24076,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n const LENGTH int = 10\n const WIDTH int = 5 \n var area int\n\n area = LENGTH * WIDTH\n fmt.Printf(\"value of area : %d\", area) \n}"
},
{
"code": null,
"e": 24339,
"s": 24258,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 24359,
"s": 24339,
"text": "value of area : 50\n"
},
{
"code": null,
"e": 24436,
"s": 24359,
"text": "Note that it is a good programming practice to define constants in CAPITALS."
},
{
"code": null,
"e": 24633,
"s": 24436,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators −"
},
{
"code": null,
"e": 24654,
"s": 24633,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 24675,
"s": 24654,
"text": "Relational Operators"
},
{
"code": null,
"e": 24693,
"s": 24675,
"text": "Logical Operators"
},
{
"code": null,
"e": 24711,
"s": 24693,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 24732,
"s": 24711,
"text": "Assignment Operators"
},
{
"code": null,
"e": 24756,
"s": 24732,
"text": "Miscellaneous Operators"
},
{
"code": null,
"e": 24865,
"s": 24756,
"text": "This tutorial explains arithmetic, relational, logical, bitwise, assignment, and other operators one by one."
},
{
"code": null,
"e": 25000,
"s": 24865,
"text": "Following table shows all the arithmetic operators supported by Go language. Assume variable A holds 10 and variable B holds 20 then −"
},
{
"code": null,
"e": 25014,
"s": 25000,
"text": "Show Examples"
},
{
"code": null,
"e": 25154,
"s": 25014,
"text": "The following table lists all the relational operators supported by Go language. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 25168,
"s": 25154,
"text": "Show Examples"
},
{
"code": null,
"e": 25303,
"s": 25168,
"text": "The following table lists all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then −"
},
{
"code": null,
"e": 25317,
"s": 25303,
"text": "Show Examples"
},
{
"code": null,
"e": 25459,
"s": 25317,
"text": "The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then −"
},
{
"code": null,
"e": 25574,
"s": 25459,
"text": "Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −"
},
{
"code": null,
"e": 25645,
"s": 25574,
"text": "Assume A = 60; and B = 13. In binary format, they will be as follows −"
},
{
"code": null,
"e": 25659,
"s": 25645,
"text": "A = 0011 1100"
},
{
"code": null,
"e": 25673,
"s": 25659,
"text": "B = 0000 1101"
},
{
"code": null,
"e": 25691,
"s": 25673,
"text": "-----------------"
},
{
"code": null,
"e": 25707,
"s": 25691,
"text": "A&B = 0000 1100"
},
{
"code": null,
"e": 25723,
"s": 25707,
"text": "A|B = 0011 1101"
},
{
"code": null,
"e": 25739,
"s": 25723,
"text": "A^B = 0011 0001"
},
{
"code": null,
"e": 25755,
"s": 25739,
"text": "~A = 1100 0011"
},
{
"code": null,
"e": 25895,
"s": 25755,
"text": "The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −"
},
{
"code": null,
"e": 25909,
"s": 25895,
"text": "Show Examples"
},
{
"code": null,
"e": 25991,
"s": 25909,
"text": "The following table lists all the assignment operators supported by Go language −"
},
{
"code": null,
"e": 26005,
"s": 25991,
"text": "Show Examples"
},
{
"code": null,
"e": 26097,
"s": 26005,
"text": "There are a few other important operators supported by Go Language including sizeof and ?:."
},
{
"code": null,
"e": 26111,
"s": 26097,
"text": "Show Examples"
},
{
"code": null,
"e": 26372,
"s": 26111,
"text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator."
},
{
"code": null,
"e": 26538,
"s": 26372,
"text": "For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7."
},
{
"code": null,
"e": 26733,
"s": 26538,
"text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first."
},
{
"code": null,
"e": 26747,
"s": 26733,
"text": "Show Examples"
},
{
"code": null,
"e": 27062,
"s": 26747,
"text": "Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false."
},
{
"code": null,
"e": 27176,
"s": 27062,
"text": "Following is the general form of a typical decision making structure found in most of the programming languages −"
},
{
"code": null,
"e": 27309,
"s": 27176,
"text": "Go programming language provides the following types of decision making statements. Click the following links to check their detail."
},
{
"code": null,
"e": 27394,
"s": 27309,
"text": "An if statement consists of a boolean expression followed by one or more statements."
},
{
"code": null,
"e": 27510,
"s": 27394,
"text": "An if statement can be followed by an optional else statement, which executes when the boolean expression is false."
},
{
"code": null,
"e": 27593,
"s": 27510,
"text": "You can use one if or else if statement inside another if or else if statement(s)."
},
{
"code": null,
"e": 27682,
"s": 27593,
"text": "A switch statement allows a variable to be tested for equality against a list of values."
},
{
"code": null,
"e": 27803,
"s": 27682,
"text": "A select statement is similar to switch statement with difference that case statements refers to channel communications."
},
{
"code": null,
"e": 28033,
"s": 27803,
"text": "There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 28139,
"s": 28033,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 28320,
"s": 28139,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 28413,
"s": 28320,
"text": "Go programming language provides the following types of loop to handle looping requirements."
},
{
"code": null,
"e": 28522,
"s": 28413,
"text": "It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 28575,
"s": 28522,
"text": "These are one or multiple loops inside any for loop."
},
{
"code": null,
"e": 28750,
"s": 28575,
"text": "Loop control statements change an execution from its normal sequence. When an execution leaves its scope, all automatic objects that were created in that scope are destroyed."
},
{
"code": null,
"e": 28797,
"s": 28750,
"text": "Go supports the following control statements −"
},
{
"code": null,
"e": 28929,
"s": 28797,
"text": "It terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch."
},
{
"code": null,
"e": 29041,
"s": 28929,
"text": "It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 29088,
"s": 29041,
"text": "It transfers control to the labeled statement."
},
{
"code": null,
"e": 29383,
"s": 29088,
"text": "A loop becomes an infinite loop if its condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or by passing true to it."
},
{
"code": null,
"e": 29499,
"s": 29383,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n for true {\n fmt.Printf(\"This loop will run forever.\\n\");\n }\n}"
},
{
"code": null,
"e": 29712,
"s": 29499,
"text": "When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop."
},
{
"code": null,
"e": 29781,
"s": 29712,
"text": "Note − You can terminate an infinite loop by pressing Ctrl + C keys."
},
{
"code": null,
"e": 30111,
"s": 29781,
"text": "A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(). You can divide your code into separate functions. How you divide your code among different functions is up to you, but logically, the division should be such that each function performs a specific task."
},
{
"code": null,
"e": 30269,
"s": 30111,
"text": "A function declaration tells the compiler about a function name, return type, and parameters. A function definition provides the actual body of the function."
},
{
"code": null,
"e": 30619,
"s": 30269,
"text": "The Go standard library provides numerous built-in functions that your program can call. For example, the function len() takes arguments of various types and returns the length of the type. If a string is passed to it, the function returns the length of the string in bytes. If an array is passed to it, the function returns the length of the array."
},
{
"code": null,
"e": 30682,
"s": 30619,
"text": "Functions are also known as method, sub-routine, or procedure."
},
{
"code": null,
"e": 30767,
"s": 30682,
"text": "The general form of a function definition in Go programming language is as follows −"
},
{
"code": null,
"e": 30850,
"s": 30767,
"text": "func function_name( [parameter list] ) [return_types]\n{\n body of the function\n}\n"
},
{
"code": null,
"e": 30989,
"s": 30850,
"text": "A function definition in Go programming language consists of a function header and a function body. Here are all the parts of a function −"
},
{
"code": null,
"e": 31037,
"s": 30989,
"text": "Func − It starts the declaration of a function."
},
{
"code": null,
"e": 31085,
"s": 31037,
"text": "Func − It starts the declaration of a function."
},
{
"code": null,
"e": 31225,
"s": 31085,
"text": "Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature."
},
{
"code": null,
"e": 31365,
"s": 31225,
"text": "Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature."
},
{
"code": null,
"e": 31697,
"s": 31365,
"text": "Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters."
},
{
"code": null,
"e": 32029,
"s": 31697,
"text": "Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters."
},
{
"code": null,
"e": 32286,
"s": 32029,
"text": "Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required."
},
{
"code": null,
"e": 32543,
"s": 32286,
"text": "Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required."
},
{
"code": null,
"e": 32634,
"s": 32543,
"text": "Function Body − It contains a collection of statements that define what the function does."
},
{
"code": null,
"e": 32725,
"s": 32634,
"text": "Function Body − It contains a collection of statements that define what the function does."
},
{
"code": null,
"e": 32873,
"s": 32725,
"text": "The following source code shows a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two −"
},
{
"code": null,
"e": 33107,
"s": 32873,
"text": "/* function returning the max between two numbers */\nfunc max(num1, num2 int) int {\n /* local variable declaration */\n result int\n\n if (num1 > num2) {\n result = num1\n } else {\n result = num2\n }\n return result \n}"
},
{
"code": null,
"e": 33275,
"s": 33107,
"text": "While creating a Go function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task."
},
{
"code": null,
"e": 33562,
"s": 33275,
"text": "When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program."
},
{
"code": null,
"e": 33746,
"s": 33562,
"text": "To call a function, you simply need to pass the required parameters along with its function name. If the function returns a value, then you can store the returned value. For example −"
},
{
"code": null,
"e": 34227,
"s": 33746,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var a int = 100\n var b int = 200\n var ret int\n\n /* calling a function to get max value */\n ret = max(a, b)\n\n fmt.Printf( \"Max value is : %d\\n\", ret )\n}\n\n/* function returning the max between two numbers */\nfunc max(num1, num2 int) int {\n /* local variable declaration */\n var result int\n\n if (num1 > num2) {\n result = num1\n } else {\n result = num2\n }\n return result \n}"
},
{
"code": null,
"e": 34396,
"s": 34227,
"text": "We have kept the max() function along with the main() function and compiled the source code. While running the final executable, it would produce the following result −"
},
{
"code": null,
"e": 34416,
"s": 34396,
"text": "Max value is : 200\n"
},
{
"code": null,
"e": 34472,
"s": 34416,
"text": "A Go function can return multiple values. For example −"
},
{
"code": null,
"e": 34631,
"s": 34472,
"text": "package main\n\nimport \"fmt\"\n\nfunc swap(x, y string) (string, string) {\n return y, x\n}\nfunc main() {\n a, b := swap(\"Mahesh\", \"Kumar\")\n fmt.Println(a, b)\n}"
},
{
"code": null,
"e": 34712,
"s": 34631,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 34726,
"s": 34712,
"text": "Kumar Mahesh\n"
},
{
"code": null,
"e": 34894,
"s": 34726,
"text": "If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function."
},
{
"code": null,
"e": 35040,
"s": 34894,
"text": "The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit."
},
{
"code": null,
"e": 35130,
"s": 35040,
"text": "While calling a function, there are two ways that arguments can be passed to a function −"
},
{
"code": null,
"e": 35320,
"s": 35130,
"text": "This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument."
},
{
"code": null,
"e": 35549,
"s": 35320,
"text": "This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument."
},
{
"code": null,
"e": 35779,
"s": 35549,
"text": "By default, Go uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. The above program, while calling the max() function, used the same method."
},
{
"code": null,
"e": 35825,
"s": 35779,
"text": "A function can be used in the following ways:"
},
{
"code": null,
"e": 35888,
"s": 35825,
"text": "Functions can be created on the fly and can be used as values."
},
{
"code": null,
"e": 35971,
"s": 35888,
"text": "Functions closures are anonymous functions and can be used in dynamic programming."
},
{
"code": null,
"e": 36018,
"s": 35971,
"text": "Methods are special functions with a receiver."
},
{
"code": null,
"e": 36240,
"s": 36018,
"text": "A scope in any programming is a region of the program where a defined variable can exist and beyond that the variable cannot be accessed. There are three places where variables can be declared in Go programming language −"
},
{
"code": null,
"e": 36287,
"s": 36240,
"text": "Inside a function or a block (local variables)"
},
{
"code": null,
"e": 36334,
"s": 36287,
"text": "Inside a function or a block (local variables)"
},
{
"code": null,
"e": 36378,
"s": 36334,
"text": "Outside of all functions (global variables)"
},
{
"code": null,
"e": 36422,
"s": 36378,
"text": "Outside of all functions (global variables)"
},
{
"code": null,
"e": 36483,
"s": 36422,
"text": "In the definition of function parameters (formal parameters)"
},
{
"code": null,
"e": 36544,
"s": 36483,
"text": "In the definition of function parameters (formal parameters)"
},
{
"code": null,
"e": 36628,
"s": 36544,
"text": "Let us find out what are local and global variables and what are formal parameters."
},
{
"code": null,
"e": 36972,
"s": 36628,
"text": "Variables that are declared inside a function or a block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example uses local variables. Here all the variables a, b, and c are local to the main() function."
},
{
"code": null,
"e": 37202,
"s": 36972,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable declaration */\n var a, b, c int \n\n /* actual initialization */\n a = 10\n b = 20\n c = a + b\n\n fmt.Printf (\"value of a = %d, b = %d and c = %d\\n\", a, b, c)\n}"
},
{
"code": null,
"e": 37283,
"s": 37202,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 37319,
"s": 37283,
"text": "value of a = 10, b = 20 and c = 30\n"
},
{
"code": null,
"e": 37553,
"s": 37319,
"text": "Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program."
},
{
"code": null,
"e": 37759,
"s": 37553,
"text": "A global variable can be accessed by any function. That is, a global variable is available for use throughout the program after its declaration. The following example uses both global and local variables −"
},
{
"code": null,
"e": 38031,
"s": 37759,
"text": "package main\n\nimport \"fmt\"\n \n/* global variable declaration */\nvar g int\n \nfunc main() {\n /* local variable declaration */\n var a, b int\n\n /* actual initialization */\n a = 10\n b = 20\n g = a + b\n\n fmt.Printf(\"value of a = %d, b = %d and g = %d\\n\", a, b, g)\n}"
},
{
"code": null,
"e": 38112,
"s": 38031,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 38148,
"s": 38112,
"text": "value of a = 10, b = 20 and g = 30\n"
},
{
"code": null,
"e": 38298,
"s": 38148,
"text": "A program can have the same name for local and global variables but the value of the local variable inside a function takes preference. For example −"
},
{
"code": null,
"e": 38490,
"s": 38298,
"text": "package main\n\nimport \"fmt\"\n \n/* global variable declaration */\nvar g int = 20\n \nfunc main() {\n /* local variable declaration */\n var g int = 10\n \n fmt.Printf (\"value of g = %d\\n\", g)\n}"
},
{
"code": null,
"e": 38571,
"s": 38490,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 38588,
"s": 38571,
"text": "value of g = 10\n"
},
{
"code": null,
"e": 38725,
"s": 38588,
"text": "Formal parameters are treated as local variables with-in that function and they take preference over the global variables. For example −"
},
{
"code": null,
"e": 39226,
"s": 38725,
"text": "package main\n\nimport \"fmt\"\n \n/* global variable declaration */\nvar a int = 20;\n \nfunc main() {\n /* local variable declaration in main function */\n var a int = 10\n var b int = 20\n var c int = 0\n\n fmt.Printf(\"value of a in main() = %d\\n\", a);\n c = sum( a, b);\n fmt.Printf(\"value of c in main() = %d\\n\", c);\n}\n/* function to add two integers */\nfunc sum(a, b int) int {\n fmt.Printf(\"value of a in sum() = %d\\n\", a);\n fmt.Printf(\"value of b in sum() = %d\\n\", b);\n\n return a + b;\n}"
},
{
"code": null,
"e": 39307,
"s": 39226,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 39410,
"s": 39307,
"text": "value of a in main() = 10\nvalue of a in sum() = 10\nvalue of b in sum() = 20\nvalue of c in main() = 30\n"
},
{
"code": null,
"e": 39528,
"s": 39410,
"text": "Local and global variables are initialized to their default value, which is 0; while pointers are initialized to nil."
},
{
"code": null,
"e": 39727,
"s": 39528,
"text": "Strings, which are widely used in Go programming, are a readonly slice of bytes. In the Go programming language, strings are slices. The Go platform provides various libraries to manipulate strings."
},
{
"code": null,
"e": 39735,
"s": 39727,
"text": "unicode"
},
{
"code": null,
"e": 39742,
"s": 39735,
"text": "regexp"
},
{
"code": null,
"e": 39750,
"s": 39742,
"text": "strings"
},
{
"code": null,
"e": 39803,
"s": 39750,
"text": "The most direct way to create a string is to write −"
},
{
"code": null,
"e": 39834,
"s": 39803,
"text": "var greeting = \"Hello world!\"\n"
},
{
"code": null,
"e": 39970,
"s": 39834,
"text": "Whenever it encounters a string literal in your code, the compiler creates a string object with its value in this case, \"Hello world!'."
},
{
"code": null,
"e": 40063,
"s": 39970,
"text": "A string literal holds a valid UTF-8 sequences called runes. A String holds arbitrary bytes."
},
{
"code": null,
"e": 40649,
"s": 40063,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var greeting = \"Hello world!\"\n \n fmt.Printf(\"normal string: \")\n fmt.Printf(\"%s\", greeting)\n fmt.Printf(\"\\n\")\n fmt.Printf(\"hex bytes: \")\n \n for i := 0; i < len(greeting); i++ {\n fmt.Printf(\"%x \", greeting[i])\n }\n fmt.Printf(\"\\n\")\n \n const sampleText = \"\\xbd\\xb2\\x3d\\xbc\\x20\\xe2\\x8c\\x98\" \n /*q flag escapes unprintable characters, with + flag it escapses non-ascii \n characters as well to make output unambigous \n */\n fmt.Printf(\"quoted string: \")\n fmt.Printf(\"%+q\", sampleText)\n fmt.Printf(\"\\n\") \n}"
},
{
"code": null,
"e": 40691,
"s": 40649,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 40806,
"s": 40691,
"text": "normal string: Hello world!\nhex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 \nquoted string: \"\\xbd\\xb2=\\xbc \\u2318\"\n"
},
{
"code": null,
"e": 40909,
"s": 40806,
"text": "Note − The string literal is immutable, so that once it is created a string literal cannot be changed."
},
{
"code": null,
"e": 40986,
"s": 40909,
"text": "len(str) method returns the number of bytes contained in the string literal."
},
{
"code": null,
"e": 41136,
"s": 40986,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var greeting = \"Hello world!\"\n \n fmt.Printf(\"String Length is: \")\n fmt.Println(len(greeting)) \n}"
},
{
"code": null,
"e": 41178,
"s": 41136,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 41201,
"s": 41178,
"text": "String Length is : 12\n"
},
{
"code": null,
"e": 41281,
"s": 41201,
"text": "The strings package includes a method join for concatenating multiple strings −"
},
{
"code": null,
"e": 41308,
"s": 41281,
"text": "strings.Join(sample, \" \")\n"
},
{
"code": null,
"e": 41454,
"s": 41308,
"text": "Join concatenates the elements of an array to create a single string. Second parameter is seperator which is placed between element of the array."
},
{
"code": null,
"e": 41493,
"s": 41454,
"text": "Let us look at the following example −"
},
{
"code": null,
"e": 41655,
"s": 41493,
"text": "package main\n\nimport (\"fmt\" \"math\" )\"fmt\" \"strings\")\n\nfunc main() {\n greetings := []string{\"Hello\",\"world!\"} \n fmt.Println(strings.Join(greetings, \" \"))\n}"
},
{
"code": null,
"e": 41697,
"s": 41655,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 41711,
"s": 41697,
"text": "Hello world!\n"
},
{
"code": null,
"e": 42004,
"s": 41711,
"text": "Go programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 42283,
"s": 42004,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index."
},
{
"code": null,
"e": 42431,
"s": 42283,
"text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element."
},
{
"code": null,
"e": 42567,
"s": 42431,
"text": "To declare an array in Go, a programmer specifies the type of the elements and the number of elements required by an array as follows −"
},
{
"code": null,
"e": 42607,
"s": 42567,
"text": "var variable_name [SIZE] variable_type\n"
},
{
"code": null,
"e": 42846,
"s": 42607,
"text": "This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Go data type. For example, to declare a 10-element array called balance of type float32, use this statement −"
},
{
"code": null,
"e": 42872,
"s": 42846,
"text": "var balance [10] float32\n"
},
{
"code": null,
"e": 42944,
"s": 42872,
"text": "Here, balance is a variable array that can hold up to 10 float numbers."
},
{
"code": null,
"e": 43034,
"s": 42944,
"text": "You can initialize array in Go either one by one or using a single statement as follows −"
},
{
"code": null,
"e": 43089,
"s": 43034,
"text": "var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}\n"
},
{
"code": null,
"e": 43234,
"s": 43089,
"text": "The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]."
},
{
"code": null,
"e": 43360,
"s": 43234,
"text": "If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −"
},
{
"code": null,
"e": 43414,
"s": 43360,
"text": "var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}\n"
},
{
"code": null,
"e": 43555,
"s": 43414,
"text": "You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −"
},
{
"code": null,
"e": 43574,
"s": 43555,
"text": "balance[4] = 50.0\n"
},
{
"code": null,
"e": 43892,
"s": 43574,
"text": "The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above −"
},
{
"code": null,
"e": 44058,
"s": 43892,
"text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −"
},
{
"code": null,
"e": 44087,
"s": 44058,
"text": "float32 salary = balance[9]\n"
},
{
"code": null,
"e": 44316,
"s": 44087,
"text": "The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays −"
},
{
"code": null,
"e": 44704,
"s": 44316,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var n [10]int /* n is an array of 10 integers */\n var i,j int\n\n /* initialize elements of array n to 0 */ \n for i = 0; i < 10; i++ {\n n[i] = i + 100 /* set element at location i to i + 100 */\n }\n /* output each array element's value */\n for j = 0; j < 10; j++ {\n fmt.Printf(\"Element[%d] = %d\\n\", j, n[j] )\n }\n}"
},
{
"code": null,
"e": 44785,
"s": 44704,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 44956,
"s": 44785,
"text": "Element[0] = 100\nElement[1] = 101\nElement[2] = 102\nElement[3] = 103\nElement[4] = 104\nElement[5] = 105\nElement[6] = 106\nElement[7] = 107\nElement[8] = 108\nElement[9] = 109\n"
},
{
"code": null,
"e": 45045,
"s": 44956,
"text": "There are important concepts related to array which should be clear to a Go programmer −"
},
{
"code": null,
"e": 45158,
"s": 45045,
"text": "Go supports multidimensional arrays. The simplest form of a multidimensional array is the two-dimensional array."
},
{
"code": null,
"e": 45258,
"s": 45158,
"text": "You can pass to the function a pointer to an array by specifying the array's name without an index."
},
{
"code": null,
"e": 45532,
"s": 45258,
"text": "Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Go programmer."
},
{
"code": null,
"e": 45807,
"s": 45532,
"text": "As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined −"
},
{
"code": null,
"e": 45923,
"s": 45807,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a int = 10 \n fmt.Printf(\"Address of a variable: %x\\n\", &a )\n}"
},
{
"code": null,
"e": 46004,
"s": 45923,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 46037,
"s": 46004,
"text": "Address of a variable: 10328000\n"
},
{
"code": null,
"e": 46134,
"s": 46037,
"text": "So you understood what is memory address and how to access it. Now let us see what pointers are."
},
{
"code": null,
"e": 46418,
"s": 46134,
"text": "A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is −"
},
{
"code": null,
"e": 46442,
"s": 46418,
"text": "var var_name *var-type\n"
},
{
"code": null,
"e": 46799,
"s": 46442,
"text": "Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −"
},
{
"code": null,
"e": 46891,
"s": 46799,
"text": "var ip *int /* pointer to an integer */\nvar fp *float32 /* pointer to a float */\n"
},
{
"code": null,
"e": 47187,
"s": 46891,
"text": "The actual data type of the value of all pointers, whether integer, float, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to."
},
{
"code": null,
"e": 47424,
"s": 47187,
"text": "There are a few important operations, which we frequently perform with pointers: (a) we define pointer variables, (b) assign the address of a variable to a pointer, and (c) access the value at the address stored in the pointer variable."
},
{
"code": null,
"e": 47645,
"s": 47424,
"text": "All these operations are carried out using the unary operator * that returns the value of the variable located at the address specified by its operand. The following example demonstrates how to perform these operations −"
},
{
"code": null,
"e": 48106,
"s": 47645,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a int = 20 /* actual variable declaration */\n var ip *int /* pointer variable declaration */\n\n ip = &a /* store address of a in pointer variable*/\n\n fmt.Printf(\"Address of a variable: %x\\n\", &a )\n\n /* address stored in pointer variable */\n fmt.Printf(\"Address stored in ip variable: %x\\n\", ip )\n\n /* access the value using the pointer */\n fmt.Printf(\"Value of *ip variable: %d\\n\", *ip )\n}"
},
{
"code": null,
"e": 48187,
"s": 48106,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 48288,
"s": 48187,
"text": "Address of var variable: 10328000\nAddress stored in ip variable: 10328000\nValue of *ip variable: 20\n"
},
{
"code": null,
"e": 48501,
"s": 48288,
"text": "Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer."
},
{
"code": null,
"e": 48624,
"s": 48501,
"text": "The nil pointer is a constant with a value of zero defined in several standard libraries. Consider the following program −"
},
{
"code": null,
"e": 48737,
"s": 48624,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var ptr *int\n\n fmt.Printf(\"The value of ptr is : %x\\n\", ptr )\n}"
},
{
"code": null,
"e": 48818,
"s": 48737,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 48841,
"s": 48818,
"text": "The value of ptr is 0\n"
},
{
"code": null,
"e": 49230,
"s": 48841,
"text": "On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the nil (zero) value, it is assumed to point to nothing."
},
{
"code": null,
"e": 49298,
"s": 49230,
"text": "To check for a nil pointer you can use an if statement as follows −"
},
{
"code": null,
"e": 49395,
"s": 49298,
"text": "if(ptr != nil) /* succeeds if p is not nil */\nif(ptr == nil) /* succeeds if p is null */\n"
},
{
"code": null,
"e": 49551,
"s": 49395,
"text": "Pointers have many but easy concepts and they are very important to Go programming. The following concepts of pointers should be clear to a Go programmer −"
},
{
"code": null,
"e": 49603,
"s": 49551,
"text": "You can define arrays to hold a number of pointers."
},
{
"code": null,
"e": 49657,
"s": 49603,
"text": "Go allows you to have pointer on a pointer and so on."
},
{
"code": null,
"e": 49798,
"s": 49657,
"text": "Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function."
},
{
"code": null,
"e": 50021,
"s": 49798,
"text": "Go arrays allow you to define variables that can hold several data items of the same kind. Structure is another user-defined data type available in Go programming, which allows you to combine data items of different kinds."
},
{
"code": null,
"e": 50186,
"s": 50021,
"text": "Structures are used to represent a record. Suppose you want to keep track of the books in a library. You might want to track the following attributes of each book −"
},
{
"code": null,
"e": 50192,
"s": 50186,
"text": "Title"
},
{
"code": null,
"e": 50199,
"s": 50192,
"text": "Author"
},
{
"code": null,
"e": 50207,
"s": 50199,
"text": "Subject"
},
{
"code": null,
"e": 50215,
"s": 50207,
"text": "Book ID"
},
{
"code": null,
"e": 50265,
"s": 50215,
"text": "In such a scenario, structures are highly useful."
},
{
"code": null,
"e": 50541,
"s": 50265,
"text": "To define a structure, you must use type and struct statements. The struct statement defines a new data type, with multiple members for your program. The type statement binds a name with the type which is struct in our case. The format of the struct statement is as follows −"
},
{
"code": null,
"e": 50651,
"s": 50541,
"text": "type struct_variable_type struct {\n member definition;\n member definition;\n ...\n member definition;\n}"
},
{
"code": null,
"e": 50762,
"s": 50651,
"text": "Once a structure type is defined, it can be used to declare variables of that type using the following syntax."
},
{
"code": null,
"e": 50830,
"s": 50762,
"text": "variable_name := structure_variable_type {value1, value2...valuen}\n"
},
{
"code": null,
"e": 51163,
"s": 50830,
"text": "To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. The following example explains how to use a structure −"
},
{
"code": null,
"e": 52227,
"s": 51163,
"text": "package main\n\nimport \"fmt\"\n\ntype Books struct {\n title string\n author string\n subject string\n book_id int\n}\nfunc main() {\n var Book1 Books /* Declare Book1 of type Book */\n var Book2 Books /* Declare Book2 of type Book */\n \n /* book 1 specification */\n Book1.title = \"Go Programming\"\n Book1.author = \"Mahesh Kumar\"\n Book1.subject = \"Go Programming Tutorial\"\n Book1.book_id = 6495407\n\n /* book 2 specification */\n Book2.title = \"Telecom Billing\"\n Book2.author = \"Zara Ali\"\n Book2.subject = \"Telecom Billing Tutorial\"\n Book2.book_id = 6495700\n \n /* print Book1 info */\n fmt.Printf( \"Book 1 title : %s\\n\", Book1.title)\n fmt.Printf( \"Book 1 author : %s\\n\", Book1.author)\n fmt.Printf( \"Book 1 subject : %s\\n\", Book1.subject)\n fmt.Printf( \"Book 1 book_id : %d\\n\", Book1.book_id)\n\n /* print Book2 info */\n fmt.Printf( \"Book 2 title : %s\\n\", Book2.title)\n fmt.Printf( \"Book 2 author : %s\\n\", Book2.author)\n fmt.Printf( \"Book 2 subject : %s\\n\", Book2.subject)\n fmt.Printf( \"Book 2 book_id : %d\\n\", Book2.book_id)\n}"
},
{
"code": null,
"e": 52308,
"s": 52227,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 52587,
"s": 52308,
"text": "Book 1 title : Go Programming\nBook 1 author : Mahesh Kumar\nBook 1 subject : Go Programming Tutorial\nBook 1 book_id : 6495407\nBook 2 title : Telecom Billing\nBook 2 author : Zara Ali\nBook 2 subject : Telecom Billing Tutorial\nBook 2 book_id : 6495700\n"
},
{
"code": null,
"e": 52785,
"s": 52587,
"text": "You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the same way as you did in the above example −"
},
{
"code": null,
"e": 53700,
"s": 52785,
"text": "package main\n\nimport \"fmt\"\n\ntype Books struct {\n title string\n author string\n subject string\n book_id int\n}\nfunc main() {\n var Book1 Books /* Declare Book1 of type Book */\n var Book2 Books /* Declare Book2 of type Book */\n \n /* book 1 specification */\n Book1.title = \"Go Programming\"\n Book1.author = \"Mahesh Kumar\"\n Book1.subject = \"Go Programming Tutorial\"\n Book1.book_id = 6495407\n\n /* book 2 specification */\n Book2.title = \"Telecom Billing\"\n Book2.author = \"Zara Ali\"\n Book2.subject = \"Telecom Billing Tutorial\"\n Book2.book_id = 6495700\n \n /* print Book1 info */\n printBook(Book1)\n\n /* print Book2 info */\n printBook(Book2)\n}\nfunc printBook( book Books ) {\n fmt.Printf( \"Book title : %s\\n\", book.title);\n fmt.Printf( \"Book author : %s\\n\", book.author);\n fmt.Printf( \"Book subject : %s\\n\", book.subject);\n fmt.Printf( \"Book book_id : %d\\n\", book.book_id);\n}"
},
{
"code": null,
"e": 53781,
"s": 53700,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 54036,
"s": 53781,
"text": "Book title : Go Programming\nBook author : Mahesh Kumar\nBook subject : Go Programming Tutorial\nBook book_id : 6495407\nBook title : Telecom Billing\nBook author : Zara Ali\nBook subject : Telecom Billing Tutorial\nBook book_id : 6495700\n"
},
{
"code": null,
"e": 54147,
"s": 54036,
"text": "You can define pointers to structures in the same way as you define pointer to any other variable as follows −"
},
{
"code": null,
"e": 54174,
"s": 54147,
"text": "var struct_pointer *Books\n"
},
{
"code": null,
"e": 54375,
"s": 54174,
"text": "Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −"
},
{
"code": null,
"e": 54401,
"s": 54375,
"text": "struct_pointer = &Book1;\n"
},
{
"code": null,
"e": 54516,
"s": 54401,
"text": "To access the members of a structure using a pointer to that structure, you must use the \".\" operator as follows −"
},
{
"code": null,
"e": 54539,
"s": 54516,
"text": "struct_pointer.title;\n"
},
{
"code": null,
"e": 54599,
"s": 54539,
"text": "Let us re-write the above example using structure pointer −"
},
{
"code": null,
"e": 55515,
"s": 54599,
"text": "package main\n\nimport \"fmt\"\n\ntype Books struct {\n title string\n author string\n subject string\n book_id int\n}\nfunc main() {\n var Book1 Books /* Declare Book1 of type Book */\n var Book2 Books /* Declare Book2 of type Book */\n \n /* book 1 specification */\n Book1.title = \"Go Programming\"\n Book1.author = \"Mahesh Kumar\"\n Book1.subject = \"Go Programming Tutorial\"\n Book1.book_id = 6495407\n\n /* book 2 specification */\n Book2.title = \"Telecom Billing\"\n Book2.author = \"Zara Ali\"\n Book2.subject = \"Telecom Billing Tutorial\"\n Book2.book_id = 6495700\n \n /* print Book1 info */\n printBook(&Book1)\n\n /* print Book2 info */\n printBook(&Book2)\n}\nfunc printBook( book *Books ) {\n fmt.Printf( \"Book title : %s\\n\", book.title);\n fmt.Printf( \"Book author : %s\\n\", book.author);\n fmt.Printf( \"Book subject : %s\\n\", book.subject);\n fmt.Printf( \"Book book_id : %d\\n\", book.book_id);\n}"
},
{
"code": null,
"e": 55596,
"s": 55515,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 55851,
"s": 55596,
"text": "Book title : Go Programming\nBook author : Mahesh Kumar\nBook subject : Go Programming Tutorial\nBook book_id : 6495407\nBook title : Telecom Billing\nBook author : Zara Ali\nBook subject : Telecom Billing Tutorial\nBook book_id : 6495700\n"
},
{
"code": null,
"e": 56214,
"s": 55851,
"text": "Go Slice is an abstraction over Go Array. Go Array allows you to define variables that can hold several data items of the same kind but it does not provide any inbuilt method to increase its size dynamically or get a sub-array of its own. Slices overcome this limitation. It provides many utility functions required on Array and is widely used in Go programming."
},
{
"code": null,
"e": 56353,
"s": 56214,
"text": "To define a slice, you can declare it as an array without specifying its size. Alternatively, you can use make function to create a slice."
},
{
"code": null,
"e": 56505,
"s": 56353,
"text": "var numbers []int /* a slice of unspecified size */\n/* numbers == []int{0,0,0,0,0}*/\nnumbers = make([]int,5,5) /* a slice of length 5 and capacity 5*/\n"
},
{
"code": null,
"e": 56813,
"s": 56505,
"text": "A slice is an abstraction over array. It actually uses arrays as an underlying structure. The len() function returns the elements presents in the slice where cap() function returns the capacity of the slice (i.e., how many elements it can be accommodate). The following example explains the usage of slice −"
},
{
"code": null,
"e": 56999,
"s": 56813,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var numbers = make([]int,3,5)\n printSlice(numbers)\n}\nfunc printSlice(x []int){\n fmt.Printf(\"len=%d cap=%d slice=%v\\n\",len(x),cap(x),x)\n}"
},
{
"code": null,
"e": 57080,
"s": 56999,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 57113,
"s": 57080,
"text": "len = 3 cap = 5 slice = [0 0 0]\n"
},
{
"code": null,
"e": 57243,
"s": 57113,
"text": "If a slice is declared with no inputs, then by default, it is initialized as nil. Its length and capacity are zero. For example −"
},
{
"code": null,
"e": 57490,
"s": 57243,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var numbers []int\n printSlice(numbers)\n \n if(numbers == nil){\n fmt.Printf(\"slice is nil\")\n }\n}\nfunc printSlice(x []int){\n fmt.Printf(\"len = %d cap = %d slice = %v\\n\", len(x), cap(x),x)\n}"
},
{
"code": null,
"e": 57571,
"s": 57490,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 57612,
"s": 57571,
"text": "len = 0 cap = 0 slice = []\nslice is nil\n"
},
{
"code": null,
"e": 57741,
"s": 57612,
"text": "Slice allows lower-bound and upper bound to be specified to get the subslice of it using[lower-bound:upper-bound]. For example −"
},
{
"code": null,
"e": 58692,
"s": 57741,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* create a slice */\n numbers := []int{0,1,2,3,4,5,6,7,8} \n printSlice(numbers)\n \n /* print the original slice */\n fmt.Println(\"numbers ==\", numbers)\n \n /* print the sub slice starting from index 1(included) to index 4(excluded)*/\n fmt.Println(\"numbers[1:4] ==\", numbers[1:4])\n \n /* missing lower bound implies 0*/\n fmt.Println(\"numbers[:3] ==\", numbers[:3])\n \n /* missing upper bound implies len(s)*/\n fmt.Println(\"numbers[4:] ==\", numbers[4:])\n \n numbers1 := make([]int,0,5)\n printSlice(numbers1)\n \n /* print the sub slice starting from index 0(included) to index 2(excluded) */\n number2 := numbers[:2]\n printSlice(number2)\n \n /* print the sub slice starting from index 2(included) to index 5(excluded) */\n number3 := numbers[2:5]\n printSlice(number3)\n \n}\nfunc printSlice(x []int){\n fmt.Printf(\"len = %d cap = %d slice = %v\\n\", len(x), cap(x),x)\n}"
},
{
"code": null,
"e": 58773,
"s": 58692,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 59013,
"s": 58773,
"text": "len = 9 cap = 9 slice = [0 1 2 3 4 5 6 7 8]\nnumbers == [0 1 2 3 4 5 6 7 8]\nnumbers[1:4] == [1 2 3]\nnumbers[:3] == [0 1 2]\nnumbers[4:] == [4 5 6 7 8]\nlen = 0 cap = 5 slice = []\nlen = 2 cap = 9 slice = [0 1]\nlen = 3 cap = 7 slice = [2 3 4]\n"
},
{
"code": null,
"e": 59185,
"s": 59013,
"text": "One can increase the capacity of a slice using the append() function. Using copy()function, the contents of a source slice are copied to a destination slice. For example −"
},
{
"code": null,
"e": 59889,
"s": 59185,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var numbers []int\n printSlice(numbers)\n \n /* append allows nil slice */\n numbers = append(numbers, 0)\n printSlice(numbers)\n \n /* add one element to slice*/\n numbers = append(numbers, 1)\n printSlice(numbers)\n \n /* add more than one element at a time*/\n numbers = append(numbers, 2,3,4)\n printSlice(numbers)\n \n /* create a slice numbers1 with double the capacity of earlier slice*/\n numbers1 := make([]int, len(numbers), (cap(numbers))*2)\n \n /* copy content of numbers to numbers1 */\n copy(numbers1,numbers)\n printSlice(numbers1) \n}\nfunc printSlice(x []int){\n fmt.Printf(\"len=%d cap=%d slice=%v\\n\",len(x),cap(x),x)\n}"
},
{
"code": null,
"e": 59970,
"s": 59889,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 60129,
"s": 59970,
"text": "len = 0 cap = 0 slice = []\nlen = 1 cap = 2 slice = [0]\nlen = 2 cap = 2 slice = [0 1]\nlen = 5 cap = 8 slice = [0 1 2 3 4]\nlen = 5 cap = 16 slice = [0 1 2 3 4]\n"
},
{
"code": null,
"e": 60495,
"s": 60129,
"text": "The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table."
},
{
"code": null,
"e": 60544,
"s": 60495,
"text": "The following paragraph shows how to use range −"
},
{
"code": null,
"e": 61185,
"s": 60544,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* create a slice */\n numbers := []int{0,1,2,3,4,5,6,7,8} \n \n /* print the numbers */\n for i:= range numbers {\n fmt.Println(\"Slice item\",i,\"is\",numbers[i])\n }\n \n /* create a map*/\n countryCapitalMap := map[string] string {\"France\":\"Paris\",\"Italy\":\"Rome\",\"Japan\":\"Tokyo\"}\n \n /* print map using keys*/\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n \n /* print map using key-value*/\n for country,capital := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",capital)\n }\n}"
},
{
"code": null,
"e": 61266,
"s": 61185,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 61585,
"s": 61266,
"text": "Slice item 0 is 0\nSlice item 1 is 1\nSlice item 2 is 2\nSlice item 3 is 3\nSlice item 4 is 4\nSlice item 5 is 5\nSlice item 6 is 6\nSlice item 7 is 7\nSlice item 8 is 8\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\n"
},
{
"code": null,
"e": 61869,
"s": 61585,
"text": "Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key."
},
{
"code": null,
"e": 61913,
"s": 61869,
"text": "You must use make function to create a map."
},
{
"code": null,
"e": 62134,
"s": 61913,
"text": "/* declare a variable, by default map will be nil*/\nvar map_variable map[key_data_type]value_data_type\n\n/* define the map as nil map can not be assigned any value*/\nmap_variable = make(map[key_data_type]value_data_type)\n"
},
{
"code": null,
"e": 62198,
"s": 62134,
"text": "The following example illustrates how to create and use a map −"
},
{
"code": null,
"e": 63045,
"s": 62198,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var countryCapitalMap map[string]string\n /* create a map*/\n countryCapitalMap = make(map[string]string)\n \n /* insert key-value pairs in the map*/\n countryCapitalMap[\"France\"] = \"Paris\"\n countryCapitalMap[\"Italy\"] = \"Rome\"\n countryCapitalMap[\"Japan\"] = \"Tokyo\"\n countryCapitalMap[\"India\"] = \"New Delhi\"\n \n /* print map using keys*/\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n \n /* test if entry is present in the map or not*/\n capital, ok := countryCapitalMap[\"United States\"]\n \n /* if ok is true, entry is present otherwise entry is absent*/\n if(ok){\n fmt.Println(\"Capital of United States is\", capital) \n } else {\n fmt.Println(\"Capital of United States is not present\") \n }\n}"
},
{
"code": null,
"e": 63126,
"s": 63045,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 63275,
"s": 63126,
"text": "Capital of India is New Delhi\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\nCapital of United States is not present\n"
},
{
"code": null,
"e": 63416,
"s": 63275,
"text": "delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example −"
},
{
"code": null,
"e": 64076,
"s": 63416,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() { \n /* create a map*/\n countryCapitalMap := map[string] string {\"France\":\"Paris\",\"Italy\":\"Rome\",\"Japan\":\"Tokyo\",\"India\":\"New Delhi\"}\n \n fmt.Println(\"Original map\") \n \n /* print map */\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n \n /* delete an entry */\n delete(countryCapitalMap,\"France\");\n fmt.Println(\"Entry for France is deleted\") \n \n fmt.Println(\"Updated map\") \n \n /* print map */\n for country := range countryCapitalMap {\n fmt.Println(\"Capital of\",country,\"is\",countryCapitalMap[country])\n }\n}"
},
{
"code": null,
"e": 64157,
"s": 64076,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 64400,
"s": 64157,
"text": "Original Map\nCapital of France is Paris\nCapital of Italy is Rome\nCapital of Japan is Tokyo\nCapital of India is New Delhi\nEntry for France is deleted\nUpdated Map\nCapital of India is New Delhi\nCapital of Italy is Rome\nCapital of Japan is Tokyo\n"
},
{
"code": null,
"e": 64675,
"s": 64400,
"text": "Recursion is the process of repeating items in a self-similar way. The same concept applies in programming languages as well. If a program allows to call a function inside the same function, then it is called a recursive function call. Take a look at the following example −"
},
{
"code": null,
"e": 64770,
"s": 64675,
"text": "func recursion() {\n recursion() /* function calls itself */\n}\nfunc main() {\n recursion()\n}"
},
{
"code": null,
"e": 65021,
"s": 64770,
"text": "The Go programming language supports recursion. That is, it allows a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go on to become an infinite loop."
},
{
"code": null,
"e": 65172,
"s": 65021,
"text": "Recursive functions are very useful to solve many mathematical problems such as calculating factorial of a number, generating a Fibonacci series, etc."
},
{
"code": null,
"e": 65266,
"s": 65172,
"text": "The following example calculates the factorial of a given number using a recursive function −"
},
{
"code": null,
"e": 65481,
"s": 65266,
"text": "package main\n\nimport \"fmt\"\n\nfunc factorial(i int)int {\n if(i <= 1) {\n return 1\n }\n return i * factorial(i - 1)\n}\nfunc main() { \n var i int = 15\n fmt.Printf(\"Factorial of %d is %d\", i, factorial(i))\n}"
},
{
"code": null,
"e": 65562,
"s": 65481,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 65596,
"s": 65562,
"text": "Factorial of 15 is 1307674368000\n"
},
{
"code": null,
"e": 65706,
"s": 65596,
"text": "The following example shows how to generate a Fibonacci series of a given number using a recursive function −"
},
{
"code": null,
"e": 65978,
"s": 65706,
"text": "package main\n\nimport \"fmt\"\n\nfunc fibonaci(i int) (ret int) {\n if i == 0 {\n return 0\n }\n if i == 1 {\n return 1\n }\n return fibonaci(i-1) + fibonaci(i-2)\n}\nfunc main() {\n var i int\n for i = 0; i < 10; i++ {\n fmt.Printf(\"%d \", fibonaci(i))\n }\n}"
},
{
"code": null,
"e": 66059,
"s": 65978,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 66084,
"s": 66059,
"text": "0 1 1 2 3 5 8 13 21 34 \n"
},
{
"code": null,
"e": 66374,
"s": 66084,
"text": "Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator. Its syntax is as follows −"
},
{
"code": null,
"e": 66397,
"s": 66374,
"text": "type_name(expression)\n"
},
{
"code": null,
"e": 66555,
"s": 66397,
"text": "Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating number operation."
},
{
"code": null,
"e": 66745,
"s": 66555,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var sum int = 17\n var count int = 5\n var mean float32\n \n mean = float32(sum)/float32(count)\n fmt.Printf(\"Value of mean : %f\\n\",mean)\n}"
},
{
"code": null,
"e": 66826,
"s": 66745,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 66852,
"s": 66826,
"text": "Value of mean : 3.400000\n"
},
{
"code": null,
"e": 67077,
"s": 66852,
"text": "Go programming provides another data type called interfaces which represents a set of method signatures. The struct data type implements these interfaces to have method definitions for the method signature of the interfaces."
},
{
"code": null,
"e": 67581,
"s": 67077,
"text": "/* define an interface */\ntype interface_name interface {\n method_name1 [return_type]\n method_name2 [return_type]\n method_name3 [return_type]\n ...\n method_namen [return_type]\n}\n\n/* define a struct */\ntype struct_name struct {\n /* variables */\n}\n\n/* implement interface methods*/\nfunc (struct_name_variable struct_name) method_name1() [return_type] {\n /* method implementation */\n}\n...\nfunc (struct_name_variable struct_name) method_namen() [return_type] {\n /* method implementation */\n}\n"
},
{
"code": null,
"e": 68449,
"s": 67581,
"text": "package main\n\nimport (\n \"fmt\" \n \"math\" \n)\n\n/* define an interface */\ntype Shape interface {\n area() float64\n}\n\n/* define a circle */\ntype Circle struct {\n x,y,radius float64\n}\n\n/* define a rectangle */\ntype Rectangle struct {\n width, height float64\n}\n\n/* define a method for circle (implementation of Shape.area())*/\nfunc(circle Circle) area() float64 {\n return math.Pi * circle.radius * circle.radius\n}\n\n/* define a method for rectangle (implementation of Shape.area())*/\nfunc(rect Rectangle) area() float64 {\n return rect.width * rect.height\n}\n\n/* define a method for shape */\nfunc getArea(shape Shape) float64 {\n return shape.area()\n}\n\nfunc main() {\n circle := Circle{x:0,y:0,radius:5}\n rectangle := Rectangle {width:10, height:5}\n \n fmt.Printf(\"Circle area: %f\\n\",getArea(circle))\n fmt.Printf(\"Rectangle area: %f\\n\",getArea(rectangle))\n}"
},
{
"code": null,
"e": 68530,
"s": 68449,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 68580,
"s": 68530,
"text": "Circle area: 78.539816\nRectangle area: 50.000000\n"
},
{
"code": null,
"e": 68710,
"s": 68580,
"text": "Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration −"
},
{
"code": null,
"e": 68754,
"s": 68710,
"text": "type error interface {\n Error() string\n}\n"
},
{
"code": null,
"e": 68873,
"s": 68754,
"text": "Functions normally return error as last return value. Use errors.New to construct a basic error message as following −"
},
{
"code": null,
"e": 69040,
"s": 68873,
"text": "func Sqrt(value float64)(float64, error) {\n if(value < 0){\n return 0, errors.New(\"Math: negative number passed to Sqrt\")\n }\n return math.Sqrt(value), nil\n}"
},
{
"code": null,
"e": 69076,
"s": 69040,
"text": "Use return value and error message."
},
{
"code": null,
"e": 69138,
"s": 69076,
"text": "result, err:= Sqrt(-1)\n\nif err != nil {\n fmt.Println(err)\n}"
},
{
"code": null,
"e": 69606,
"s": 69138,
"text": "package main\n\nimport \"errors\"\nimport \"fmt\"\nimport \"math\"\n\nfunc Sqrt(value float64)(float64, error) {\n if(value < 0){\n return 0, errors.New(\"Math: negative number passed to Sqrt\")\n }\n return math.Sqrt(value), nil\n}\nfunc main() {\n result, err:= Sqrt(-1)\n\n if err != nil {\n fmt.Println(err)\n } else {\n fmt.Println(result)\n }\n \n result, err = Sqrt(9)\n\n if err != nil {\n fmt.Println(err)\n } else {\n fmt.Println(result)\n }\n}"
},
{
"code": null,
"e": 69687,
"s": 69606,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 69727,
"s": 69687,
"text": "Math: negative number passed to Sqrt\n3\n"
},
{
"code": null,
"e": 69762,
"s": 69727,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 69775,
"s": 69762,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 69810,
"s": 69775,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 69824,
"s": 69810,
"text": " Asif Hussain"
},
{
"code": null,
"e": 69857,
"s": 69824,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 69876,
"s": 69857,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 69909,
"s": 69876,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 69928,
"s": 69909,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 69960,
"s": 69928,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 69977,
"s": 69960,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 70010,
"s": 69977,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 70029,
"s": 70010,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 70036,
"s": 70029,
"text": " Print"
},
{
"code": null,
"e": 70047,
"s": 70036,
"text": " Add Notes"
}
] |
Comparing enum members in C# | To compare enum members, use the Enum.CompareTo() method.
Firstly, set the values for students.
enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };
Now use the compareTo() method to compare one enum value with another.
Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );
The following is the code to compare enum members in C#.
Live Demo
using System;
public class Demo {
enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };
public static void Main() {
StudentRank student1 = StudentRank.Tom;
StudentRank student2 = StudentRank.Henry;
StudentRank student3 = StudentRank.Amit;
Console.WriteLine("{0} has more rank than {1}?", student1, student2);
Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );
}
}
Tom has more rank than Henry?
Yes | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "To compare enum members, use the Enum.CompareTo() method."
},
{
"code": null,
"e": 1158,
"s": 1120,
"text": "Firstly, set the values for students."
},
{
"code": null,
"e": 1209,
"s": 1158,
"text": "enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };"
},
{
"code": null,
"e": 1280,
"s": 1209,
"text": "Now use the compareTo() method to compare one enum value with another."
},
{
"code": null,
"e": 1381,
"s": 1280,
"text": "Console.WriteLine( \"{0}{1}\", student1.CompareTo(student2) > 0 ? \"Yes\" : \"No\", Environment.NewLine );"
},
{
"code": null,
"e": 1438,
"s": 1381,
"text": "The following is the code to compare enum members in C#."
},
{
"code": null,
"e": 1449,
"s": 1438,
"text": " Live Demo"
},
{
"code": null,
"e": 1899,
"s": 1449,
"text": "using System;\npublic class Demo {\n enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };\n public static void Main() {\n StudentRank student1 = StudentRank.Tom;\n StudentRank student2 = StudentRank.Henry;\n StudentRank student3 = StudentRank.Amit;\n Console.WriteLine(\"{0} has more rank than {1}?\", student1, student2);\n Console.WriteLine( \"{0}{1}\", student1.CompareTo(student2) > 0 ? \"Yes\" : \"No\", Environment.NewLine );\n }\n}"
},
{
"code": null,
"e": 1933,
"s": 1899,
"text": "Tom has more rank than Henry?\nYes"
}
] |
Search in a matrix | Practice | GeeksforGeeks | Given a matrix mat[][] of size N x M, where every row and column is sorted in increasing order, and a number X is given. The task is to find whether element X is present in the matrix or not.
Example 1:
Input:
N = 3, M = 3
mat[][] = 3 30 38
44 52 54
57 60 69
X = 62
Output:
0
Explanation:
62 is not present in the
matrix, so output is 0
Example 2:
Input:
N = 1, M = 6
mat[][] = 18 21 27 38 55 67
X = 55
Output:
1
Explanation:
55 is present in the
matrix at 5th cell.
Your Task:
You don't need to read input or print anything. You just have to complete the function matSearch() which takes a 2D matrix mat[][], its dimensions N and M and integer X as inputs and returns 1 if the element X is present in the matrix and 0 otherwise.
Expected Time Complexity: O(N+M).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N, M <= 1005
1 <= mat[][] <= 10000000
1<= X <= 10000000
0
mayank180919995 hours ago
int matSearch (vector <vector <int>> &mat, int N, int M, int X)
{
// your code here
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(mat[i][j]==X){
return 1;
}
}
}
return 0;
}
0
tusharbijalwan126 hours ago
class Solution{public: int binary_Srch(int s,vector<int>ar,int low,int high){ low=0,high=ar.size()-1; while(low<=high){ int mid=(low+high)/2; if(ar[mid]==s){ return 1; } else if(ar[mid]>s){ high=mid-1; } else{ low=mid+1; } } return 0; }
int matSearch (vector <vector <int>> &mat, int N, int M, int x){ // your code here vector<int>v; for(int i=0;i<mat.size();i++){ for(int j=0;j<mat[0].size();j++){ v.push_back(mat[i][j]); } } sort(v.begin(),v.end()); if(binary_Srch(x,v,0,v.size())){ return 1; } else{ return 0; } }};
+1
bhardwajji1 week ago
binary search row and col vise
int matSearch (int n, int m, int mat[][m], int x)
{
int i=0 , j=m-1;
while(i>=0 && j>=0 && i<n && j<m){
if(mat[i][j] == x )
return 1;
else if(mat[i][j] < x){
i++;
}
else{
j--;
}
}
return 0;
}
0
anishmeena0011 week ago
int matSearch (vector <vector <int>> &mat, int N, int M, int X){ // your code here for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { if(mat[i][j]==X) return 1; } }return 0;}
0
scientiest311 week ago
def matSearch(self,mat, N, M, X): for i in range(N): if mat[i][0] <= X and mat[i][M-1] >= X: if X in mat[i]: return 1 return 0
0
tusharbijalwan123 weeks ago
int matSearch (vector <vector <int>> &mat, int N, int M, int X){ // your code here int s=0; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(mat[i][j]==X){ s=1; } } } return s;}
0
gunateja pm1 month ago
class Sol{ public static int matSearch(int mat[][], int N, int M, int X) { // your code here int k =0; for(int i[] : mat) { for(int j : i) { if(j==X) { k=1; } else if(j>X) { break; } } } return k; }}
+3
17rashishukla2 months ago
//C++ solution
UPVOTE IT IF YOU LIKE AND UNDERSTAND THE SOLUTION
//It is basically startting from row =3 and col=0
//If you have any doubt you can ask.
class Solution{
public:
int matSearch (vector <vector <int>> &mat, int N, int M, int X)
{
int row=N-1;
int col=0;
while(row>=0 && col <= (M-1)){
if(mat[row][col]==X){
return 1;
}
else if(mat[row][col]>X){
row--;
}
else{
col++;
}
}
return 0;
}
};
0
aakasshuit2 months ago
//Java Solution
int row=0;
int col=M-1;
while(row<N && col>=0){
if(mat[row][col]==X){
return 1;
}
if(mat[row][col]<X){
row++;
}
else{
col--;
}
}
return 0;
+1
singhtanay20002 months ago
// { Driver Code Starts//Initial Template for C
#include <stdio.h>
// } Driver Code Ends//User function Template for C
int matSearch (int N, int M, int matrix[][M], int x){ int row=0,column=M-1; while(row<N && column>=0){ if(matrix[row][column]==x) return 1; else if(matrix[row][column]>x) column--; else row++; } return 0;}
// { Driver Code Starts.
int main(){ int tc;scanf("%d", &tc);while(tc--){ int n, m; scanf("%d", &n); scanf("%d", &m); int matrix[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ scanf("%d", &matrix[i][j]); } } int x; scanf("%d", &x); int result = matSearch (n, m, matrix, x); printf("%d", result); printf("\n"); } return 0;} // } Driver Code Ends
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": 430,
"s": 238,
"text": "Given a matrix mat[][] of size N x M, where every row and column is sorted in increasing order, and a number X is given. The task is to find whether element X is present in the matrix or not."
},
{
"code": null,
"e": 442,
"s": 430,
"text": "\nExample 1:"
},
{
"code": null,
"e": 596,
"s": 442,
"text": "Input:\nN = 3, M = 3\nmat[][] = 3 30 38 \n 44 52 54 \n 57 60 69\nX = 62\nOutput:\n0\nExplanation:\n62 is not present in the\nmatrix, so output is 0"
},
{
"code": null,
"e": 608,
"s": 596,
"text": "\nExample 2:"
},
{
"code": null,
"e": 727,
"s": 608,
"text": "Input:\nN = 1, M = 6\nmat[][] = 18 21 27 38 55 67\nX = 55\nOutput:\n1\nExplanation:\n55 is present in the\nmatrix at 5th cell."
},
{
"code": null,
"e": 991,
"s": 727,
"text": "\nYour Task:\nYou don't need to read input or print anything. You just have to complete the function matSearch() which takes a 2D matrix mat[][], its dimensions N and M and integer X as inputs and returns 1 if the element X is present in the matrix and 0 otherwise."
},
{
"code": null,
"e": 1058,
"s": 991,
"text": "\nExpected Time Complexity: O(N+M).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1133,
"s": 1058,
"text": "\nConstraints:\n1 <= N, M <= 1005\n1 <= mat[][] <= 10000000\n1<= X <= 10000000"
},
{
"code": null,
"e": 1135,
"s": 1133,
"text": "0"
},
{
"code": null,
"e": 1161,
"s": 1135,
"text": "mayank180919995 hours ago"
},
{
"code": null,
"e": 1418,
"s": 1161,
"text": "\tint matSearch (vector <vector <int>> &mat, int N, int M, int X)\n\t{\n\t // your code here\n\t for(int i=0;i<N;i++){\n\t for(int j=0;j<M;j++){\n\t if(mat[i][j]==X){\n\t return 1;\n\t }\n\t }\n\t }\n\t return 0;\n\t}"
},
{
"code": null,
"e": 1420,
"s": 1418,
"text": "0"
},
{
"code": null,
"e": 1448,
"s": 1420,
"text": "tusharbijalwan126 hours ago"
},
{
"code": null,
"e": 1826,
"s": 1448,
"text": "class Solution{public: int binary_Srch(int s,vector<int>ar,int low,int high){ low=0,high=ar.size()-1; while(low<=high){ int mid=(low+high)/2; if(ar[mid]==s){ return 1; } else if(ar[mid]>s){ high=mid-1; } else{ low=mid+1; } } return 0; }"
},
{
"code": null,
"e": 2177,
"s": 1826,
"text": "int matSearch (vector <vector <int>> &mat, int N, int M, int x){ // your code here vector<int>v; for(int i=0;i<mat.size();i++){ for(int j=0;j<mat[0].size();j++){ v.push_back(mat[i][j]); } } sort(v.begin(),v.end()); if(binary_Srch(x,v,0,v.size())){ return 1; } else{ return 0; } }};"
},
{
"code": null,
"e": 2182,
"s": 2179,
"text": "+1"
},
{
"code": null,
"e": 2203,
"s": 2182,
"text": "bhardwajji1 week ago"
},
{
"code": null,
"e": 2234,
"s": 2203,
"text": "binary search row and col vise"
},
{
"code": null,
"e": 2532,
"s": 2234,
"text": "int matSearch (int n, int m, int mat[][m], int x)\n{\n \n int i=0 , j=m-1;\n while(i>=0 && j>=0 && i<n && j<m){\n if(mat[i][j] == x )\n return 1;\n else if(mat[i][j] < x){\n i++;\n }\n else{\n j--;\n }\n \n }\n return 0;\n}"
},
{
"code": null,
"e": 2534,
"s": 2532,
"text": "0"
},
{
"code": null,
"e": 2558,
"s": 2534,
"text": "anishmeena0011 week ago"
},
{
"code": null,
"e": 2786,
"s": 2558,
"text": "int matSearch (vector <vector <int>> &mat, int N, int M, int X){ // your code here for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { if(mat[i][j]==X) return 1; } }return 0;}"
},
{
"code": null,
"e": 2788,
"s": 2786,
"text": "0"
},
{
"code": null,
"e": 2811,
"s": 2788,
"text": "scientiest311 week ago"
},
{
"code": null,
"e": 2971,
"s": 2811,
"text": "def matSearch(self,mat, N, M, X): for i in range(N): if mat[i][0] <= X and mat[i][M-1] >= X: if X in mat[i]: return 1 return 0"
},
{
"code": null,
"e": 2973,
"s": 2971,
"text": "0"
},
{
"code": null,
"e": 3001,
"s": 2973,
"text": "tusharbijalwan123 weeks ago"
},
{
"code": null,
"e": 3248,
"s": 3001,
"text": " int matSearch (vector <vector <int>> &mat, int N, int M, int X){ // your code here int s=0; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ if(mat[i][j]==X){ s=1; } } } return s;}"
},
{
"code": null,
"e": 3250,
"s": 3248,
"text": "0"
},
{
"code": null,
"e": 3273,
"s": 3250,
"text": "gunateja pm1 month ago"
},
{
"code": null,
"e": 3621,
"s": 3273,
"text": "class Sol{ public static int matSearch(int mat[][], int N, int M, int X) { // your code here int k =0; for(int i[] : mat) { for(int j : i) { if(j==X) { k=1; } else if(j>X) { break; } } } return k; }}"
},
{
"code": null,
"e": 3624,
"s": 3621,
"text": "+3"
},
{
"code": null,
"e": 3650,
"s": 3624,
"text": "17rashishukla2 months ago"
},
{
"code": null,
"e": 3665,
"s": 3650,
"text": "//C++ solution"
},
{
"code": null,
"e": 3715,
"s": 3665,
"text": "UPVOTE IT IF YOU LIKE AND UNDERSTAND THE SOLUTION"
},
{
"code": null,
"e": 4171,
"s": 3715,
"text": "//It is basically startting from row =3 and col=0 \n//If you have any doubt you can ask.\nclass Solution{\npublic:\t\n\tint matSearch (vector <vector <int>> &mat, int N, int M, int X)\n\t{\n\t int row=N-1;\n\t int col=0;\n\t while(row>=0 && col <= (M-1)){\n\t if(mat[row][col]==X){\n\t return 1;\n\t }\n\t else if(mat[row][col]>X){\n\t row--;\n\t }\n\t else{\n\t col++;\n\t }\n\t }\n\t return 0;\n\t}\n};"
},
{
"code": null,
"e": 4173,
"s": 4171,
"text": "0"
},
{
"code": null,
"e": 4196,
"s": 4173,
"text": "aakasshuit2 months ago"
},
{
"code": null,
"e": 4512,
"s": 4196,
"text": "//Java Solution\n\n int row=0;\n int col=M-1;\n while(row<N && col>=0){\n if(mat[row][col]==X){\n return 1;\n }\n if(mat[row][col]<X){\n row++;\n }\n else{\n col--;\n }\n }\n return 0;"
},
{
"code": null,
"e": 4515,
"s": 4512,
"text": "+1"
},
{
"code": null,
"e": 4542,
"s": 4515,
"text": "singhtanay20002 months ago"
},
{
"code": null,
"e": 4590,
"s": 4542,
"text": "// { Driver Code Starts//Initial Template for C"
},
{
"code": null,
"e": 4609,
"s": 4590,
"text": "#include <stdio.h>"
},
{
"code": null,
"e": 4661,
"s": 4609,
"text": "// } Driver Code Ends//User function Template for C"
},
{
"code": null,
"e": 4930,
"s": 4661,
"text": "int matSearch (int N, int M, int matrix[][M], int x){ int row=0,column=M-1; while(row<N && column>=0){ if(matrix[row][column]==x) return 1; else if(matrix[row][column]>x) column--; else row++; } return 0;}"
},
{
"code": null,
"e": 4955,
"s": 4930,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 5325,
"s": 4955,
"text": "int main(){ int tc;scanf(\"%d\", &tc);while(tc--){ int n, m; scanf(\"%d\", &n); scanf(\"%d\", &m); int matrix[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ scanf(\"%d\", &matrix[i][j]); } } int x; scanf(\"%d\", &x); int result = matSearch (n, m, matrix, x); printf(\"%d\", result); printf(\"\\n\"); } return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 5471,
"s": 5325,
"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": 5507,
"s": 5471,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5517,
"s": 5507,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5527,
"s": 5517,
"text": "\nContest\n"
},
{
"code": null,
"e": 5590,
"s": 5527,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5738,
"s": 5590,
"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": 5946,
"s": 5738,
"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": 6052,
"s": 5946,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
The Best Way to Generate Indices in BigQuery | by Jye Sawtell-Rickson | Towards Data Science | When you stumble upon your first task of creating a histogram within BigQuery you might approach it with a simple GROUP BY, something like:
SELECT hour, COUNT(*) AS num_accessesFROM accessesGROUP BY hourORDER BY hour
This is fine, it does a decent job and would earn you a pat on the back from your friendly colleague. What it doesn’t do though, is handle the case of missing hours. For example, you might have accesses throughout most of the day but at 3 am no one accesses your site, sorry. This would leave a gap in your histogram which just isn’t very nice, is it? And in some cases, can look downright silly.
Instead, we can use a variety of techniques to get that extra hour, my favourite of which combines the harmonious duo of UNNEST and GENERATE_ARRAY.
The general idea is to generate an array of all the possible values, convert that array into rows and then use those rows as an index to join your results onto — elementary, you say! Let’s try this:
SELECT * FROM UNNEST(GENERATE_ARRAY(0, 23)) AS hour
This query will generate an array with the numbers 0, 1, ..., 23 to pass to UNNEST which takes those values and puts them in rows, finally labeled as hour.
With that index we can then do a left join (we want to keep the null rows in the index else all would have been for naught). Our final query looks something like this:
WITH index AS (SELECT * FROM UNNEST(GENERATE_ARRAY(0, 23)) AS hour),hourly_counts AS ( SELECT hour, COUNT(*) AS num_accesses FROM accesses GROUP BY hour )SELECT hour, COALESCE(num_accesses, 0) AS num_accessesFROM index LEFT JOIN hourly_counts USING (hour)ORDER BY hour
Instead of the convenient predefined bounds we used above, you might have variable bounds. An example would be if you’re trying to produce a histogram of the number of accesses in a day. Again, you might try to apply a GROUP BY, but you won’t have the missing indices.
WITH daily_accesses AS ( SELECT day, COUNT(*) AS num_accesses FROM accesses GROUP BY day )SELECT num_accesses, COUNT(*) AS num_daysFROM daily_accessesGROUP BY num_accessesORDER BY num_accesses
No good! So let’s try generating the index again, but this time using variable bounds, since the num_accesses on any given day is unconstrained.
SELECT *FROM UNNEST(GENERATE_ARRAY( (SELECT MIN(num_accesses) FROM daily_accesses)mi, (SELECT MAX(num_accesses) FROM daily_accesses)ma )) AS num_accesses
From our daily accesses table we’ve pulled out the minimum and maximum values, which gives us the lower and upper bound, respectively. Combining these all together we get:
WITH daily_accesses AS ( SELECT day, COUNT(*) AS num_accesses FROM accesses GROUP BY day ),day_counts AS ( SELECT num_accesses, COUNT(*) AS num_days FROM daily_accesses GROUP BY num_accesses ),index AS ( SELECT * FROM UNNEST(GENERATE_ARRAY( (SELECT MIN(num_accesses) FROM daily_accesses)mi, (SELECT MAX(num_accesses) FROM daily_accesses)ma )) AS num_accesses )SELECT num_accesses, COALESCE(num_days, 0) AS num_daysFROM index LEFT JOIN day_counts USING (num_accesses)ORDER BY num_accesses
A little more involved than the previous example, but the principle remains the same.
Finally, you’re likely to come across a date index during your data journey. You could generate a number using GENERATE_ARRAY and then use something like DATE_ADD to get the dates, but Bigquery has a built-in function GENERATE_DATE_ARRAY.
Consider now if we want to get the daily number of accesses to our website for 2020 (it’s review time!). Since it has been a year with a lot of variability, there may be days without any accesses.
Again, our basic query:
SELECT date, COUNT(*) AS num_accessesFROM accessesGROUP BY dateORDER BY date
And we create our index like:
SELECT * FROM UNNEST(GENERATE_DATE_ARRAY( '2020-01-01', CURRENT_DATE() )) AS date
Which will create one date for each day up until today in 2020. Giving the final query.
WITH index AS ( SELECT * FROM UNNEST(GENERATE_DATE_ARRAY( '2020-01-01', CURRENT_DATE() )) AS date ),daily_counts AS ( SELECT date, COUNT(*) AS num_accesses FROM accesses GROUP BY date )SELECT date, COALESCE(num_accesses, 0) AS num_accessesFROM index LEFT JOIN daily_counts USING (date)ORDER BY date
Throughout the examples so far, we’ve assumed the interval is 1 (or 1 DAY), but it’s perfectly reasonable to use different step sizes such as every seven days. To achieve such things you can pass an additional parameter to the GENERATE function which will then return an adjusted index. In this case, you’ll need to be a little more tricky in how you join your underlying data, but it’s achievable for the determined data wrangler!
Hopefully this simple approach to generating indices can help you out next time you need a well defined index. As always, check out the Bigquery docs if you’d like to learn more.
Let me know if you use any other interesting or convenient methods! | [
{
"code": null,
"e": 312,
"s": 172,
"text": "When you stumble upon your first task of creating a histogram within BigQuery you might approach it with a simple GROUP BY, something like:"
},
{
"code": null,
"e": 404,
"s": 312,
"text": "SELECT hour, COUNT(*) AS num_accessesFROM accessesGROUP BY hourORDER BY hour"
},
{
"code": null,
"e": 801,
"s": 404,
"text": "This is fine, it does a decent job and would earn you a pat on the back from your friendly colleague. What it doesn’t do though, is handle the case of missing hours. For example, you might have accesses throughout most of the day but at 3 am no one accesses your site, sorry. This would leave a gap in your histogram which just isn’t very nice, is it? And in some cases, can look downright silly."
},
{
"code": null,
"e": 949,
"s": 801,
"text": "Instead, we can use a variety of techniques to get that extra hour, my favourite of which combines the harmonious duo of UNNEST and GENERATE_ARRAY."
},
{
"code": null,
"e": 1148,
"s": 949,
"text": "The general idea is to generate an array of all the possible values, convert that array into rows and then use those rows as an index to join your results onto — elementary, you say! Let’s try this:"
},
{
"code": null,
"e": 1200,
"s": 1148,
"text": "SELECT * FROM UNNEST(GENERATE_ARRAY(0, 23)) AS hour"
},
{
"code": null,
"e": 1356,
"s": 1200,
"text": "This query will generate an array with the numbers 0, 1, ..., 23 to pass to UNNEST which takes those values and puts them in rows, finally labeled as hour."
},
{
"code": null,
"e": 1524,
"s": 1356,
"text": "With that index we can then do a left join (we want to keep the null rows in the index else all would have been for naught). Our final query looks something like this:"
},
{
"code": null,
"e": 1846,
"s": 1524,
"text": "WITH index AS (SELECT * FROM UNNEST(GENERATE_ARRAY(0, 23)) AS hour),hourly_counts AS ( SELECT hour, COUNT(*) AS num_accesses FROM accesses GROUP BY hour )SELECT hour, COALESCE(num_accesses, 0) AS num_accessesFROM index LEFT JOIN hourly_counts USING (hour)ORDER BY hour"
},
{
"code": null,
"e": 2115,
"s": 1846,
"text": "Instead of the convenient predefined bounds we used above, you might have variable bounds. An example would be if you’re trying to produce a histogram of the number of accesses in a day. Again, you might try to apply a GROUP BY, but you won’t have the missing indices."
},
{
"code": null,
"e": 2363,
"s": 2115,
"text": "WITH daily_accesses AS ( SELECT day, COUNT(*) AS num_accesses FROM accesses GROUP BY day )SELECT num_accesses, COUNT(*) AS num_daysFROM daily_accessesGROUP BY num_accessesORDER BY num_accesses"
},
{
"code": null,
"e": 2508,
"s": 2363,
"text": "No good! So let’s try generating the index again, but this time using variable bounds, since the num_accesses on any given day is unconstrained."
},
{
"code": null,
"e": 2689,
"s": 2508,
"text": "SELECT *FROM UNNEST(GENERATE_ARRAY( (SELECT MIN(num_accesses) FROM daily_accesses)mi, (SELECT MAX(num_accesses) FROM daily_accesses)ma )) AS num_accesses"
},
{
"code": null,
"e": 2861,
"s": 2689,
"text": "From our daily accesses table we’ve pulled out the minimum and maximum values, which gives us the lower and upper bound, respectively. Combining these all together we get:"
},
{
"code": null,
"e": 3500,
"s": 2861,
"text": "WITH daily_accesses AS ( SELECT day, COUNT(*) AS num_accesses FROM accesses GROUP BY day ),day_counts AS ( SELECT num_accesses, COUNT(*) AS num_days FROM daily_accesses GROUP BY num_accesses ),index AS ( SELECT * FROM UNNEST(GENERATE_ARRAY( (SELECT MIN(num_accesses) FROM daily_accesses)mi, (SELECT MAX(num_accesses) FROM daily_accesses)ma )) AS num_accesses )SELECT num_accesses, COALESCE(num_days, 0) AS num_daysFROM index LEFT JOIN day_counts USING (num_accesses)ORDER BY num_accesses"
},
{
"code": null,
"e": 3586,
"s": 3500,
"text": "A little more involved than the previous example, but the principle remains the same."
},
{
"code": null,
"e": 3825,
"s": 3586,
"text": "Finally, you’re likely to come across a date index during your data journey. You could generate a number using GENERATE_ARRAY and then use something like DATE_ADD to get the dates, but Bigquery has a built-in function GENERATE_DATE_ARRAY."
},
{
"code": null,
"e": 4022,
"s": 3825,
"text": "Consider now if we want to get the daily number of accesses to our website for 2020 (it’s review time!). Since it has been a year with a lot of variability, there may be days without any accesses."
},
{
"code": null,
"e": 4046,
"s": 4022,
"text": "Again, our basic query:"
},
{
"code": null,
"e": 4138,
"s": 4046,
"text": "SELECT date, COUNT(*) AS num_accessesFROM accessesGROUP BY dateORDER BY date"
},
{
"code": null,
"e": 4168,
"s": 4138,
"text": "And we create our index like:"
},
{
"code": null,
"e": 4259,
"s": 4168,
"text": "SELECT * FROM UNNEST(GENERATE_DATE_ARRAY( '2020-01-01', CURRENT_DATE() )) AS date"
},
{
"code": null,
"e": 4347,
"s": 4259,
"text": "Which will create one date for each day up until today in 2020. Giving the final query."
},
{
"code": null,
"e": 4725,
"s": 4347,
"text": "WITH index AS ( SELECT * FROM UNNEST(GENERATE_DATE_ARRAY( '2020-01-01', CURRENT_DATE() )) AS date ),daily_counts AS ( SELECT date, COUNT(*) AS num_accesses FROM accesses GROUP BY date )SELECT date, COALESCE(num_accesses, 0) AS num_accessesFROM index LEFT JOIN daily_counts USING (date)ORDER BY date"
},
{
"code": null,
"e": 5157,
"s": 4725,
"text": "Throughout the examples so far, we’ve assumed the interval is 1 (or 1 DAY), but it’s perfectly reasonable to use different step sizes such as every seven days. To achieve such things you can pass an additional parameter to the GENERATE function which will then return an adjusted index. In this case, you’ll need to be a little more tricky in how you join your underlying data, but it’s achievable for the determined data wrangler!"
},
{
"code": null,
"e": 5336,
"s": 5157,
"text": "Hopefully this simple approach to generating indices can help you out next time you need a well defined index. As always, check out the Bigquery docs if you’d like to learn more."
}
] |
PDF Viewer for Python Tkinter | Python is well known for its large set of libraries and extensions, each for different features, properties and use-cases. To handle PDF files, Python provides PyPDF2 toolkit which is capable of processing, extracting, merging multiple pages, encrypting PDF files, and many more. It is a very useful Package for managing and manipulating the file streams such as PDFs. Using PyPDF2, we will create a Tkinter application that reads the PDF file by asking users to select and open a PDF file from the local directory.
To create the application, we will follow the steps given below −
Install the requirement by typingpip install PyPDF2in the command Shell. Once installed, import the library in the notebook using import Pypdf2 in Notebook.
Install the requirement by typing
pip install PyPDF2
Import filedialog to create a dialog box for selecting the file from the local directory.
Import filedialog to create a dialog box for selecting the file from the local directory.
Create a Text Widget and add some Menus to it like Open, Clear, and Quit.
Create a Text Widget and add some Menus to it like Open, Clear, and Quit.
Define a function for each Menu.
Define a function for each Menu.
Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file.
Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file.
Insert the content in the Text Box.
Insert the content in the Text Box.
Define the function for Quit Menu.
Define the function for Quit Menu.
#Import the required Libraries
import PyPDF2
from tkinter import *
from tkinter import filedialog
#Create an instance of tkinter frame
win= Tk()
#Set the Geometry
win.geometry("750x450")
#Create a Text Box
text= Text(win,width= 80,height=30)
text.pack(pady=20)
#Define a function to clear the text
def clear_text():
text.delete(1.0, END)
#Define a function to open the pdf file
def open_pdf():
file= filedialog.askopenfilename(title="Select a PDF", filetype=(("PDF Files","*.pdf"),("All Files","*.*")))
if file:
#Open the PDF File
pdf_file= PyPDF2.PdfFileReader(file)
#Select a Page to read
page= pdf_file.getPage(0)
#Get the content of the Page
content=page.extractText()
#Add the content to TextBox
text.insert(1.0,content)
#Define function to Quit the window
def quit_app():
win.destroy()
#Create a Menu
my_menu= Menu(win)
win.config(menu=my_menu)
#Add dropdown to the Menus
file_menu=Menu(my_menu,tearoff=False)
my_menu.add_cascade(label="File",menu= file_menu)
file_menu.add_command(label="Open",command=open_pdf)
file_menu.add_command(label="Clear",command=clear_text)
file_menu.add_command(label="Quit",command=quit_app)
win.mainloop()
Running the above code will display a full-fledged tkinter application. It has functionalities of opening the file, clearing the file, and quit to terminate the application.
Click the "File" Menu on upper left corner of the application, open a new PDF File in the Text Box. | [
{
"code": null,
"e": 1578,
"s": 1062,
"text": "Python is well known for its large set of libraries and extensions, each for different features, properties and use-cases. To handle PDF files, Python provides PyPDF2 toolkit which is capable of processing, extracting, merging multiple pages, encrypting PDF files, and many more. It is a very useful Package for managing and manipulating the file streams such as PDFs. Using PyPDF2, we will create a Tkinter application that reads the PDF file by asking users to select and open a PDF file from the local directory."
},
{
"code": null,
"e": 1644,
"s": 1578,
"text": "To create the application, we will follow the steps given below −"
},
{
"code": null,
"e": 1801,
"s": 1644,
"text": "Install the requirement by typingpip install PyPDF2in the command Shell. Once installed, import the library in the notebook using import Pypdf2 in Notebook."
},
{
"code": null,
"e": 1835,
"s": 1801,
"text": "Install the requirement by typing"
},
{
"code": null,
"e": 1854,
"s": 1835,
"text": "pip install PyPDF2"
},
{
"code": null,
"e": 1944,
"s": 1854,
"text": "Import filedialog to create a dialog box for selecting the file from the local directory."
},
{
"code": null,
"e": 2034,
"s": 1944,
"text": "Import filedialog to create a dialog box for selecting the file from the local directory."
},
{
"code": null,
"e": 2108,
"s": 2034,
"text": "Create a Text Widget and add some Menus to it like Open, Clear, and Quit."
},
{
"code": null,
"e": 2182,
"s": 2108,
"text": "Create a Text Widget and add some Menus to it like Open, Clear, and Quit."
},
{
"code": null,
"e": 2215,
"s": 2182,
"text": "Define a function for each Menu."
},
{
"code": null,
"e": 2248,
"s": 2215,
"text": "Define a function for each Menu."
},
{
"code": null,
"e": 2397,
"s": 2248,
"text": "Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file."
},
{
"code": null,
"e": 2546,
"s": 2397,
"text": "Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file."
},
{
"code": null,
"e": 2582,
"s": 2546,
"text": "Insert the content in the Text Box."
},
{
"code": null,
"e": 2618,
"s": 2582,
"text": "Insert the content in the Text Box."
},
{
"code": null,
"e": 2653,
"s": 2618,
"text": "Define the function for Quit Menu."
},
{
"code": null,
"e": 2688,
"s": 2653,
"text": "Define the function for Quit Menu."
},
{
"code": null,
"e": 3895,
"s": 2688,
"text": "#Import the required Libraries\nimport PyPDF2\nfrom tkinter import *\nfrom tkinter import filedialog\n#Create an instance of tkinter frame\nwin= Tk()\n#Set the Geometry\nwin.geometry(\"750x450\")\n#Create a Text Box\ntext= Text(win,width= 80,height=30)\ntext.pack(pady=20)\n#Define a function to clear the text\ndef clear_text():\n text.delete(1.0, END)\n#Define a function to open the pdf file\ndef open_pdf():\n file= filedialog.askopenfilename(title=\"Select a PDF\", filetype=((\"PDF Files\",\"*.pdf\"),(\"All Files\",\"*.*\")))\n if file:\n #Open the PDF File\n pdf_file= PyPDF2.PdfFileReader(file)\n #Select a Page to read\n page= pdf_file.getPage(0)\n #Get the content of the Page\n content=page.extractText()\n #Add the content to TextBox\n text.insert(1.0,content)\n\n#Define function to Quit the window\ndef quit_app():\n win.destroy()\n#Create a Menu\nmy_menu= Menu(win)\nwin.config(menu=my_menu)\n#Add dropdown to the Menus\nfile_menu=Menu(my_menu,tearoff=False)\nmy_menu.add_cascade(label=\"File\",menu= file_menu)\nfile_menu.add_command(label=\"Open\",command=open_pdf)\nfile_menu.add_command(label=\"Clear\",command=clear_text)\nfile_menu.add_command(label=\"Quit\",command=quit_app)\nwin.mainloop()"
},
{
"code": null,
"e": 4069,
"s": 3895,
"text": "Running the above code will display a full-fledged tkinter application. It has functionalities of opening the file, clearing the file, and quit to terminate the application."
},
{
"code": null,
"e": 4169,
"s": 4069,
"text": "Click the \"File\" Menu on upper left corner of the application, open a new PDF File in the Text Box."
}
] |
DAX Filter - CALCULATE function | Evaluates an expression in a context that is modified by the specified filters.
CALCULATE (<expression>, [<filter1>], [<filter2>] ...)
expression
The expression to be evaluated.
filter1, filter2, ...
Optional.
A comma separated list of Boolean expressions or a table expression that defines a filter.
The value that is the result of the expression.
The expression used as the first parameter is essentially the same as a calculated field.
If Boolean expressions are used as arguments, the following restrictions apply −
An expression cannot reference a calculated field.
An expression cannot reference a calculated field.
An expression cannot use a nested CALCULATE function.
An expression cannot use a nested CALCULATE function.
An expression cannot use any function that scans a table or returns a table, including aggregation functions.
An expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
If the data has been filtered, the CALCULATE function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter argument, any existing filters on that column are removed, and the filter used in the filter argument is applied instead.
= COUNTA (Results[Medal])/CALCULATE (COUNTA (Results[Medal], ALL (Results))
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2081,
"s": 2001,
"text": "Evaluates an expression in a context that is modified by the specified filters."
},
{
"code": null,
"e": 2138,
"s": 2081,
"text": "CALCULATE (<expression>, [<filter1>], [<filter2>] ...) \n"
},
{
"code": null,
"e": 2149,
"s": 2138,
"text": "expression"
},
{
"code": null,
"e": 2181,
"s": 2149,
"text": "The expression to be evaluated."
},
{
"code": null,
"e": 2203,
"s": 2181,
"text": "filter1, filter2, ..."
},
{
"code": null,
"e": 2213,
"s": 2203,
"text": "Optional."
},
{
"code": null,
"e": 2304,
"s": 2213,
"text": "A comma separated list of Boolean expressions or a table expression that defines a filter."
},
{
"code": null,
"e": 2352,
"s": 2304,
"text": "The value that is the result of the expression."
},
{
"code": null,
"e": 2442,
"s": 2352,
"text": "The expression used as the first parameter is essentially the same as a calculated field."
},
{
"code": null,
"e": 2523,
"s": 2442,
"text": "If Boolean expressions are used as arguments, the following restrictions apply −"
},
{
"code": null,
"e": 2574,
"s": 2523,
"text": "An expression cannot reference a calculated field."
},
{
"code": null,
"e": 2625,
"s": 2574,
"text": "An expression cannot reference a calculated field."
},
{
"code": null,
"e": 2679,
"s": 2625,
"text": "An expression cannot use a nested CALCULATE function."
},
{
"code": null,
"e": 2733,
"s": 2679,
"text": "An expression cannot use a nested CALCULATE function."
},
{
"code": null,
"e": 2843,
"s": 2733,
"text": "An expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 2953,
"s": 2843,
"text": "An expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3069,
"s": 2953,
"text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value."
},
{
"code": null,
"e": 3395,
"s": 3069,
"text": "If the data has been filtered, the CALCULATE function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter argument, any existing filters on that column are removed, and the filter used in the filter argument is applied instead."
},
{
"code": null,
"e": 3472,
"s": 3395,
"text": "= COUNTA (Results[Medal])/CALCULATE (COUNTA (Results[Medal], ALL (Results)) "
},
{
"code": null,
"e": 3507,
"s": 3472,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3521,
"s": 3507,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3554,
"s": 3521,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3568,
"s": 3554,
"text": " Randy Minder"
},
{
"code": null,
"e": 3603,
"s": 3568,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3617,
"s": 3603,
"text": " Randy Minder"
},
{
"code": null,
"e": 3624,
"s": 3617,
"text": " Print"
},
{
"code": null,
"e": 3635,
"s": 3624,
"text": " Add Notes"
}
] |
remainder() in C++ | Here we will see the functionality of remainder() method of C++. The remainder() function is used to compute the floating point remainder of numerator/denominator.
So the remainder(x, y) will be like below.
remainder(x, y) = x – rquote * y
The rquote is the value of x/y. This is rounded towards the nearest integral value. This function takes two arguments of type double, float, long double, and returns the remainder of the same type, that was given as argument. The first argument is numerator, and the second argument is the denominator.
#include <iostream>
#include <cmath>
using namespace std;
main() {
double x = 14.5, y = 4.1;
double res = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " is: " << res << endl;
x = -34.50;
y = 4.0;
res = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " is: " << res << endl;
x = 65.23;
y = 0;
res = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " is: " << res << endl;
}
Remainder of 14.5/4.1 is: -1.9
Remainder of -34.5/4 is: 1.5
Remainder of 65.23/0 is: nan | [
{
"code": null,
"e": 1226,
"s": 1062,
"text": "Here we will see the functionality of remainder() method of C++. The remainder() function is used to compute the floating point remainder of numerator/denominator."
},
{
"code": null,
"e": 1269,
"s": 1226,
"text": "So the remainder(x, y) will be like below."
},
{
"code": null,
"e": 1302,
"s": 1269,
"text": "remainder(x, y) = x – rquote * y"
},
{
"code": null,
"e": 1605,
"s": 1302,
"text": "The rquote is the value of x/y. This is rounded towards the nearest integral value. This function takes two arguments of type double, float, long double, and returns the remainder of the same type, that was given as argument. The first argument is numerator, and the second argument is the denominator."
},
{
"code": null,
"e": 2052,
"s": 1605,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nmain() {\n double x = 14.5, y = 4.1;\n double res = remainder(x, y);\n cout << \"Remainder of \" << x << \"/\" << y << \" is: \" << res << endl;\n x = -34.50;\n y = 4.0;\n res = remainder(x, y);\n cout << \"Remainder of \" << x << \"/\" << y << \" is: \" << res << endl;\n x = 65.23;\n y = 0;\n res = remainder(x, y);\n cout << \"Remainder of \" << x << \"/\" << y << \" is: \" << res << endl;\n}"
},
{
"code": null,
"e": 2141,
"s": 2052,
"text": "Remainder of 14.5/4.1 is: -1.9\nRemainder of -34.5/4 is: 1.5\nRemainder of 65.23/0 is: nan"
}
] |
NumPy Basics Cheat Sheet (2021), Python for Data Science | by Chris Zaire | Towards Data Science | The NumPy library is the core library for scientific computation in Python. It provides a high-performance multidimensional array object and tools for working with arrays.
Check out the different sections below to learn the various array functions and tools NumPy offers.
Sections:1. Creating Arrays2. Inspecting Your Array3. Array Mathematics4. Comparisons5. Aggregate Functions6. Subsetting, Slicing, Indexing7. Adding/Removing Elements8. Array Manipulation9. Copying Arrays10. Sorting Arrays11. Data Types
A NumPy array is a grid of values, all of the same type. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
In this section, you’ll learn how to create these various types of arrays.
1-dimensional array
>>> a = np.array([1,2,3]) array([1, 2, 3])
2-dimensional array
>>> b = np.array([(1.5,2,3),(4,5,6)], dtype = float) array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
3-dimensional array
>>> c = np.array([[(1.5,2,3),(4,5,6)],[(3,2,1),(4,5,6)]], dtype = float)
Array of zeros
>>> np.zeros((3,4)) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
Array of ones
>>> np.ones((3,4)) array([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]])
Array of evenly spaced values (step value)
>>> np.arange(10,25,5) array([10, 15, 20])
Array of evenly spaced values (number of samples)
>>> np.linspace(0,2,9) array([0.0, 0.25, 0.5 , 0.75, 1.0, 1.25, 1.5 , 1.75, 2.0])
2x2 identity matrix
>>> np.eye(2) array([[1., 0.], [0., 1.]])
Array with random values
>>> np.random.random((2,2)) array([[0.42326354, 0.56737208], [0.01597192, 0.79065649]])
In this section, you’ll learn how to extract the specific characteristics of an array including length, data type, size, and dimensions.
a and b in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
Array dimensions
>>> b.shape (2,3)
Length of array
>>> len(a) 3
Number of array dimensions
>>> b.ndim 2
Number of array elements
>>> b.size 6
Data type of array elements
>>> b.dtype dtype('float64')
Covert an array to a different type
>>> b.astype(int) array([[1, 2, 3], [4, 5, 6]])
In this section, you’ll learn how to perform various arithmetic operations using two different arrays.
a and b in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
Subtraction
>>> a - b array([[-0.5, 0. , 0. ], [-3. , -3. , -3. ]])
Subtraction.v2
>>> np.subtract(a,b) array([[-0.5, 0. , 0. ], [-3. , -3. , -3. ]])
Addition
>>> a + b array([[2.5, 4. , 6. ], [5. , 7. , 9. ]])
Addition.v2
>>> np.add(a,b) array([[2.5, 4. , 6. ], [5. , 7. , 9. ]])
Division
>>> a/b array([[0.66, 1. , 1. ], [0.25, 0.4, 0.5]])
Division.v2
>>> np.divide(a,b) array([[0.66, 1. , 1. ], [0.25, 0.4, 0.5]])
Multiplication
>>> a*b array([[ 1.5, 4. , 9. ], [ 4. , 10. , 18. ]])
Multiplication.v2
>>> np.multiply(a,b) array([[ 1.5, 4. , 9. ], [ 4. , 10. , 18. ]])
Exponentiation
>>> np.exp(b) array([[ 4.48168907, 7.3890561 , 20.08553692], [ 54.59815003, 148.4131591 , 403.42879349]])
Square root
>>> np.sqrt(b) array([[1.22474487, 1.41421356, 1.73205081], [2. , 2.23606798, 2.44948974]])
Logarithm
>>> np.log(b) array([[0.40546511, 0.69314718, 1.09861229], [1.38629436, 1.60943791, 1.79175947]])
In this section, you’ll learn how to compare arrays using a specific element or another array.
a and b in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
Element-wise comparison
>>> a == b array([[False, True, True], [False, False, False]])
Element-wise comparison.v2
>>> a < 2 array([True, False, False])
Array-wise comparisons
>>> np.array_equal(a,b) False
In this section, you’ll learn how to use various aggregate functions like sum, min, max, mean, and median on an array.
a and b in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
Array sum
>>> a.sum() 6
Array minimum value
>>> a.min() 1
Maximum value of an array row
>>> b.max(axis = 0) array([4., 5., 6.])
Cumulative sum of the elements
>>> b.cumsum(axis = 1) array([[ 1.5, 3.5, 6.5], [ 4. , 9. , 15. ]])
Mean
>>> a.mean() 2
In this section, you’ll learn how to retrieve specific values from an array.
a and b in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
Select the element at the 2nd index
>>> a[2] 3
Select the element at row 1 in column 2
>>> b[1,2] 6
Select items at index 0 and 1
>>> a[0:2] array([1, 2])
Select items at row 0 and 1 in column 1
>>> b[0:2,1] array([2., 5.])
Select all items at row 0
>>> b[:1] array([[1.5, 2. , 3. ]]
Reverse array
>>> a[::-1] array([3, 2, 1])
Select elements that are less than 3
>>> a[a<3] array([1, 2])
In this section, you’ll learn how to add specific elements into an array and how to remove them.
a and b in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])
Return a new array with shape (1,6)
>>> b.resize(1,6) array([[1.5, 2. , 3. , 4. , 5. , 6. ]])
Append items to an array
>>> np.append(a,7) array([1, 2, 3, 7])
Insert items in an array
>>> np.insert(a,1,9) array([1, 9, 2, 3])
Delete items from an array
>>> np.delete(a,[1]) array([1, 3])
In this section, you’ll learn how to change the look of an array. You’ll learn how to flatten, transpose, reshape, and concatenate arrays.
a, b, and d in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])>>> d = np.array([10, 15, 20])
Flatten an array
>>> b.ravel() array([1.5, 2. , 3. , 4. , 5. , 6. ])
Reshape, but don’t change the data
>>> b.reshape(3,2) array([[1.5, 2. ], [3. , 4. ], [5. , 6. ]])
Concatenate arrays
>>> np.concatenate((a,d),axis = 0) array([ 1, 2, 3, 10, 15, 20])
Transpose array
>>> np.transpose(b) array([[1.5, 4. ], [2. , 5. ], [3. , 6. ]])
In this section, you’ll learn how to create a copy of an array for future use.
a in the code below is used as an example of an array throughout this section.
>>> a = np.array([1, 2, 3])
Create a copy of the array
>>> np.copy(a) array([1, 2, 3])
Create a deep copy of the array
>>> a.copy() array([1, 2, 3])
In this section, you’ll learn how to sort an array so it’s decreasing to increasing or vice versa.
a and c in the code below are used as examples of arrays throughout this section.
>>> a = np.array([1, 2, 3])>>> c = np.array([[(1.5,2,3),(4,5,6)],[(3,2,1),(4,5,6)]]
Sort an array
>>> a.sort() array([1, 2, 3])
Sort the elements of an array’s axis
>>> c.sort(axis = 0)
These are the different data types that can be in a NumPy array.
64-bit integer types: np.int64
Double-precision floating point: np.float32
Boolean type string TRUE and FALSE: np.bool
Python object type values: np.object
Fixed-length string type: np.string
Fixed-length Unicode type: np.unicode_
Python is the top dog when it comes to data science for now and in the foreseeable future. Knowledge of NumPy, one of its most powerful libraries is often a requirement for Data Scientists today.
Use this cheat sheet as a guide in the beginning and come back to it when needed, and you’ll be well on your way to mastering the NumPy library.
Join my email list with 2k+ people to get The Complete Python for Data Science Cheat Sheet Booklet for Free. | [
{
"code": null,
"e": 344,
"s": 172,
"text": "The NumPy library is the core library for scientific computation in Python. It provides a high-performance multidimensional array object and tools for working with arrays."
},
{
"code": null,
"e": 444,
"s": 344,
"text": "Check out the different sections below to learn the various array functions and tools NumPy offers."
},
{
"code": null,
"e": 681,
"s": 444,
"text": "Sections:1. Creating Arrays2. Inspecting Your Array3. Array Mathematics4. Comparisons5. Aggregate Functions6. Subsetting, Slicing, Indexing7. Adding/Removing Elements8. Array Manipulation9. Copying Arrays10. Sorting Arrays11. Data Types"
},
{
"code": null,
"e": 885,
"s": 681,
"text": "A NumPy array is a grid of values, all of the same type. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension."
},
{
"code": null,
"e": 960,
"s": 885,
"text": "In this section, you’ll learn how to create these various types of arrays."
},
{
"code": null,
"e": 980,
"s": 960,
"text": "1-dimensional array"
},
{
"code": null,
"e": 1023,
"s": 980,
"text": ">>> a = np.array([1,2,3]) array([1, 2, 3])"
},
{
"code": null,
"e": 1043,
"s": 1023,
"text": "2-dimensional array"
},
{
"code": null,
"e": 1145,
"s": 1043,
"text": ">>> b = np.array([(1.5,2,3),(4,5,6)], dtype = float) array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 1165,
"s": 1145,
"text": "3-dimensional array"
},
{
"code": null,
"e": 1238,
"s": 1165,
"text": ">>> c = np.array([[(1.5,2,3),(4,5,6)],[(3,2,1),(4,5,6)]], dtype = float)"
},
{
"code": null,
"e": 1253,
"s": 1238,
"text": "Array of zeros"
},
{
"code": null,
"e": 1349,
"s": 1253,
"text": ">>> np.zeros((3,4)) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])"
},
{
"code": null,
"e": 1363,
"s": 1349,
"text": "Array of ones"
},
{
"code": null,
"e": 1458,
"s": 1363,
"text": ">>> np.ones((3,4)) array([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]])"
},
{
"code": null,
"e": 1501,
"s": 1458,
"text": "Array of evenly spaced values (step value)"
},
{
"code": null,
"e": 1544,
"s": 1501,
"text": ">>> np.arange(10,25,5) array([10, 15, 20])"
},
{
"code": null,
"e": 1594,
"s": 1544,
"text": "Array of evenly spaced values (number of samples)"
},
{
"code": null,
"e": 1676,
"s": 1594,
"text": ">>> np.linspace(0,2,9) array([0.0, 0.25, 0.5 , 0.75, 1.0, 1.25, 1.5 , 1.75, 2.0])"
},
{
"code": null,
"e": 1696,
"s": 1676,
"text": "2x2 identity matrix"
},
{
"code": null,
"e": 1745,
"s": 1696,
"text": ">>> np.eye(2) array([[1., 0.], [0., 1.]])"
},
{
"code": null,
"e": 1770,
"s": 1745,
"text": "Array with random values"
},
{
"code": null,
"e": 1865,
"s": 1770,
"text": ">>> np.random.random((2,2)) array([[0.42326354, 0.56737208], [0.01597192, 0.79065649]])"
},
{
"code": null,
"e": 2002,
"s": 1865,
"text": "In this section, you’ll learn how to extract the specific characteristics of an array including length, data type, size, and dimensions."
},
{
"code": null,
"e": 2084,
"s": 2002,
"text": "a and b in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 2164,
"s": 2084,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 2181,
"s": 2164,
"text": "Array dimensions"
},
{
"code": null,
"e": 2199,
"s": 2181,
"text": ">>> b.shape (2,3)"
},
{
"code": null,
"e": 2215,
"s": 2199,
"text": "Length of array"
},
{
"code": null,
"e": 2228,
"s": 2215,
"text": ">>> len(a) 3"
},
{
"code": null,
"e": 2255,
"s": 2228,
"text": "Number of array dimensions"
},
{
"code": null,
"e": 2268,
"s": 2255,
"text": ">>> b.ndim 2"
},
{
"code": null,
"e": 2293,
"s": 2268,
"text": "Number of array elements"
},
{
"code": null,
"e": 2306,
"s": 2293,
"text": ">>> b.size 6"
},
{
"code": null,
"e": 2334,
"s": 2306,
"text": "Data type of array elements"
},
{
"code": null,
"e": 2363,
"s": 2334,
"text": ">>> b.dtype dtype('float64')"
},
{
"code": null,
"e": 2399,
"s": 2363,
"text": "Covert an array to a different type"
},
{
"code": null,
"e": 2454,
"s": 2399,
"text": ">>> b.astype(int) array([[1, 2, 3], [4, 5, 6]])"
},
{
"code": null,
"e": 2557,
"s": 2454,
"text": "In this section, you’ll learn how to perform various arithmetic operations using two different arrays."
},
{
"code": null,
"e": 2639,
"s": 2557,
"text": "a and b in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 2719,
"s": 2639,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 2731,
"s": 2719,
"text": "Subtraction"
},
{
"code": null,
"e": 2796,
"s": 2731,
"text": ">>> a - b array([[-0.5, 0. , 0. ], [-3. , -3. , -3. ]])"
},
{
"code": null,
"e": 2811,
"s": 2796,
"text": "Subtraction.v2"
},
{
"code": null,
"e": 2887,
"s": 2811,
"text": ">>> np.subtract(a,b) array([[-0.5, 0. , 0. ], [-3. , -3. , -3. ]])"
},
{
"code": null,
"e": 2896,
"s": 2887,
"text": "Addition"
},
{
"code": null,
"e": 2955,
"s": 2896,
"text": ">>> a + b array([[2.5, 4. , 6. ], [5. , 7. , 9. ]])"
},
{
"code": null,
"e": 2967,
"s": 2955,
"text": "Addition.v2"
},
{
"code": null,
"e": 3031,
"s": 2967,
"text": ">>> np.add(a,b) array([[2.5, 4. , 6. ], [5. , 7. , 9. ]])"
},
{
"code": null,
"e": 3040,
"s": 3031,
"text": "Division"
},
{
"code": null,
"e": 3099,
"s": 3040,
"text": ">>> a/b array([[0.66, 1. , 1. ], [0.25, 0.4, 0.5]])"
},
{
"code": null,
"e": 3111,
"s": 3099,
"text": "Division.v2"
},
{
"code": null,
"e": 3181,
"s": 3111,
"text": ">>> np.divide(a,b) array([[0.66, 1. , 1. ], [0.25, 0.4, 0.5]])"
},
{
"code": null,
"e": 3196,
"s": 3181,
"text": "Multiplication"
},
{
"code": null,
"e": 3258,
"s": 3196,
"text": ">>> a*b array([[ 1.5, 4. , 9. ], [ 4. , 10. , 18. ]])"
},
{
"code": null,
"e": 3276,
"s": 3258,
"text": "Multiplication.v2"
},
{
"code": null,
"e": 3351,
"s": 3276,
"text": ">>> np.multiply(a,b) array([[ 1.5, 4. , 9. ], [ 4. , 10. , 18. ]])"
},
{
"code": null,
"e": 3366,
"s": 3351,
"text": "Exponentiation"
},
{
"code": null,
"e": 3482,
"s": 3366,
"text": ">>> np.exp(b) array([[ 4.48168907, 7.3890561 , 20.08553692], [ 54.59815003, 148.4131591 , 403.42879349]])"
},
{
"code": null,
"e": 3494,
"s": 3482,
"text": "Square root"
},
{
"code": null,
"e": 3599,
"s": 3494,
"text": ">>> np.sqrt(b) array([[1.22474487, 1.41421356, 1.73205081], [2. , 2.23606798, 2.44948974]])"
},
{
"code": null,
"e": 3609,
"s": 3599,
"text": "Logarithm"
},
{
"code": null,
"e": 3714,
"s": 3609,
"text": ">>> np.log(b) array([[0.40546511, 0.69314718, 1.09861229], [1.38629436, 1.60943791, 1.79175947]])"
},
{
"code": null,
"e": 3809,
"s": 3714,
"text": "In this section, you’ll learn how to compare arrays using a specific element or another array."
},
{
"code": null,
"e": 3891,
"s": 3809,
"text": "a and b in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 3971,
"s": 3891,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 3995,
"s": 3971,
"text": "Element-wise comparison"
},
{
"code": null,
"e": 4066,
"s": 3995,
"text": ">>> a == b array([[False, True, True], [False, False, False]])"
},
{
"code": null,
"e": 4093,
"s": 4066,
"text": "Element-wise comparison.v2"
},
{
"code": null,
"e": 4131,
"s": 4093,
"text": ">>> a < 2 array([True, False, False])"
},
{
"code": null,
"e": 4154,
"s": 4131,
"text": "Array-wise comparisons"
},
{
"code": null,
"e": 4184,
"s": 4154,
"text": ">>> np.array_equal(a,b) False"
},
{
"code": null,
"e": 4303,
"s": 4184,
"text": "In this section, you’ll learn how to use various aggregate functions like sum, min, max, mean, and median on an array."
},
{
"code": null,
"e": 4385,
"s": 4303,
"text": "a and b in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 4465,
"s": 4385,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 4475,
"s": 4465,
"text": "Array sum"
},
{
"code": null,
"e": 4489,
"s": 4475,
"text": ">>> a.sum() 6"
},
{
"code": null,
"e": 4509,
"s": 4489,
"text": "Array minimum value"
},
{
"code": null,
"e": 4523,
"s": 4509,
"text": ">>> a.min() 1"
},
{
"code": null,
"e": 4553,
"s": 4523,
"text": "Maximum value of an array row"
},
{
"code": null,
"e": 4593,
"s": 4553,
"text": ">>> b.max(axis = 0) array([4., 5., 6.])"
},
{
"code": null,
"e": 4624,
"s": 4593,
"text": "Cumulative sum of the elements"
},
{
"code": null,
"e": 4702,
"s": 4624,
"text": ">>> b.cumsum(axis = 1) array([[ 1.5, 3.5, 6.5], [ 4. , 9. , 15. ]])"
},
{
"code": null,
"e": 4707,
"s": 4702,
"text": "Mean"
},
{
"code": null,
"e": 4722,
"s": 4707,
"text": ">>> a.mean() 2"
},
{
"code": null,
"e": 4799,
"s": 4722,
"text": "In this section, you’ll learn how to retrieve specific values from an array."
},
{
"code": null,
"e": 4881,
"s": 4799,
"text": "a and b in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 4961,
"s": 4881,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 4997,
"s": 4961,
"text": "Select the element at the 2nd index"
},
{
"code": null,
"e": 5008,
"s": 4997,
"text": ">>> a[2] 3"
},
{
"code": null,
"e": 5048,
"s": 5008,
"text": "Select the element at row 1 in column 2"
},
{
"code": null,
"e": 5061,
"s": 5048,
"text": ">>> b[1,2] 6"
},
{
"code": null,
"e": 5091,
"s": 5061,
"text": "Select items at index 0 and 1"
},
{
"code": null,
"e": 5116,
"s": 5091,
"text": ">>> a[0:2] array([1, 2])"
},
{
"code": null,
"e": 5156,
"s": 5116,
"text": "Select items at row 0 and 1 in column 1"
},
{
"code": null,
"e": 5185,
"s": 5156,
"text": ">>> b[0:2,1] array([2., 5.])"
},
{
"code": null,
"e": 5211,
"s": 5185,
"text": "Select all items at row 0"
},
{
"code": null,
"e": 5245,
"s": 5211,
"text": ">>> b[:1] array([[1.5, 2. , 3. ]]"
},
{
"code": null,
"e": 5259,
"s": 5245,
"text": "Reverse array"
},
{
"code": null,
"e": 5288,
"s": 5259,
"text": ">>> a[::-1] array([3, 2, 1])"
},
{
"code": null,
"e": 5325,
"s": 5288,
"text": "Select elements that are less than 3"
},
{
"code": null,
"e": 5350,
"s": 5325,
"text": ">>> a[a<3] array([1, 2])"
},
{
"code": null,
"e": 5447,
"s": 5350,
"text": "In this section, you’ll learn how to add specific elements into an array and how to remove them."
},
{
"code": null,
"e": 5529,
"s": 5447,
"text": "a and b in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 5609,
"s": 5529,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])"
},
{
"code": null,
"e": 5645,
"s": 5609,
"text": "Return a new array with shape (1,6)"
},
{
"code": null,
"e": 5703,
"s": 5645,
"text": ">>> b.resize(1,6) array([[1.5, 2. , 3. , 4. , 5. , 6. ]])"
},
{
"code": null,
"e": 5728,
"s": 5703,
"text": "Append items to an array"
},
{
"code": null,
"e": 5767,
"s": 5728,
"text": ">>> np.append(a,7) array([1, 2, 3, 7])"
},
{
"code": null,
"e": 5792,
"s": 5767,
"text": "Insert items in an array"
},
{
"code": null,
"e": 5833,
"s": 5792,
"text": ">>> np.insert(a,1,9) array([1, 9, 2, 3])"
},
{
"code": null,
"e": 5860,
"s": 5833,
"text": "Delete items from an array"
},
{
"code": null,
"e": 5895,
"s": 5860,
"text": ">>> np.delete(a,[1]) array([1, 3])"
},
{
"code": null,
"e": 6034,
"s": 5895,
"text": "In this section, you’ll learn how to change the look of an array. You’ll learn how to flatten, transpose, reshape, and concatenate arrays."
},
{
"code": null,
"e": 6120,
"s": 6034,
"text": "a, b, and d in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 6230,
"s": 6120,
"text": ">>> a = np.array([1, 2, 3])>>> b = np.array([[1.5, 2. , 3. ], [4. , 5. , 6. ]])>>> d = np.array([10, 15, 20])"
},
{
"code": null,
"e": 6247,
"s": 6230,
"text": "Flatten an array"
},
{
"code": null,
"e": 6299,
"s": 6247,
"text": ">>> b.ravel() array([1.5, 2. , 3. , 4. , 5. , 6. ])"
},
{
"code": null,
"e": 6334,
"s": 6299,
"text": "Reshape, but don’t change the data"
},
{
"code": null,
"e": 6411,
"s": 6334,
"text": ">>> b.reshape(3,2) array([[1.5, 2. ], [3. , 4. ], [5. , 6. ]])"
},
{
"code": null,
"e": 6430,
"s": 6411,
"text": "Concatenate arrays"
},
{
"code": null,
"e": 6495,
"s": 6430,
"text": ">>> np.concatenate((a,d),axis = 0) array([ 1, 2, 3, 10, 15, 20])"
},
{
"code": null,
"e": 6511,
"s": 6495,
"text": "Transpose array"
},
{
"code": null,
"e": 6589,
"s": 6511,
"text": ">>> np.transpose(b) array([[1.5, 4. ], [2. , 5. ], [3. , 6. ]])"
},
{
"code": null,
"e": 6668,
"s": 6589,
"text": "In this section, you’ll learn how to create a copy of an array for future use."
},
{
"code": null,
"e": 6747,
"s": 6668,
"text": "a in the code below is used as an example of an array throughout this section."
},
{
"code": null,
"e": 6775,
"s": 6747,
"text": ">>> a = np.array([1, 2, 3])"
},
{
"code": null,
"e": 6802,
"s": 6775,
"text": "Create a copy of the array"
},
{
"code": null,
"e": 6834,
"s": 6802,
"text": ">>> np.copy(a) array([1, 2, 3])"
},
{
"code": null,
"e": 6866,
"s": 6834,
"text": "Create a deep copy of the array"
},
{
"code": null,
"e": 6896,
"s": 6866,
"text": ">>> a.copy() array([1, 2, 3])"
},
{
"code": null,
"e": 6995,
"s": 6896,
"text": "In this section, you’ll learn how to sort an array so it’s decreasing to increasing or vice versa."
},
{
"code": null,
"e": 7077,
"s": 6995,
"text": "a and c in the code below are used as examples of arrays throughout this section."
},
{
"code": null,
"e": 7161,
"s": 7077,
"text": ">>> a = np.array([1, 2, 3])>>> c = np.array([[(1.5,2,3),(4,5,6)],[(3,2,1),(4,5,6)]]"
},
{
"code": null,
"e": 7175,
"s": 7161,
"text": "Sort an array"
},
{
"code": null,
"e": 7205,
"s": 7175,
"text": ">>> a.sort() array([1, 2, 3])"
},
{
"code": null,
"e": 7242,
"s": 7205,
"text": "Sort the elements of an array’s axis"
},
{
"code": null,
"e": 7263,
"s": 7242,
"text": ">>> c.sort(axis = 0)"
},
{
"code": null,
"e": 7328,
"s": 7263,
"text": "These are the different data types that can be in a NumPy array."
},
{
"code": null,
"e": 7359,
"s": 7328,
"text": "64-bit integer types: np.int64"
},
{
"code": null,
"e": 7403,
"s": 7359,
"text": "Double-precision floating point: np.float32"
},
{
"code": null,
"e": 7447,
"s": 7403,
"text": "Boolean type string TRUE and FALSE: np.bool"
},
{
"code": null,
"e": 7484,
"s": 7447,
"text": "Python object type values: np.object"
},
{
"code": null,
"e": 7520,
"s": 7484,
"text": "Fixed-length string type: np.string"
},
{
"code": null,
"e": 7559,
"s": 7520,
"text": "Fixed-length Unicode type: np.unicode_"
},
{
"code": null,
"e": 7755,
"s": 7559,
"text": "Python is the top dog when it comes to data science for now and in the foreseeable future. Knowledge of NumPy, one of its most powerful libraries is often a requirement for Data Scientists today."
},
{
"code": null,
"e": 7900,
"s": 7755,
"text": "Use this cheat sheet as a guide in the beginning and come back to it when needed, and you’ll be well on your way to mastering the NumPy library."
}
] |
Detecting Credit Card Fraud using Tensorflow | by Sarah Beshr | Towards Data Science | In this article, we’ll be leveraging the power of deep learning to solve a key issue that credit card companies often have to address, namely detecting fraudulent transactions. For this task, a Deep Neural Network (DNN) will be trained in order to do exactly that. We’ll walk through the following steps:
Data OverviewData PreprocessingDNN model buildingDNN model evaluationConclusion
Data Overview
Data Preprocessing
DNN model building
DNN model evaluation
Conclusion
Without further ado, let’s get started!
We got the dataset we’re using today from Kaggle and it contains two days’ worth of transactions by European cardholders. It’s important to note that due to the confidential nature of the data, a PCA transformation was done on 28 features and we have no information on what those feature names are. The only features that haven’t undergone this transformation and we can identify are ‘Time’, ‘Amount’, and ‘Class’. ‘Time’ represents the seconds elapsed between each transaction and the first transaction in the dataset. ‘Amount’ denotes the amount of each transaction and ‘Class’ refers to our target variable with 0 referring to a normal transaction and 1 referring to a fraudulent one. Our dataset also contains a total of 284,807 rows.
One thing we’d expect (and hope) from this dataset is that the target variable’s instances are imbalanced. This makes sense, right? It should as fraudulent transactions typically represent a minority of the cases. We can confirm this using the code below. We’ll also be changing the target variable’s column name so that it’s more intuitive.
#Rename Classdata.rename(columns={"Class": "isFraud"}, inplace=True)#Percentage of fraudfraud_per = data[data.isFraud == 1].isFraud.count() / data.isFraud.count()print(fraud_per)
This indeed turned out to be the case as only 0.17% of our transactions are fraudulent (whew)! While a low percentage of credit card fraud is certainly good news for a credit card company, it actually threatens the predictive performance of our network, especially for the fraudulent cases, so we’ll remedy this later using SMOTE. We’ll now investigate whether our dataset contains missing data.
# Looking for missing dataprint(data.isnull().any().sum())
The output shows that our dataset contains no missing values. Next, a correlation matrix can help give us an all-rounded understanding of how the variables in our dataset relate to each other.
#Correlation Plotplt.figure(figsize = (14,10))plt.title('Correlation Plot', size = 20)corr = data.corr()sns.heatmap(corr,xticklabels=corr.columns,yticklabels=corr.columns,linewidths=.1,cmap="Blues",fmt='.1f',annot=True)plt.show()
It’s now time to prepare our data so that it’s ready for training.
The first thing we’ll be doing is defining our features and our target variable.
# Defining x and yy = data["isFraud"]x = data.drop(["isFraud"], axis = 1)
One of the best practices for training a Neural Network is standardizing your data as it speeds up the training process. We’ll do so with the following code.
#Standardizationscaler = StandardScaler()x = scaler.fit_transform(x)
We’re close to the most exciting part which is training our network but not just yet, we still need to define our training and testing dataset.
# Train-Test splitX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)
But wait, haven’t we mentioned earlier that we’re dealing with a highly imbalanced dataset? Well, we did, and we’ll address this using Synthetic Minority Oversampling Technique (SMOTE). It might sound complicated but all it really is is just an oversampling technique that creates artificial minority class samples. In our case, it creates synthetic fraud instances and so corrects the imbalance in our dataset.
# SMOTEX_train_SMOTE, y_train_SMOTE = SMOTE().fit_sample(X_train, y_train)#SMOTE plotpd.Series(y_train_SMOTE).value_counts().plot(kind="bar")plt.title("Balanced Dataset")plt.show()
Aaand now it’s time to train our DNN. Firstly, ‘input_dim’ represents the number of features that we’re using for our training and ‘units’ denotes the number of neurons in each layer. We’ve come to this number of neurons and layers in our network using a trial and error approach. We also used ReLU as our activation function for the hidden layers and a sigmoid function for our output layer. An in-depth explanation of why these activation functions are best for our use case can be found here. Lastly, we used multiple dropout layers to prevent our network from overfitting.
# DNNmodel = keras.Sequential([layers.Dense(input_dim = 30, units = 128, activation = "relu"),layers.Dense(units= 64, activation = "relu"),layers.Dropout(0.2),layers.Dense(units= 32, activation = "relu"),layers.Dropout(0.2),layers.Dense(units= 32, activation = "relu"),layers.Dropout(0.2),layers.Dense(units= 16, activation = "relu"),layers.Dropout(0.2),layers.Dense(units=1, activation = "sigmoid")])model.summary()
With our model architecture ready, it’s time to compile, train and evaluate the model.
# Metricsmetrics = [ metrics.Accuracy(name="Accuracy"), metrics.Precision(name="Precision"), metrics.Recall(name="Recall")]# Compiling and fiting the modelmodel.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = metrics)model.fit(X_train_SMOTE, y_train_SMOTE, batch_size = 32, epochs = 100)print("Evaluate on test data")score = model.evaluate(X_test, y_test)print("test loss, test accuracy, test precision, test recall:", score)
We used ‘adam’ as our optimizer as it’s computationally efficient and is well suited for problems with a high number of parameters and ‘binary_crossentropy’ as our loss function as it’s most appropriate for our binary classification problem. For our evaluation, we’ll not only focus on accuracy as a metric but we’ll assess precision and recall too. Now let’s have a look at how the last 10 epochs went and how well our model performed on our test data.
We can clearly see that our model has performed well on our test data!
With this, we can round up our demonstration of how a DNN can be trained to predict credit card fraud. To recap, we’ve had a quick walkthrough for our data structure. We’ve assessed our target class imbalance and addressed it using SMOTE and we’ve standardized our data so that our training process is faster. We’ve trained and assessed our model and had results of 98% accuracy, 85% precision, and 82% recall on our test data! Annd that’s it. I would love to hear any questions or comments that you may have. | [
{
"code": null,
"e": 476,
"s": 171,
"text": "In this article, we’ll be leveraging the power of deep learning to solve a key issue that credit card companies often have to address, namely detecting fraudulent transactions. For this task, a Deep Neural Network (DNN) will be trained in order to do exactly that. We’ll walk through the following steps:"
},
{
"code": null,
"e": 556,
"s": 476,
"text": "Data OverviewData PreprocessingDNN model buildingDNN model evaluationConclusion"
},
{
"code": null,
"e": 570,
"s": 556,
"text": "Data Overview"
},
{
"code": null,
"e": 589,
"s": 570,
"text": "Data Preprocessing"
},
{
"code": null,
"e": 608,
"s": 589,
"text": "DNN model building"
},
{
"code": null,
"e": 629,
"s": 608,
"text": "DNN model evaluation"
},
{
"code": null,
"e": 640,
"s": 629,
"text": "Conclusion"
},
{
"code": null,
"e": 680,
"s": 640,
"text": "Without further ado, let’s get started!"
},
{
"code": null,
"e": 1419,
"s": 680,
"text": "We got the dataset we’re using today from Kaggle and it contains two days’ worth of transactions by European cardholders. It’s important to note that due to the confidential nature of the data, a PCA transformation was done on 28 features and we have no information on what those feature names are. The only features that haven’t undergone this transformation and we can identify are ‘Time’, ‘Amount’, and ‘Class’. ‘Time’ represents the seconds elapsed between each transaction and the first transaction in the dataset. ‘Amount’ denotes the amount of each transaction and ‘Class’ refers to our target variable with 0 referring to a normal transaction and 1 referring to a fraudulent one. Our dataset also contains a total of 284,807 rows."
},
{
"code": null,
"e": 1761,
"s": 1419,
"text": "One thing we’d expect (and hope) from this dataset is that the target variable’s instances are imbalanced. This makes sense, right? It should as fraudulent transactions typically represent a minority of the cases. We can confirm this using the code below. We’ll also be changing the target variable’s column name so that it’s more intuitive."
},
{
"code": null,
"e": 1940,
"s": 1761,
"text": "#Rename Classdata.rename(columns={\"Class\": \"isFraud\"}, inplace=True)#Percentage of fraudfraud_per = data[data.isFraud == 1].isFraud.count() / data.isFraud.count()print(fraud_per)"
},
{
"code": null,
"e": 2336,
"s": 1940,
"text": "This indeed turned out to be the case as only 0.17% of our transactions are fraudulent (whew)! While a low percentage of credit card fraud is certainly good news for a credit card company, it actually threatens the predictive performance of our network, especially for the fraudulent cases, so we’ll remedy this later using SMOTE. We’ll now investigate whether our dataset contains missing data."
},
{
"code": null,
"e": 2395,
"s": 2336,
"text": "# Looking for missing dataprint(data.isnull().any().sum())"
},
{
"code": null,
"e": 2588,
"s": 2395,
"text": "The output shows that our dataset contains no missing values. Next, a correlation matrix can help give us an all-rounded understanding of how the variables in our dataset relate to each other."
},
{
"code": null,
"e": 2818,
"s": 2588,
"text": "#Correlation Plotplt.figure(figsize = (14,10))plt.title('Correlation Plot', size = 20)corr = data.corr()sns.heatmap(corr,xticklabels=corr.columns,yticklabels=corr.columns,linewidths=.1,cmap=\"Blues\",fmt='.1f',annot=True)plt.show()"
},
{
"code": null,
"e": 2885,
"s": 2818,
"text": "It’s now time to prepare our data so that it’s ready for training."
},
{
"code": null,
"e": 2966,
"s": 2885,
"text": "The first thing we’ll be doing is defining our features and our target variable."
},
{
"code": null,
"e": 3040,
"s": 2966,
"text": "# Defining x and yy = data[\"isFraud\"]x = data.drop([\"isFraud\"], axis = 1)"
},
{
"code": null,
"e": 3198,
"s": 3040,
"text": "One of the best practices for training a Neural Network is standardizing your data as it speeds up the training process. We’ll do so with the following code."
},
{
"code": null,
"e": 3267,
"s": 3198,
"text": "#Standardizationscaler = StandardScaler()x = scaler.fit_transform(x)"
},
{
"code": null,
"e": 3411,
"s": 3267,
"text": "We’re close to the most exciting part which is training our network but not just yet, we still need to define our training and testing dataset."
},
{
"code": null,
"e": 3522,
"s": 3411,
"text": "# Train-Test splitX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)"
},
{
"code": null,
"e": 3934,
"s": 3522,
"text": "But wait, haven’t we mentioned earlier that we’re dealing with a highly imbalanced dataset? Well, we did, and we’ll address this using Synthetic Minority Oversampling Technique (SMOTE). It might sound complicated but all it really is is just an oversampling technique that creates artificial minority class samples. In our case, it creates synthetic fraud instances and so corrects the imbalance in our dataset."
},
{
"code": null,
"e": 4115,
"s": 3934,
"text": "# SMOTEX_train_SMOTE, y_train_SMOTE = SMOTE().fit_sample(X_train, y_train)#SMOTE plotpd.Series(y_train_SMOTE).value_counts().plot(kind=\"bar\")plt.title(\"Balanced Dataset\")plt.show()"
},
{
"code": null,
"e": 4692,
"s": 4115,
"text": "Aaand now it’s time to train our DNN. Firstly, ‘input_dim’ represents the number of features that we’re using for our training and ‘units’ denotes the number of neurons in each layer. We’ve come to this number of neurons and layers in our network using a trial and error approach. We also used ReLU as our activation function for the hidden layers and a sigmoid function for our output layer. An in-depth explanation of why these activation functions are best for our use case can be found here. Lastly, we used multiple dropout layers to prevent our network from overfitting."
},
{
"code": null,
"e": 5109,
"s": 4692,
"text": "# DNNmodel = keras.Sequential([layers.Dense(input_dim = 30, units = 128, activation = \"relu\"),layers.Dense(units= 64, activation = \"relu\"),layers.Dropout(0.2),layers.Dense(units= 32, activation = \"relu\"),layers.Dropout(0.2),layers.Dense(units= 32, activation = \"relu\"),layers.Dropout(0.2),layers.Dense(units= 16, activation = \"relu\"),layers.Dropout(0.2),layers.Dense(units=1, activation = \"sigmoid\")])model.summary()"
},
{
"code": null,
"e": 5196,
"s": 5109,
"text": "With our model architecture ready, it’s time to compile, train and evaluate the model."
},
{
"code": null,
"e": 5651,
"s": 5196,
"text": "# Metricsmetrics = [ metrics.Accuracy(name=\"Accuracy\"), metrics.Precision(name=\"Precision\"), metrics.Recall(name=\"Recall\")]# Compiling and fiting the modelmodel.compile(optimizer = \"adam\", loss = \"binary_crossentropy\", metrics = metrics)model.fit(X_train_SMOTE, y_train_SMOTE, batch_size = 32, epochs = 100)print(\"Evaluate on test data\")score = model.evaluate(X_test, y_test)print(\"test loss, test accuracy, test precision, test recall:\", score)"
},
{
"code": null,
"e": 6105,
"s": 5651,
"text": "We used ‘adam’ as our optimizer as it’s computationally efficient and is well suited for problems with a high number of parameters and ‘binary_crossentropy’ as our loss function as it’s most appropriate for our binary classification problem. For our evaluation, we’ll not only focus on accuracy as a metric but we’ll assess precision and recall too. Now let’s have a look at how the last 10 epochs went and how well our model performed on our test data."
},
{
"code": null,
"e": 6176,
"s": 6105,
"text": "We can clearly see that our model has performed well on our test data!"
}
] |
How to create GridView Layout in an Android App using Kotlin? | This example demonstrates how to create GridView Layout in an Android App using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.AdapterView.OnItemClickListener
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var gridView: GridView
private var playerNames = arrayOf("Cristiano Ronaldo", "Joao Felix", "Bernado Silva", "Andre Silve", "Bruno
Fernandez", "William Carvalho", "Nelson Semedo", "Pepe", "Rui Patricio")
private var playerImages = intArrayOf(R.drawable.ronaldo, R.drawable.felix, R.drawable.bernado,
R.drawable.andre,
R.drawable.bruno, R.drawable.carvalho, R.drawable.semedo, R.drawable.pepe, R.drawable.patricio)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
gridView = findViewById(R.id.gridView)
val mainAdapter = MainAdapter(this@MainActivity, playerNames, playerImages)
gridView.adapter = mainAdapter
gridView.onItemClickListener = OnItemClickListener { _, _, position, _ ->
Toast.makeText(applicationContext, "You CLicked " + playerNames[+position],
Toast.LENGTH_SHORT).show()
}
}
}
Step 4 − Create a Kotlin class (MyAdapter.kt) and add the following code
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
internal class MainAdapter(
private val context: Context,
private val numbersInWords: Array<String>,
private val numberImage: IntArray
) :
BaseAdapter() {
private var layoutInflater: LayoutInflater? = null
private lateinit var imageView: ImageView
private lateinit var textView: TextView
override fun getCount(): Int {
return numbersInWords.size
}
override fun getItem(position: Int): Any? {
return null
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup
): View? {
var convertView = convertView
if (layoutInflater == null) {
layoutInflater =
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}
if (convertView == null) {
convertView = layoutInflater!!.inflate(R.layout.rowitem, null)
}
imageView = convertView!!.findViewById(R.id.imageView)
textView = convertView.findViewById(R.id.textView)
imageView.setImageResource(numberImage[position])
textView.text = numbersInWords[position]
return convertView
}
}
Step 5 − Create a Layout Resource file (row_item.xml) and add the following code −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:padding="8dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp" />
<TextView
android:textAlignment="center"
android:gravity="center"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Numbers"
android:layout_marginBottom="10dp"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
Step 6 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how to create GridView Layout in an Android App using Kotlin."
},
{
"code": null,
"e": 1278,
"s": 1150,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1343,
"s": 1278,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1786,
"s": 1343,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<GridView\n android:id=\"@+id/gridView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:numColumns=\"2\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1841,
"s": 1786,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3062,
"s": 1841,
"text": "import android.os.Bundle\nimport android.widget.AdapterView.OnItemClickListener\nimport android.widget.GridView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var gridView: GridView\n private var playerNames = arrayOf(\"Cristiano Ronaldo\", \"Joao Felix\", \"Bernado Silva\", \"Andre Silve\", \"Bruno\n Fernandez\", \"William Carvalho\", \"Nelson Semedo\", \"Pepe\", \"Rui Patricio\")\n private var playerImages = intArrayOf(R.drawable.ronaldo, R.drawable.felix, R.drawable.bernado,\n R.drawable.andre,\n R.drawable.bruno, R.drawable.carvalho, R.drawable.semedo, R.drawable.pepe, R.drawable.patricio)\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n gridView = findViewById(R.id.gridView)\n val mainAdapter = MainAdapter(this@MainActivity, playerNames, playerImages)\n gridView.adapter = mainAdapter\n gridView.onItemClickListener = OnItemClickListener { _, _, position, _ ->\n Toast.makeText(applicationContext, \"You CLicked \" + playerNames[+position],\n Toast.LENGTH_SHORT).show()\n }\n }\n}"
},
{
"code": null,
"e": 3135,
"s": 3062,
"text": "Step 4 − Create a Kotlin class (MyAdapter.kt) and add the following code"
},
{
"code": null,
"e": 4528,
"s": 3135,
"text": "import android.content.Context\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.BaseAdapter\nimport android.widget.ImageView\nimport android.widget.TextView\ninternal class MainAdapter(\n private val context: Context,\n private val numbersInWords: Array<String>,\n private val numberImage: IntArray\n) :\nBaseAdapter() {\n private var layoutInflater: LayoutInflater? = null\n private lateinit var imageView: ImageView\n private lateinit var textView: TextView\n override fun getCount(): Int {\n return numbersInWords.size\n }\n override fun getItem(position: Int): Any? {\n return null\n }\n override fun getItemId(position: Int): Long {\n return 0\n }\n override fun getView(\n position: Int,\n convertView: View?,\n parent: ViewGroup\n ): View? {\n var convertView = convertView\n if (layoutInflater == null) {\n layoutInflater =\n context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater\n }\n if (convertView == null) {\n convertView = layoutInflater!!.inflate(R.layout.rowitem, null)\n }\n imageView = convertView!!.findViewById(R.id.imageView)\n textView = convertView.findViewById(R.id.textView)\n imageView.setImageResource(numberImage[position])\n textView.text = numbersInWords[position]\n return convertView\n }\n}"
},
{
"code": null,
"e": 4611,
"s": 4528,
"text": "Step 5 − Create a Layout Resource file (row_item.xml) and add the following code −"
},
{
"code": null,
"e": 5408,
"s": 4611,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n android:padding=\"8dp\">\n<ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"100dp\"\n android:layout_height=\"100dp\" />\n<TextView\n android:textAlignment=\"center\"\n android:gravity=\"center\"\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"16dp\"\n android:text=\"Numbers\"\n android:layout_marginBottom=\"10dp\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 5463,
"s": 5408,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6134,
"s": 5463,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6482,
"s": 6134,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Find longest length number in a string - GeeksforGeeks | 12 May, 2021
Given a string of digits and characters. Write a program to find the number with the maximum number of digits in a string. Note: The number may not be the greatest number in the string. For example, if the string is “a123bc321” then the answer can be 123 or 321 as the problem is to find the number with the longest length and not the largest value.Examples:
Input: geeks100for1234geeks
Output: 1234
Input: abx12321bst1234yz
Output: 12321
Approach: The idea is to traverse the string and if a digit is encountered, store its position and from that position traverse further until a character occurs. Every time a continuous series of a digit is encountered, store its length and match it with the length previously find series of a digit to find out the maximum of all the continuous series of digits.Below is the implementation of above approach.
C++
Java
C#
Python 3
PHP
Javascript
// C++ code for finding the longest// length integer#include <iostream>using namespace std; string longestInteger(string str, int l){ int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (int i = 0; i < l; i++) { // Store the previous position and previous length // of the digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, store its position in pos if (isdigit(str[i])) pos = i; // Traverse the string till a character occurs. while (isdigit(str[i])) { count++; i++; len++; } // Check if the length of the string is // greater than the previous ones or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.substr(pos, len));} // Driver codeint main(){ string str = "geeks100for1234geeks"; int l = str.length(); cout << longestInteger(str, l); return 0;}
// Java code for finding the// longest length integerimport java.io.*;import java.util.*;import java.lang.*; class GFG{static String longestInteger(String str, int l){ int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (int i = 0; i < l; i++) { // Store the previous position // and previous length of the // digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, // store its position in pos if (Character.isDigit(str.charAt(i))) pos = i; // Traverse the string // till a character occurs. while (Character.isDigit(str.charAt(i))) { count++; i++; len++; } // Check if the length of // the string is greater // than the previous ones // or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.substring(pos, pos + len));} // Driver codepublic static void main(String[] args){ String str = "geeks100for1234geeks"; int l = str.length(); System.out.print(longestInteger(str, l));}}
// C# code for finding the// longest length integerusing System; class GFG{static string longestInteger(string str, int l){ int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (int i = 0; i < l; i++) { // Store the previous position // and previous length of the // digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, // store its position in pos if (Char.IsDigit(str[i])) pos = i; // Traverse the string // till a character occurs. while (Char.IsDigit(str[i])) { count++; i++; len++; } // Check if the length of // the string is greater // than the previous ones // or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.Substring(pos, len));} // Driver codepublic static void Main(){ string str = "geeks100for1234geeks"; int l = str.Length; Console.Write(longestInteger(str, l));}} // This code is contributed// by ChitraNayal
# Python 3 code for finding the# longest length integer def longestInteger(s, length): count = 0 maximum = 0 pos = -1 l = 0 # Traverse the string for i in range(length): # Store the previous position # and previous length of # the digits encountered. pre_pos = pos pre_len = l count = 0 l = 0 # If first digit occurs, # store its position in pos if (s[i].isdecimal()): pos = i # Traverse the string # till a character occurs. while (s[i].isdecimal()): count += 1 i += 1 l += 1 # Check if the length of # the string is greater # than the previous ones # or not. if (count > maximum): maximum = count else: pos = pre_pos l = pre_len return (s[pos: pos + l]) # Driver codes = "geeks100for1234geeks"length = len(s)print(longestInteger(s, length)) # This code is contributed# by ChitraNayal
<?php// PHP code for finding the// longest length integer function longestInteger($str, $l){ $count = 0; $max = 0; $pos = -1; $pre_pos = 0; $pre_len = 0; $len = 0; // Traverse the string for ($i = 0; $i < $l; $i++) { // Store the previous position // and previous length of // the digits encountered. $pre_pos = $pos; $pre_len = $len; $count = 0; $len = 0; // If first digit occurs, // store its position in pos if (is_numeric($str[$i])) $pos = $i; // Traverse the string till // a character occurs. while (is_numeric($str[$i])) { $count++; $i++; $len++; } // Check if the length of // the string is greater // than the previous ones // or not. if ($count > $max) { $max = $count; } else { $pos = $pre_pos; $len = $pre_len; } } return (substr($str, $pos, $len));} // Driver code$str = "geeks100for1234geeks";$l = strlen($str);echo longestInteger($str, $l); // This code is contributed// by ChitraNayal?>
<script>// Javascript code for finding the// longest length integer function longestInteger(str,l) { let count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (let i = 0; i < l; i++) { // Store the previous position // and previous length of the // digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, // store its position in pos if (!isNaN(String(str[i]) * 1)) pos = i; // Traverse the string // till a character occurs. while (!isNaN(String(str[i]) * 1)) { count++; i++; len++; } // Check if the length of // the string is greater // than the previous ones // or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.substring(pos, pos + len)); } // Driver code let str = "geeks100for1234geeks"; let l = str.length; document.write(longestInteger(str, l)); // This code is contributed by rag2127</script>
1234
Time Complexity: O(n) Auxiliary Space Complexity: O(1)
ukasp
ManasChhabra2
rag2127
C-String-Question
school-programming
C++ Programs
School Programming
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++
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 25799,
"s": 25771,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 26160,
"s": 25799,
"text": "Given a string of digits and characters. Write a program to find the number with the maximum number of digits in a string. Note: The number may not be the greatest number in the string. For example, if the string is “a123bc321” then the answer can be 123 or 321 as the problem is to find the number with the longest length and not the largest value.Examples: "
},
{
"code": null,
"e": 26241,
"s": 26160,
"text": "Input: geeks100for1234geeks\nOutput: 1234\n\nInput: abx12321bst1234yz\nOutput: 12321"
},
{
"code": null,
"e": 26654,
"s": 26243,
"text": "Approach: The idea is to traverse the string and if a digit is encountered, store its position and from that position traverse further until a character occurs. Every time a continuous series of a digit is encountered, store its length and match it with the length previously find series of a digit to find out the maximum of all the continuous series of digits.Below is the implementation of above approach. "
},
{
"code": null,
"e": 26658,
"s": 26654,
"text": "C++"
},
{
"code": null,
"e": 26663,
"s": 26658,
"text": "Java"
},
{
"code": null,
"e": 26666,
"s": 26663,
"text": "C#"
},
{
"code": null,
"e": 26675,
"s": 26666,
"text": "Python 3"
},
{
"code": null,
"e": 26679,
"s": 26675,
"text": "PHP"
},
{
"code": null,
"e": 26690,
"s": 26679,
"text": "Javascript"
},
{
"code": "// C++ code for finding the longest// length integer#include <iostream>using namespace std; string longestInteger(string str, int l){ int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (int i = 0; i < l; i++) { // Store the previous position and previous length // of the digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, store its position in pos if (isdigit(str[i])) pos = i; // Traverse the string till a character occurs. while (isdigit(str[i])) { count++; i++; len++; } // Check if the length of the string is // greater than the previous ones or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.substr(pos, len));} // Driver codeint main(){ string str = \"geeks100for1234geeks\"; int l = str.length(); cout << longestInteger(str, l); return 0;}",
"e": 27791,
"s": 26690,
"text": null
},
{
"code": "// Java code for finding the// longest length integerimport java.io.*;import java.util.*;import java.lang.*; class GFG{static String longestInteger(String str, int l){ int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (int i = 0; i < l; i++) { // Store the previous position // and previous length of the // digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, // store its position in pos if (Character.isDigit(str.charAt(i))) pos = i; // Traverse the string // till a character occurs. while (Character.isDigit(str.charAt(i))) { count++; i++; len++; } // Check if the length of // the string is greater // than the previous ones // or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.substring(pos, pos + len));} // Driver codepublic static void main(String[] args){ String str = \"geeks100for1234geeks\"; int l = str.length(); System.out.print(longestInteger(str, l));}}",
"e": 29088,
"s": 27791,
"text": null
},
{
"code": "// C# code for finding the// longest length integerusing System; class GFG{static string longestInteger(string str, int l){ int count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (int i = 0; i < l; i++) { // Store the previous position // and previous length of the // digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, // store its position in pos if (Char.IsDigit(str[i])) pos = i; // Traverse the string // till a character occurs. while (Char.IsDigit(str[i])) { count++; i++; len++; } // Check if the length of // the string is greater // than the previous ones // or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.Substring(pos, len));} // Driver codepublic static void Main(){ string str = \"geeks100for1234geeks\"; int l = str.Length; Console.Write(longestInteger(str, l));}} // This code is contributed// by ChitraNayal",
"e": 30366,
"s": 29088,
"text": null
},
{
"code": "# Python 3 code for finding the# longest length integer def longestInteger(s, length): count = 0 maximum = 0 pos = -1 l = 0 # Traverse the string for i in range(length): # Store the previous position # and previous length of # the digits encountered. pre_pos = pos pre_len = l count = 0 l = 0 # If first digit occurs, # store its position in pos if (s[i].isdecimal()): pos = i # Traverse the string # till a character occurs. while (s[i].isdecimal()): count += 1 i += 1 l += 1 # Check if the length of # the string is greater # than the previous ones # or not. if (count > maximum): maximum = count else: pos = pre_pos l = pre_len return (s[pos: pos + l]) # Driver codes = \"geeks100for1234geeks\"length = len(s)print(longestInteger(s, length)) # This code is contributed# by ChitraNayal",
"e": 31410,
"s": 30366,
"text": null
},
{
"code": "<?php// PHP code for finding the// longest length integer function longestInteger($str, $l){ $count = 0; $max = 0; $pos = -1; $pre_pos = 0; $pre_len = 0; $len = 0; // Traverse the string for ($i = 0; $i < $l; $i++) { // Store the previous position // and previous length of // the digits encountered. $pre_pos = $pos; $pre_len = $len; $count = 0; $len = 0; // If first digit occurs, // store its position in pos if (is_numeric($str[$i])) $pos = $i; // Traverse the string till // a character occurs. while (is_numeric($str[$i])) { $count++; $i++; $len++; } // Check if the length of // the string is greater // than the previous ones // or not. if ($count > $max) { $max = $count; } else { $pos = $pre_pos; $len = $pre_len; } } return (substr($str, $pos, $len));} // Driver code$str = \"geeks100for1234geeks\";$l = strlen($str);echo longestInteger($str, $l); // This code is contributed// by ChitraNayal?>",
"e": 32607,
"s": 31410,
"text": null
},
{
"code": "<script>// Javascript code for finding the// longest length integer function longestInteger(str,l) { let count = 0, max = 0, pos = -1, pre_pos, pre_len, len = 0; // Traverse the string for (let i = 0; i < l; i++) { // Store the previous position // and previous length of the // digits encountered. pre_pos = pos; pre_len = len; count = 0; len = 0; // If first digit occurs, // store its position in pos if (!isNaN(String(str[i]) * 1)) pos = i; // Traverse the string // till a character occurs. while (!isNaN(String(str[i]) * 1)) { count++; i++; len++; } // Check if the length of // the string is greater // than the previous ones // or not. if (count > max) { max = count; } else { pos = pre_pos; len = pre_len; } } return (str.substring(pos, pos + len)); } // Driver code let str = \"geeks100for1234geeks\"; let l = str.length; document.write(longestInteger(str, l)); // This code is contributed by rag2127</script>",
"e": 33865,
"s": 32607,
"text": null
},
{
"code": null,
"e": 33870,
"s": 33865,
"text": "1234"
},
{
"code": null,
"e": 33928,
"s": 33872,
"text": "Time Complexity: O(n) Auxiliary Space Complexity: O(1) "
},
{
"code": null,
"e": 33934,
"s": 33928,
"text": "ukasp"
},
{
"code": null,
"e": 33948,
"s": 33934,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 33956,
"s": 33948,
"text": "rag2127"
},
{
"code": null,
"e": 33974,
"s": 33956,
"text": "C-String-Question"
},
{
"code": null,
"e": 33993,
"s": 33974,
"text": "school-programming"
},
{
"code": null,
"e": 34006,
"s": 33993,
"text": "C++ Programs"
},
{
"code": null,
"e": 34025,
"s": 34006,
"text": "School Programming"
},
{
"code": null,
"e": 34123,
"s": 34025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34164,
"s": 34123,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 34223,
"s": 34164,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 34244,
"s": 34223,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 34256,
"s": 34244,
"text": "cout in C++"
},
{
"code": null,
"e": 34277,
"s": 34256,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 34295,
"s": 34277,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34311,
"s": 34295,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34330,
"s": 34311,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 34355,
"s": 34330,
"text": "Reverse a string in Java"
}
] |
How to check an element is exists in array or not in PHP ? - GeeksforGeeks | 31 Oct, 2021
An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods :
Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not.
in_array(element , array)
Arguments :
element: The element to check in the array
array: The array to look for element
Example:
PHP
<?php // Declaring an array object $arr = array("Hello", "GEEKs" , "User" , "PHP");print("Original Array </br>");print (json_encode($arr) . " </br>"); // Declaring element$ele = "GEEKs"; // Check if element existsif(in_array($ele, $arr)){ print($ele . " - Element found.");}else{ print($ele . "Element not found.");}?>
Output:
Original Array:
["Hello","GEEKs","User","PHP"]
GEEKs - Element found.
Approach 2 (Using for loop): A for loop iteration is done throughout the array. A boolean flag is declared to check for the presence of an element. It is initialized to the boolean value of false. In case the value is false, and the element is found in the array, the flag value is changed to the true value. No further modifications in the flag value are made.
Example:
PHP
<?php // Declaring an array object $arr = array(1, 3, 5, 6);print("Original Array </br>");print (json_encode($arr)." </br>"); // Declaring element$ele = 5; // Declare a flag $flag = FALSE; // Check if element existsforeach($arr as $val){ if($flag == FALSE){ if($val == $ele){ $flag = TRUE; } }}if($flag ==TRUE){ print($ele . " - Element found.");}else{ print($ele . " - Element not found.");}?>
Output:
Original Array
[1, 3, 5, 6]
5 - Element found.
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
PHP str_replace() Function
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 26398,
"s": 26217,
"text": "An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods :"
},
{
"code": null,
"e": 26670,
"s": 26398,
"text": "Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not. "
},
{
"code": null,
"e": 26696,
"s": 26670,
"text": "in_array(element , array)"
},
{
"code": null,
"e": 26709,
"s": 26696,
"text": "Arguments : "
},
{
"code": null,
"e": 26752,
"s": 26709,
"text": "element: The element to check in the array"
},
{
"code": null,
"e": 26789,
"s": 26752,
"text": "array: The array to look for element"
},
{
"code": null,
"e": 26798,
"s": 26789,
"text": "Example:"
},
{
"code": null,
"e": 26802,
"s": 26798,
"text": "PHP"
},
{
"code": "<?php // Declaring an array object $arr = array(\"Hello\", \"GEEKs\" , \"User\" , \"PHP\");print(\"Original Array </br>\");print (json_encode($arr) . \" </br>\"); // Declaring element$ele = \"GEEKs\"; // Check if element existsif(in_array($ele, $arr)){ print($ele . \" - Element found.\");}else{ print($ele . \"Element not found.\");}?>",
"e": 27130,
"s": 26802,
"text": null
},
{
"code": null,
"e": 27138,
"s": 27130,
"text": "Output:"
},
{
"code": null,
"e": 27208,
"s": 27138,
"text": "Original Array:\n[\"Hello\",\"GEEKs\",\"User\",\"PHP\"]\nGEEKs - Element found."
},
{
"code": null,
"e": 27571,
"s": 27208,
"text": "Approach 2 (Using for loop): A for loop iteration is done throughout the array. A boolean flag is declared to check for the presence of an element. It is initialized to the boolean value of false. In case the value is false, and the element is found in the array, the flag value is changed to the true value. No further modifications in the flag value are made. "
},
{
"code": null,
"e": 27580,
"s": 27571,
"text": "Example:"
},
{
"code": null,
"e": 27584,
"s": 27580,
"text": "PHP"
},
{
"code": "<?php // Declaring an array object $arr = array(1, 3, 5, 6);print(\"Original Array </br>\");print (json_encode($arr).\" </br>\"); // Declaring element$ele = 5; // Declare a flag $flag = FALSE; // Check if element existsforeach($arr as $val){ if($flag == FALSE){ if($val == $ele){ $flag = TRUE; } }}if($flag ==TRUE){ print($ele . \" - Element found.\");}else{ print($ele . \" - Element not found.\");}?>",
"e": 28020,
"s": 27584,
"text": null
},
{
"code": null,
"e": 28028,
"s": 28020,
"text": "Output:"
},
{
"code": null,
"e": 28075,
"s": 28028,
"text": "Original Array\n[1, 3, 5, 6]\n5 - Element found."
},
{
"code": null,
"e": 28088,
"s": 28075,
"text": "PHP-function"
},
{
"code": null,
"e": 28102,
"s": 28088,
"text": "PHP-Questions"
},
{
"code": null,
"e": 28109,
"s": 28102,
"text": "Picked"
},
{
"code": null,
"e": 28113,
"s": 28109,
"text": "PHP"
},
{
"code": null,
"e": 28130,
"s": 28113,
"text": "Web Technologies"
},
{
"code": null,
"e": 28134,
"s": 28130,
"text": "PHP"
},
{
"code": null,
"e": 28232,
"s": 28134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28314,
"s": 28232,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28341,
"s": 28314,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 28383,
"s": 28341,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28434,
"s": 28383,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 28508,
"s": 28434,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 28548,
"s": 28508,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28581,
"s": 28548,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28626,
"s": 28581,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28669,
"s": 28626,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Enumeration hasMoreElements() Method in Java with Examples - GeeksforGeeks | 27 Jun, 2019
An object that implements the Enumeration interface generates a series of elements, one at a time. hasMoreElements() method of Enumeration used to tests if this enumeration contains more elements. If enumeration contains more element then it will return true else false.
Syntax:
boolean hasMoreElements()
Parameters: This method accepts nothing.
Return value: This method returns true if and only if this enumeration object contains at least one more element to provide; false otherwise.
Below programs illustrate hasMoreElements() method:Program 1:
// Java program to demonstrate// Enumeration.hasMoreElements() method import java.util.*; public class GFG { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Enumeration Days; Vector week = new Vector(); week.add("Sunday"); week.add("Monday"); week.add("Tuesday"); week.add("Wednesday"); week.add("Thursday"); week.add("Friday"); week.add("Saturday"); Days = week.elements(); while (Days.hasMoreElements()) { System.out.println("Day = " + Days.nextElement()); } }}
Day = Sunday
Day = Monday
Day = Tuesday
Day = Wednesday
Day = Thursday
Day = Friday
Day = Saturday
Program 2:
// Java program to demonstrate// Enumeration.hasMoreElements() method import java.util.*; public class GFG { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Enumeration<Integer> classNine; Vector<Integer> rollno = new Vector<Integer>(); rollno.add(1); rollno.add(2); rollno.add(3); rollno.add(4); rollno.add(5); rollno.add(6); rollno.add(7); rollno.add(8); classNine = rollno.elements(); while (classNine.hasMoreElements()) { System.out.println("Roll No = " + classNine.nextElement()); } }}
Roll No = 1
Roll No = 2
Roll No = 3
Roll No = 4
Roll No = 5
Roll No = 6
Roll No = 7
Roll No = 8
References: https://docs.oracle.com/javase/10/docs/api/java/util/Enumeration.html#hasMoreElements()
Java - util package
Java-Enumeration
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 25618,
"s": 25347,
"text": "An object that implements the Enumeration interface generates a series of elements, one at a time. hasMoreElements() method of Enumeration used to tests if this enumeration contains more elements. If enumeration contains more element then it will return true else false."
},
{
"code": null,
"e": 25626,
"s": 25618,
"text": "Syntax:"
},
{
"code": null,
"e": 25653,
"s": 25626,
"text": "boolean hasMoreElements()\n"
},
{
"code": null,
"e": 25694,
"s": 25653,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 25836,
"s": 25694,
"text": "Return value: This method returns true if and only if this enumeration object contains at least one more element to provide; false otherwise."
},
{
"code": null,
"e": 25898,
"s": 25836,
"text": "Below programs illustrate hasMoreElements() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Enumeration.hasMoreElements() method import java.util.*; public class GFG { @SuppressWarnings({ \"unchecked\", \"rawtypes\" }) public static void main(String[] args) { Enumeration Days; Vector week = new Vector(); week.add(\"Sunday\"); week.add(\"Monday\"); week.add(\"Tuesday\"); week.add(\"Wednesday\"); week.add(\"Thursday\"); week.add(\"Friday\"); week.add(\"Saturday\"); Days = week.elements(); while (Days.hasMoreElements()) { System.out.println(\"Day = \" + Days.nextElement()); } }}",
"e": 26549,
"s": 25898,
"text": null
},
{
"code": null,
"e": 26649,
"s": 26549,
"text": "Day = Sunday\nDay = Monday\nDay = Tuesday\nDay = Wednesday\nDay = Thursday\nDay = Friday\nDay = Saturday\n"
},
{
"code": null,
"e": 26660,
"s": 26649,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Enumeration.hasMoreElements() method import java.util.*; public class GFG { @SuppressWarnings({ \"unchecked\", \"rawtypes\" }) public static void main(String[] args) { Enumeration<Integer> classNine; Vector<Integer> rollno = new Vector<Integer>(); rollno.add(1); rollno.add(2); rollno.add(3); rollno.add(4); rollno.add(5); rollno.add(6); rollno.add(7); rollno.add(8); classNine = rollno.elements(); while (classNine.hasMoreElements()) { System.out.println(\"Roll No = \" + classNine.nextElement()); } }}",
"e": 27345,
"s": 26660,
"text": null
},
{
"code": null,
"e": 27442,
"s": 27345,
"text": "Roll No = 1\nRoll No = 2\nRoll No = 3\nRoll No = 4\nRoll No = 5\nRoll No = 6\nRoll No = 7\nRoll No = 8\n"
},
{
"code": null,
"e": 27542,
"s": 27442,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Enumeration.html#hasMoreElements()"
},
{
"code": null,
"e": 27562,
"s": 27542,
"text": "Java - util package"
},
{
"code": null,
"e": 27579,
"s": 27562,
"text": "Java-Enumeration"
},
{
"code": null,
"e": 27594,
"s": 27579,
"text": "Java-Functions"
},
{
"code": null,
"e": 27599,
"s": 27594,
"text": "Java"
},
{
"code": null,
"e": 27604,
"s": 27599,
"text": "Java"
},
{
"code": null,
"e": 27702,
"s": 27604,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27717,
"s": 27702,
"text": "Stream In Java"
},
{
"code": null,
"e": 27738,
"s": 27717,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27757,
"s": 27738,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27787,
"s": 27757,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27833,
"s": 27787,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27850,
"s": 27833,
"text": "Generics in Java"
},
{
"code": null,
"e": 27871,
"s": 27850,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27914,
"s": 27871,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27936,
"s": 27914,
"text": "PriorityQueue in Java"
}
] |
Boyer-Moore Majority Voting Algorithm - GeeksforGeeks | 24 Feb, 2022
The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than N/ 2 occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in O(N) time complexity and O(1) space complexity.
Let us see the algorithm and intuition behind its working, by taking an example –
Input :{1,1,1,1,2,3,5}
Output : 1
Explanation : 1 occurs more than 3 times.
Input : {1,2,3}
Output : -1
This algorithm works on the fact that if an element occurs more than N/2 times, it means that the remaining elements other than this would definitely be less than N/2. So let us check the proceeding of the algorithm.
First, choose a candidate from the given set of elements if it is the same as the candidate element, increase the votes. Otherwise, decrease the votes if votes become 0, select another new element as the new candidate.
Intuition Behind Working :When the elements are the same as the candidate element, votes are incremented when some other element is found not equal to the candidate element. We decreased the count. This actually means that we are decreasing the priority of winning ability of the selected candidate, since we know that if the candidate is a majority it occurs more than N/2 times and the remaining elements are less than N/2. We keep decreasing the votes since we found some different element than the candidate element. When votes become 0, this actually means that there are the same number of different elements, which should not be the case for the element to be the majority element. So the candidate element cannot be the majority, so we choose the present element as the candidate and continue the same till all the elements get finished. The final candidate would be our majority element. We check using the 2nd traversal to see whether its count is greater than N/2. If it is true, we consider it as the majority element.
Steps to implement the algorithm :Step 1 – Find a candidate with the majority –
Initialize a variable say i ,votes = 0, candidate =-1
Traverse through the array using for loop
If votes = 0, choose the candidate = arr[i] , make votes=1.
else if the current element is the same as the candidate increment votes
else decrement votes.
Step 2 – Check if the candidate has more than N/2 votes –
Initialize a variable count =0 and increment count if it is the same as the candidate.
If the count is >N/2, return the candidate.
else return -1.
Dry run for the above example:
Given :
arr[]= 1 1 1 1 2 3 5
votes =0 1 2 3 4 3 2 1
candidate = -1 1 1 1 1 1 1 1
candidate = 1 after first traversal
1 1 1 1 2 3 5
count =0 1 2 3 4 4 4 4
candidate = 1
Hence count > 7/2 =3
So 1 is the majority element.
C++
Java
Python3
C#
Javascript
// C++ implementation for the above approach#include <iostream>using namespace std;// Function to find majority elementint findMajority(int arr[], int n){ int i, candidate = -1, votes = 0; // Finding majority candidate for (i = 0; i < n; i++) { if (votes == 0) { candidate = arr[i]; votes = 1; } else { if (arr[i] == candidate) votes++; else votes--; } } int count = 0; // Checking if majority candidate occurs more than n/2 // times for (i = 0; i < n; i++) { if (arr[i] == candidate) count++; } if (count > n / 2) return candidate; return -1;}int main(){ int arr[] = { 1, 1, 1, 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int majority = findMajority(arr, n); cout << " The majority element is : " << majority; return 0;}
import java.io.*; class GFG{ // Function to find majority element public static int findMajority(int[] nums) { int count = 0, candidate = -1; // Finding majority candidate for (int index = 0; index < nums.length; index++) { if (count == 0) { candidate = nums[index]; count = 1; } else { if (nums[index] == candidate) count++; else count--; } } // Checking if majority candidate occurs more than // n/2 times count = 0; for (int index = 0; index < nums.length; index++) { if (nums[index] == candidate) count++; } if (count > (nums.length / 2)) return candidate; return -1; // The last for loop and the if statement step can // be skip if a majority element is confirmed to // be present in an array just return candidate // in that case } // Driver code public static void main(String[] args) { int arr[] = { 1, 1, 1, 1, 2, 3, 4 }; int majority = findMajority(arr); System.out.println(" The majority element is : " + majority); }} // This code is contribute by Arnav Sharma
# Python implementation for the above approach # Function to find majority elementdef findMajority(arr, n): candidate = -1 votes = 0 # Finding majority candidate for i in range (n): if (votes == 0): candidate = arr[i] votes = 1 else: if (arr[i] == candidate): votes += 1 else: votes -= 1 count = 0 # Checking if majority candidate occurs more than n/2 # times for i in range (n): if (arr[i] == candidate): count += 1 if (count > n // 2): return candidate else: return -1 # Driver Code arr = [ 1, 1, 1, 1, 2, 3, 4 ]n = len(arr)majority = findMajority(arr, n)print(" The majority element is :" ,majority) # This code is contributed by shivanisinghss2110
using System; class GFG{ // Function to find majority element public static int findMajority(int[] nums) { int count = 0, candidate = -1; // Finding majority candidate for (int index = 0; index < nums.Length; index++) { if (count == 0) { candidate = nums[index]; count = 1; } else { if (nums[index] == candidate) count++; else count--; } } // Checking if majority candidate occurs more than // n/2 times count = 0; for (int index = 0; index < nums.Length; index++) { if (nums[index] == candidate) count++; } if (count > (nums.Length / 2)) return candidate; return -1; // The last for loop and the if statement step can // be skip if a majority element is confirmed to // be present in an array just return candidate // in that case } // Driver code public static void Main(String[] args) { int []arr = { 1, 1, 1, 1, 2, 3, 4}; int majority = findMajority(arr); Console.Write(" The majority element is : " + majority); }} // This code is contributed by shivanisinghss2110
<script>// Function to find majority elementfunction findMajority(nums) { var count = 0, candidate = -1; // Finding majority candidate for (var index = 0; index < nums.length; index++) { if (count == 0) { candidate = nums[index]; count = 1; } else { if (nums[index] == candidate) count++; else count--; } } // Checking if majority candidate occurs more than // n/2 times count = 0; for (var index = 0; index < nums.length; index++) { if (nums[index] == candidate) count++; } if (count > (nums.length / 2)) return candidate; return -1; // The last for loop and the if statement step can // be skip if a majority element is confirmed to // be present in an array just return candidate // in that case } // Driver code var arr = [ 1, 1, 1, 1, 2, 3, 4 ]; var majority = findMajority(arr); document.write(" The majority element is : " + majority); // This code is contributed by shivanisinghss2110. </script>
The majority element is : 1
Time Complexity: O(n) ( For two passes over the array )Space Complexity: O(1)
arnavsharma2711
shivanisinghss2110
murugank0204
tanveerbaba30
Moore's Voting Algorithm
Picked
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construct Pushdown Automata for all length palindrome
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Construct a Turing Machine for language L = {ww | w ∈ {0,1}}
NPDA for accepting the language L = {an bn | n>=1}
Decidability and Undecidability in TOC
Decidable and Undecidable problems in Theory of Computation
Halting Problem in Theory of Computation
Pushdown Automata Acceptance by Final State
Context-sensitive Grammar (CSG) and Language (CSL)
NPDA for accepting the language L = {anbm | n,m ≥ 1 and n ≠ m} | [
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 25336,
"s": 24984,
"text": "The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than N/ 2 occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in O(N) time complexity and O(1) space complexity."
},
{
"code": null,
"e": 25418,
"s": 25336,
"text": "Let us see the algorithm and intuition behind its working, by taking an example –"
},
{
"code": null,
"e": 25522,
"s": 25418,
"text": "Input :{1,1,1,1,2,3,5}\nOutput : 1\nExplanation : 1 occurs more than 3 times.\nInput : {1,2,3}\nOutput : -1"
},
{
"code": null,
"e": 25739,
"s": 25522,
"text": "This algorithm works on the fact that if an element occurs more than N/2 times, it means that the remaining elements other than this would definitely be less than N/2. So let us check the proceeding of the algorithm."
},
{
"code": null,
"e": 25958,
"s": 25739,
"text": "First, choose a candidate from the given set of elements if it is the same as the candidate element, increase the votes. Otherwise, decrease the votes if votes become 0, select another new element as the new candidate."
},
{
"code": null,
"e": 26989,
"s": 25958,
"text": "Intuition Behind Working :When the elements are the same as the candidate element, votes are incremented when some other element is found not equal to the candidate element. We decreased the count. This actually means that we are decreasing the priority of winning ability of the selected candidate, since we know that if the candidate is a majority it occurs more than N/2 times and the remaining elements are less than N/2. We keep decreasing the votes since we found some different element than the candidate element. When votes become 0, this actually means that there are the same number of different elements, which should not be the case for the element to be the majority element. So the candidate element cannot be the majority, so we choose the present element as the candidate and continue the same till all the elements get finished. The final candidate would be our majority element. We check using the 2nd traversal to see whether its count is greater than N/2. If it is true, we consider it as the majority element."
},
{
"code": null,
"e": 27069,
"s": 26989,
"text": "Steps to implement the algorithm :Step 1 – Find a candidate with the majority –"
},
{
"code": null,
"e": 27124,
"s": 27069,
"text": "Initialize a variable say i ,votes = 0, candidate =-1 "
},
{
"code": null,
"e": 27166,
"s": 27124,
"text": "Traverse through the array using for loop"
},
{
"code": null,
"e": 27226,
"s": 27166,
"text": "If votes = 0, choose the candidate = arr[i] , make votes=1."
},
{
"code": null,
"e": 27299,
"s": 27226,
"text": "else if the current element is the same as the candidate increment votes"
},
{
"code": null,
"e": 27321,
"s": 27299,
"text": "else decrement votes."
},
{
"code": null,
"e": 27379,
"s": 27321,
"text": "Step 2 – Check if the candidate has more than N/2 votes –"
},
{
"code": null,
"e": 27466,
"s": 27379,
"text": "Initialize a variable count =0 and increment count if it is the same as the candidate."
},
{
"code": null,
"e": 27510,
"s": 27466,
"text": "If the count is >N/2, return the candidate."
},
{
"code": null,
"e": 27526,
"s": 27510,
"text": "else return -1."
},
{
"code": null,
"e": 27915,
"s": 27526,
"text": "Dry run for the above example: \nGiven :\n arr[]= 1 1 1 1 2 3 5\n votes =0 1 2 3 4 3 2 1\n candidate = -1 1 1 1 1 1 1 1\n candidate = 1 after first traversal\n 1 1 1 1 2 3 5\n count =0 1 2 3 4 4 4 4 \n candidate = 1 \n Hence count > 7/2 =3\n So 1 is the majority element."
},
{
"code": null,
"e": 27919,
"s": 27915,
"text": "C++"
},
{
"code": null,
"e": 27924,
"s": 27919,
"text": "Java"
},
{
"code": null,
"e": 27932,
"s": 27924,
"text": "Python3"
},
{
"code": null,
"e": 27935,
"s": 27932,
"text": "C#"
},
{
"code": null,
"e": 27946,
"s": 27935,
"text": "Javascript"
},
{
"code": "// C++ implementation for the above approach#include <iostream>using namespace std;// Function to find majority elementint findMajority(int arr[], int n){ int i, candidate = -1, votes = 0; // Finding majority candidate for (i = 0; i < n; i++) { if (votes == 0) { candidate = arr[i]; votes = 1; } else { if (arr[i] == candidate) votes++; else votes--; } } int count = 0; // Checking if majority candidate occurs more than n/2 // times for (i = 0; i < n; i++) { if (arr[i] == candidate) count++; } if (count > n / 2) return candidate; return -1;}int main(){ int arr[] = { 1, 1, 1, 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int majority = findMajority(arr, n); cout << \" The majority element is : \" << majority; return 0;}",
"e": 28852,
"s": 27946,
"text": null
},
{
"code": "import java.io.*; class GFG{ // Function to find majority element public static int findMajority(int[] nums) { int count = 0, candidate = -1; // Finding majority candidate for (int index = 0; index < nums.length; index++) { if (count == 0) { candidate = nums[index]; count = 1; } else { if (nums[index] == candidate) count++; else count--; } } // Checking if majority candidate occurs more than // n/2 times count = 0; for (int index = 0; index < nums.length; index++) { if (nums[index] == candidate) count++; } if (count > (nums.length / 2)) return candidate; return -1; // The last for loop and the if statement step can // be skip if a majority element is confirmed to // be present in an array just return candidate // in that case } // Driver code public static void main(String[] args) { int arr[] = { 1, 1, 1, 1, 2, 3, 4 }; int majority = findMajority(arr); System.out.println(\" The majority element is : \" + majority); }} // This code is contribute by Arnav Sharma",
"e": 29997,
"s": 28852,
"text": null
},
{
"code": "# Python implementation for the above approach # Function to find majority elementdef findMajority(arr, n): candidate = -1 votes = 0 # Finding majority candidate for i in range (n): if (votes == 0): candidate = arr[i] votes = 1 else: if (arr[i] == candidate): votes += 1 else: votes -= 1 count = 0 # Checking if majority candidate occurs more than n/2 # times for i in range (n): if (arr[i] == candidate): count += 1 if (count > n // 2): return candidate else: return -1 # Driver Code arr = [ 1, 1, 1, 1, 2, 3, 4 ]n = len(arr)majority = findMajority(arr, n)print(\" The majority element is :\" ,majority) # This code is contributed by shivanisinghss2110 ",
"e": 30827,
"s": 29997,
"text": null
},
{
"code": "using System; class GFG{ // Function to find majority element public static int findMajority(int[] nums) { int count = 0, candidate = -1; // Finding majority candidate for (int index = 0; index < nums.Length; index++) { if (count == 0) { candidate = nums[index]; count = 1; } else { if (nums[index] == candidate) count++; else count--; } } // Checking if majority candidate occurs more than // n/2 times count = 0; for (int index = 0; index < nums.Length; index++) { if (nums[index] == candidate) count++; } if (count > (nums.Length / 2)) return candidate; return -1; // The last for loop and the if statement step can // be skip if a majority element is confirmed to // be present in an array just return candidate // in that case } // Driver code public static void Main(String[] args) { int []arr = { 1, 1, 1, 1, 2, 3, 4}; int majority = findMajority(arr); Console.Write(\" The majority element is : \" + majority); }} // This code is contributed by shivanisinghss2110",
"e": 31969,
"s": 30827,
"text": null
},
{
"code": "<script>// Function to find majority elementfunction findMajority(nums) { var count = 0, candidate = -1; // Finding majority candidate for (var index = 0; index < nums.length; index++) { if (count == 0) { candidate = nums[index]; count = 1; } else { if (nums[index] == candidate) count++; else count--; } } // Checking if majority candidate occurs more than // n/2 times count = 0; for (var index = 0; index < nums.length; index++) { if (nums[index] == candidate) count++; } if (count > (nums.length / 2)) return candidate; return -1; // The last for loop and the if statement step can // be skip if a majority element is confirmed to // be present in an array just return candidate // in that case } // Driver code var arr = [ 1, 1, 1, 1, 2, 3, 4 ]; var majority = findMajority(arr); document.write(\" The majority element is : \" + majority); // This code is contributed by shivanisinghss2110. </script>",
"e": 33040,
"s": 31969,
"text": null
},
{
"code": null,
"e": 33069,
"s": 33040,
"text": " The majority element is : 1"
},
{
"code": null,
"e": 33147,
"s": 33069,
"text": "Time Complexity: O(n) ( For two passes over the array )Space Complexity: O(1)"
},
{
"code": null,
"e": 33163,
"s": 33147,
"text": "arnavsharma2711"
},
{
"code": null,
"e": 33182,
"s": 33163,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33195,
"s": 33182,
"text": "murugank0204"
},
{
"code": null,
"e": 33209,
"s": 33195,
"text": "tanveerbaba30"
},
{
"code": null,
"e": 33234,
"s": 33209,
"text": "Moore's Voting Algorithm"
},
{
"code": null,
"e": 33241,
"s": 33234,
"text": "Picked"
},
{
"code": null,
"e": 33274,
"s": 33241,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 33372,
"s": 33274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33426,
"s": 33372,
"text": "Construct Pushdown Automata for all length palindrome"
},
{
"code": null,
"e": 33481,
"s": 33426,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 33542,
"s": 33481,
"text": "Construct a Turing Machine for language L = {ww | w ∈ {0,1}}"
},
{
"code": null,
"e": 33593,
"s": 33542,
"text": "NPDA for accepting the language L = {an bn | n>=1}"
},
{
"code": null,
"e": 33632,
"s": 33593,
"text": "Decidability and Undecidability in TOC"
},
{
"code": null,
"e": 33692,
"s": 33632,
"text": "Decidable and Undecidable problems in Theory of Computation"
},
{
"code": null,
"e": 33733,
"s": 33692,
"text": "Halting Problem in Theory of Computation"
},
{
"code": null,
"e": 33777,
"s": 33733,
"text": "Pushdown Automata Acceptance by Final State"
},
{
"code": null,
"e": 33828,
"s": 33777,
"text": "Context-sensitive Grammar (CSG) and Language (CSL)"
}
] |
Product of all Subarrays of an Array - GeeksforGeeks | 24 Nov, 2021
Given an array of integers arr of size N, the task is to print products of all subarrays of the array.
Examples:
Input: arr[] = {2, 4} Output: 64 Here, subarrays are [2], [2, 4], [4] Products are 2, 8, 4 Product of all Subarrays = 64
Input : arr[] = {10, 3, 7} Output : 27783000 Here, subarrays are [10], [10, 3], [10, 3, 7], [3], [3, 7], [7] Products are 10, 30, 210, 3, 21, 7 Product of all Subarrays = 27783000
Naive Approach: A simple solution is to generate all sub-array and compute their product.
C++
Java
Python3
C#
Javascript
// C++ program to find product// of all subarray of an array #include <bits/stdc++.h>using namespace std; // Function to find product of all subarraysvoid product_subarrays(int arr[], int n){ // Variable to store the product int product = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { for (int k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray cout << product << "\n";} // Driver codeint main(){ int arr[] = { 10, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call product_subarrays(arr, n); return 0;}
// Java program to find product// of all subarray of an arrayimport java.util.*; class GFG { // Function to find product of all subarrays static void product_subarrays(int arr[], int n) { // Variable to store the product int product = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { for (int k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray System.out.print(product + "\n"); } // Driver code public static void main(String args[]) { int arr[] = { 10, 3, 7 }; int n = arr.length; // Function call product_subarrays(arr, n); }} // This code is contributed by shivanisinghss2110
# Python3 program to find product# of all subarray of an array # Function to find product of all subarraysdef product_subarrays(arr, n): # Variable to store the product product = 1; # Compute the product while # traversing for subarrays for i in range(0, n): for j in range(i, n): for k in range(i, j + 1): product *= arr[k]; # Printing product of all subarray print(product, "\n"); # Driver codearr = [ 10, 3, 7 ]; n = len(arr); # Function callproduct_subarrays(arr, n); # This code is contributed by Code_Mech
// C# program to find product// of all subarray of an arrayusing System; class GFG { // Function to find product of all subarrays static void product_subarrays(int[] arr, int n) { // Variable to store the product int product = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { for (int k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray Console.Write(product + "\n"); } // Driver code public static void Main(String[] args) { int[] arr = { 10, 3, 7 }; int n = arr.Length; // Function call product_subarrays(arr, n); }} // This code is contributed by shivanisinghss2110
<script> // Javascript program to find product // of all subarray of an array // Function to find product of all subarrays function product_subarrays(arr, n) { // Variable to store the product let product = 1; // Compute the product while // traversing for subarrays for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { for (let k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray document.write(product + "</br>"); } let arr = [ 10, 3, 7 ]; let n = arr.length; // Function call product_subarrays(arr, n); // This code is contributed by divyeshrabadiya07.</script>
27783000
Time Complexity: O(n3)
Auxiliary Space: O(1)
Efficient Approach: An efficient approach is to use two loops and calculate the products while traversing the subarrays.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find product// of all subarray of an array #include <bits/stdc++.h>using namespace std; // Function to find product of all subarraysvoid product_subarrays(long long int arr[], int n){ // Variable to store the product long long int res = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { long long int product = 1; for (int j = i; j < n; j++) { product = product * arr[j]; res *= product; } } // Printing product of all subarray cout << res << "\n";} // Driver codeint main(){ long long int arr[] = { 10, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call product_subarrays(arr, n); return 0;}
// Java program to find product// of all subarray of an arrayimport java.util.*; class GFG { // Function to find product of all subarrays static void product_subarrays(int arr[], int n) { // Variable to store the product int res = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { int product = 1; for (int j = i; j < n; j++) { product = product * arr[j]; res *= product; } } // Printing product of all subarray System.out.println(res + "\n"); } // Driver code public static void main(String args[]) { int arr[] = { 10, 3, 7 }; int n = arr.length; // Function call product_subarrays(arr, n); }} // This code is contributed by AbhiThakur
# Python3 program to find product# of all subarray of an array # Function to find product of all subarraysdef product_subarrays(arr, n): # Variable to store the product res = 1; # Compute the product while # traversing for subarrays for i in range(n): product = 1 for j in range(i, n): product *= arr[j]; res = res * product # Printing product of all subarray print(res); # Driver codeif __name__ == '__main__': arr = [ 10, 3, 7 ]; n = len(arr); # Function call product_subarrays(arr, n); # This code is contributed by Princi Singh
// C# program to find product// of all subarray of an arrayusing System; class GFG { // Function to find product of all subarrays static void product_subarrays(int[] arr, int n) { // Variable to store the product int res = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { int product = 1; for (int j = i; j < n; j++) { product *= arr[j]; res = res * product; } } // Printing product of all subarray Console.WriteLine(res + "\n"); } // Driver code public static void Main(String[] args) { int[] arr = { 10, 3, 7 }; int n = arr.Length; // Function call product_subarrays(arr, n); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to find product// of all subarray of an array // Function to find product of all subarraysfunction product_subarrays(arr, n){ // Variable to store the product var res = 1; // Compute the product while // traversing for subarrays for (var i = 0; i < n; i++) { var product = 1; for (var j = i; j < n; j++) { product = product * arr[j]; res *= product; } } // Printing product of all subarray document.write( res );} // Driver codevar arr = [10, 3, 7];var n = arr.length;// Function callproduct_subarrays(arr, n); </script>
27783000
Time Complexity: O(n2)
Auxiliary Space: O(1)
abhaysingh290895
29AjayKumar
princi singh
pavan16081997
shivanisinghss2110
Code_Mech
architawasthi
divyeshrabadiya07
noob2000
varshagumber28
subham348
subarray
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26531,
"s": 26503,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26634,
"s": 26531,
"text": "Given an array of integers arr of size N, the task is to print products of all subarrays of the array."
},
{
"code": null,
"e": 26644,
"s": 26634,
"text": "Examples:"
},
{
"code": null,
"e": 26765,
"s": 26644,
"text": "Input: arr[] = {2, 4} Output: 64 Here, subarrays are [2], [2, 4], [4] Products are 2, 8, 4 Product of all Subarrays = 64"
},
{
"code": null,
"e": 26947,
"s": 26765,
"text": "Input : arr[] = {10, 3, 7} Output : 27783000 Here, subarrays are [10], [10, 3], [10, 3, 7], [3], [3, 7], [7] Products are 10, 30, 210, 3, 21, 7 Product of all Subarrays = 27783000 "
},
{
"code": null,
"e": 27038,
"s": 26947,
"text": "Naive Approach: A simple solution is to generate all sub-array and compute their product. "
},
{
"code": null,
"e": 27042,
"s": 27038,
"text": "C++"
},
{
"code": null,
"e": 27047,
"s": 27042,
"text": "Java"
},
{
"code": null,
"e": 27055,
"s": 27047,
"text": "Python3"
},
{
"code": null,
"e": 27058,
"s": 27055,
"text": "C#"
},
{
"code": null,
"e": 27069,
"s": 27058,
"text": "Javascript"
},
{
"code": "// C++ program to find product// of all subarray of an array #include <bits/stdc++.h>using namespace std; // Function to find product of all subarraysvoid product_subarrays(int arr[], int n){ // Variable to store the product int product = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { for (int k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray cout << product << \"\\n\";} // Driver codeint main(){ int arr[] = { 10, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call product_subarrays(arr, n); return 0;}",
"e": 27771,
"s": 27069,
"text": null
},
{
"code": "// Java program to find product// of all subarray of an arrayimport java.util.*; class GFG { // Function to find product of all subarrays static void product_subarrays(int arr[], int n) { // Variable to store the product int product = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { for (int k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray System.out.print(product + \"\\n\"); } // Driver code public static void main(String args[]) { int arr[] = { 10, 3, 7 }; int n = arr.length; // Function call product_subarrays(arr, n); }} // This code is contributed by shivanisinghss2110",
"e": 28619,
"s": 27771,
"text": null
},
{
"code": "# Python3 program to find product# of all subarray of an array # Function to find product of all subarraysdef product_subarrays(arr, n): # Variable to store the product product = 1; # Compute the product while # traversing for subarrays for i in range(0, n): for j in range(i, n): for k in range(i, j + 1): product *= arr[k]; # Printing product of all subarray print(product, \"\\n\"); # Driver codearr = [ 10, 3, 7 ]; n = len(arr); # Function callproduct_subarrays(arr, n); # This code is contributed by Code_Mech",
"e": 29196,
"s": 28619,
"text": null
},
{
"code": "// C# program to find product// of all subarray of an arrayusing System; class GFG { // Function to find product of all subarrays static void product_subarrays(int[] arr, int n) { // Variable to store the product int product = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { for (int k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray Console.Write(product + \"\\n\"); } // Driver code public static void Main(String[] args) { int[] arr = { 10, 3, 7 }; int n = arr.Length; // Function call product_subarrays(arr, n); }} // This code is contributed by shivanisinghss2110",
"e": 30033,
"s": 29196,
"text": null
},
{
"code": "<script> // Javascript program to find product // of all subarray of an array // Function to find product of all subarrays function product_subarrays(arr, n) { // Variable to store the product let product = 1; // Compute the product while // traversing for subarrays for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { for (let k = i; k <= j; k++) product *= arr[k]; } } // Printing product of all subarray document.write(product + \"</br>\"); } let arr = [ 10, 3, 7 ]; let n = arr.length; // Function call product_subarrays(arr, n); // This code is contributed by divyeshrabadiya07.</script>",
"e": 30742,
"s": 30033,
"text": null
},
{
"code": null,
"e": 30751,
"s": 30742,
"text": "27783000"
},
{
"code": null,
"e": 30776,
"s": 30753,
"text": "Time Complexity: O(n3)"
},
{
"code": null,
"e": 30798,
"s": 30776,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30971,
"s": 30798,
"text": "Efficient Approach: An efficient approach is to use two loops and calculate the products while traversing the subarrays.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 30975,
"s": 30971,
"text": "C++"
},
{
"code": null,
"e": 30980,
"s": 30975,
"text": "Java"
},
{
"code": null,
"e": 30988,
"s": 30980,
"text": "Python3"
},
{
"code": null,
"e": 30991,
"s": 30988,
"text": "C#"
},
{
"code": null,
"e": 31002,
"s": 30991,
"text": "Javascript"
},
{
"code": "// C++ program to find product// of all subarray of an array #include <bits/stdc++.h>using namespace std; // Function to find product of all subarraysvoid product_subarrays(long long int arr[], int n){ // Variable to store the product long long int res = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { long long int product = 1; for (int j = i; j < n; j++) { product = product * arr[j]; res *= product; } } // Printing product of all subarray cout << res << \"\\n\";} // Driver codeint main(){ long long int arr[] = { 10, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call product_subarrays(arr, n); return 0;}",
"e": 31751,
"s": 31002,
"text": null
},
{
"code": "// Java program to find product// of all subarray of an arrayimport java.util.*; class GFG { // Function to find product of all subarrays static void product_subarrays(int arr[], int n) { // Variable to store the product int res = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { int product = 1; for (int j = i; j < n; j++) { product = product * arr[j]; res *= product; } } // Printing product of all subarray System.out.println(res + \"\\n\"); } // Driver code public static void main(String args[]) { int arr[] = { 10, 3, 7 }; int n = arr.length; // Function call product_subarrays(arr, n); }} // This code is contributed by AbhiThakur",
"e": 32605,
"s": 31751,
"text": null
},
{
"code": "# Python3 program to find product# of all subarray of an array # Function to find product of all subarraysdef product_subarrays(arr, n): # Variable to store the product res = 1; # Compute the product while # traversing for subarrays for i in range(n): product = 1 for j in range(i, n): product *= arr[j]; res = res * product # Printing product of all subarray print(res); # Driver codeif __name__ == '__main__': arr = [ 10, 3, 7 ]; n = len(arr); # Function call product_subarrays(arr, n); # This code is contributed by Princi Singh",
"e": 33211,
"s": 32605,
"text": null
},
{
"code": "// C# program to find product// of all subarray of an arrayusing System; class GFG { // Function to find product of all subarrays static void product_subarrays(int[] arr, int n) { // Variable to store the product int res = 1; // Compute the product while // traversing for subarrays for (int i = 0; i < n; i++) { int product = 1; for (int j = i; j < n; j++) { product *= arr[j]; res = res * product; } } // Printing product of all subarray Console.WriteLine(res + \"\\n\"); } // Driver code public static void Main(String[] args) { int[] arr = { 10, 3, 7 }; int n = arr.Length; // Function call product_subarrays(arr, n); }} // This code is contributed by 29AjayKumar",
"e": 34053,
"s": 33211,
"text": null
},
{
"code": "<script> // Javascript program to find product// of all subarray of an array // Function to find product of all subarraysfunction product_subarrays(arr, n){ // Variable to store the product var res = 1; // Compute the product while // traversing for subarrays for (var i = 0; i < n; i++) { var product = 1; for (var j = i; j < n; j++) { product = product * arr[j]; res *= product; } } // Printing product of all subarray document.write( res );} // Driver codevar arr = [10, 3, 7];var n = arr.length;// Function callproduct_subarrays(arr, n); </script>",
"e": 34674,
"s": 34053,
"text": null
},
{
"code": null,
"e": 34683,
"s": 34674,
"text": "27783000"
},
{
"code": null,
"e": 34708,
"s": 34685,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 34730,
"s": 34708,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34747,
"s": 34730,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 34759,
"s": 34747,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34772,
"s": 34759,
"text": "princi singh"
},
{
"code": null,
"e": 34786,
"s": 34772,
"text": "pavan16081997"
},
{
"code": null,
"e": 34805,
"s": 34786,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 34815,
"s": 34805,
"text": "Code_Mech"
},
{
"code": null,
"e": 34829,
"s": 34815,
"text": "architawasthi"
},
{
"code": null,
"e": 34847,
"s": 34829,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 34856,
"s": 34847,
"text": "noob2000"
},
{
"code": null,
"e": 34871,
"s": 34856,
"text": "varshagumber28"
},
{
"code": null,
"e": 34881,
"s": 34871,
"text": "subham348"
},
{
"code": null,
"e": 34890,
"s": 34881,
"text": "subarray"
},
{
"code": null,
"e": 34897,
"s": 34890,
"text": "Arrays"
},
{
"code": null,
"e": 34910,
"s": 34897,
"text": "Mathematical"
},
{
"code": null,
"e": 34917,
"s": 34910,
"text": "Arrays"
},
{
"code": null,
"e": 34930,
"s": 34917,
"text": "Mathematical"
},
{
"code": null,
"e": 35028,
"s": 34930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35096,
"s": 35028,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35140,
"s": 35096,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 35188,
"s": 35140,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 35211,
"s": 35188,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35243,
"s": 35211,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35273,
"s": 35243,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35333,
"s": 35273,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35348,
"s": 35333,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35391,
"s": 35348,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
C++ Program to Find Transpose of a Matrix | A matrix is a rectangular array of numbers that is arranged in the form of rows and columns. A transpose of a matrix is a new matrix in which the rows of the original are the columns now and vice versa. For example.
A matrix is given below −
1 2 3
4 5 6
7 8 9
The transpose of the above matrix is as follows.
1 4 7
2 5 8
3 6 9
A program to find the transpose of a matrix is as follows −
Live Demo
#include<iostream<
using namespace std;
int main() {
int transpose[10][10], r=3, c=2, i, j;
int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
transpose[j][i] = a[i][j];
}
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
for(j=0; j<r; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
}
return 0;
}
The matrix is:
1 2
3 4
5 6
The transpose of the matrix is:
1 3 5
2 4 6
In the above program, the matrix is initialized. Then its values are displayed. This is shown in the following code snippet.
int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
The transpose of the matrix is calculated using a nested for loop. This is given as follows.
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) {
transpose[j][i] = a[i][j];
}
Finally, the transpose is obtained and it is printed on the screen. This is done with the following code snippet.
cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
for(j=0; j<r; ++j)
cout<<transpose[i][j]<<" ";
cout<<endl;
} | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "A matrix is a rectangular array of numbers that is arranged in the form of rows and columns. A transpose of a matrix is a new matrix in which the rows of the original are the columns now and vice versa. For example."
},
{
"code": null,
"e": 1304,
"s": 1278,
"text": "A matrix is given below −"
},
{
"code": null,
"e": 1322,
"s": 1304,
"text": "1 2 3\n4 5 6\n7 8 9"
},
{
"code": null,
"e": 1371,
"s": 1322,
"text": "The transpose of the above matrix is as follows."
},
{
"code": null,
"e": 1389,
"s": 1371,
"text": "1 4 7\n2 5 8\n3 6 9"
},
{
"code": null,
"e": 1449,
"s": 1389,
"text": "A program to find the transpose of a matrix is as follows −"
},
{
"code": null,
"e": 1460,
"s": 1449,
"text": " Live Demo"
},
{
"code": null,
"e": 2003,
"s": 1460,
"text": "#include<iostream<\nusing namespace std;\nint main() {\n int transpose[10][10], r=3, c=2, i, j;\n int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };\n cout<<\"The matrix is:\"<<endl;\n for(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n for(i=0; i<r; ++i)\n for(j=0; j<c; ++j) {\n transpose[j][i] = a[i][j];\n }\n cout<<\"The transpose of the matrix is:\"<<endl;\n for(i=0; i<c; ++i) {\n for(j=0; j<r; ++j)\n cout<<transpose[i][j]<<\" \";\n cout<<endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2075,
"s": 2003,
"text": "The matrix is:\n1 2\n3 4\n5 6\n\nThe transpose of the matrix is:\n1 3 5\n2 4 6"
},
{
"code": null,
"e": 2200,
"s": 2075,
"text": "In the above program, the matrix is initialized. Then its values are displayed. This is shown in the following code snippet."
},
{
"code": null,
"e": 2357,
"s": 2200,
"text": "int a[3][3] = { {1, 2} , {3, 4} , {5, 6} };\ncout<<\"The matrix is:\"<<endl;\nfor(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n}"
},
{
"code": null,
"e": 2450,
"s": 2357,
"text": "The transpose of the matrix is calculated using a nested for loop. This is given as follows."
},
{
"code": null,
"e": 2522,
"s": 2450,
"text": "for(i=0; i<r; ++i)\nfor(j=0; j<c; ++j) {\n transpose[j][i] = a[i][j];\n}"
},
{
"code": null,
"e": 2636,
"s": 2522,
"text": "Finally, the transpose is obtained and it is printed on the screen. This is done with the following code snippet."
},
{
"code": null,
"e": 2774,
"s": 2636,
"text": "cout<<\"The transpose of the matrix is:\"<<endl;\nfor(i=0; i<c; ++i) {\n for(j=0; j<r; ++j)\n cout<<transpose[i][j]<<\" \";\n cout<<endl;\n}"
}
] |
fread() function in C++ - GeeksforGeeks | 16 Feb, 2021
The fread() function in C++ reads the block of data from the stream. This function first, reads the count number of objects, each one with a size of size bytes from the given input stream. The total amount of bytes reads if successful is (size*count). According to the no. of characters read, the indicator file position is incremented. If the objects read are not trivially copy-able, then the behavior is undefined and if the value of size or count is equal to zero, then this program will simply return 0.Syntax :
size_t fread(void * buffer, size_t size, size_t count, FILE * stream)
Parameter : The function accepts four mandatory parameters which are described as below:
buffer: it specifies the pointer to the block of memory with a size of at least (size*count) bytes to store the objects.
size: it specifies the size of each object in bytes. size_t is an unsigned integral type.
count: it specifies the number of elements, each one with a size of size bytes.
stream: it specifies the file stream to read the data from.
Return Value: The function returns the number of objects read successfully. If an error occurs, the return value can be less than the count.Below programs illustrate the above function: Program 1:
CPP
// C++ program to illustrate fread() function#include <bits/stdc++.h>#include <cstdio>using namespace std; int main(){ FILE* file_; char buffer[100]; file_ = fopen("g4g.txt", "aman"); while (!feof(file_)) // to read file { // function used to read the contents of file fread(buffer, sizeof(buffer), 1, file_); cout << buffer; } return 0;}
Suppose the file g4g.txt contains following data:
Geeks : DS-ALgo
Gfg : DP
Contribute : writearticle
Then, when you will run the program, the output will be
Harry Potter : Specs
Hermione : Smart
Weasley : FlyingCar
Dumbledore : Wand
Program 2 :
CPP
// C++ program to illustrate fread() function// when file's size or count is equal to 0#include <bits/stdc++.h>#include <cstdio>using namespace std; int main(){ FILE* file_; char buffer[100]; file_ = fopen("g4g.txt", "aman"); cout << "count = 0, return value = " << fread(buffer, sizeof(buffer), 0, file_); cout << "\nsize = 0, return value = " << fread(buffer, 0, 1, file_) << endl; return 0;}
count = 0, return value = 0
size = 0, return value = 0
arorakashish0911
C-File Handling
cpp-file-handling
CPP-Functions
File Handling
C++
File Handling
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
vector erase() and clear() in C++ | [
{
"code": null,
"e": 23975,
"s": 23947,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 24494,
"s": 23975,
"text": "The fread() function in C++ reads the block of data from the stream. This function first, reads the count number of objects, each one with a size of size bytes from the given input stream. The total amount of bytes reads if successful is (size*count). According to the no. of characters read, the indicator file position is incremented. If the objects read are not trivially copy-able, then the behavior is undefined and if the value of size or count is equal to zero, then this program will simply return 0.Syntax : "
},
{
"code": null,
"e": 24564,
"s": 24494,
"text": "size_t fread(void * buffer, size_t size, size_t count, FILE * stream)"
},
{
"code": null,
"e": 24655,
"s": 24564,
"text": "Parameter : The function accepts four mandatory parameters which are described as below: "
},
{
"code": null,
"e": 24776,
"s": 24655,
"text": "buffer: it specifies the pointer to the block of memory with a size of at least (size*count) bytes to store the objects."
},
{
"code": null,
"e": 24866,
"s": 24776,
"text": "size: it specifies the size of each object in bytes. size_t is an unsigned integral type."
},
{
"code": null,
"e": 24946,
"s": 24866,
"text": "count: it specifies the number of elements, each one with a size of size bytes."
},
{
"code": null,
"e": 25006,
"s": 24946,
"text": "stream: it specifies the file stream to read the data from."
},
{
"code": null,
"e": 25205,
"s": 25006,
"text": "Return Value: The function returns the number of objects read successfully. If an error occurs, the return value can be less than the count.Below programs illustrate the above function: Program 1: "
},
{
"code": null,
"e": 25209,
"s": 25205,
"text": "CPP"
},
{
"code": "// C++ program to illustrate fread() function#include <bits/stdc++.h>#include <cstdio>using namespace std; int main(){ FILE* file_; char buffer[100]; file_ = fopen(\"g4g.txt\", \"aman\"); while (!feof(file_)) // to read file { // function used to read the contents of file fread(buffer, sizeof(buffer), 1, file_); cout << buffer; } return 0;}",
"e": 25590,
"s": 25209,
"text": null
},
{
"code": null,
"e": 25642,
"s": 25590,
"text": "Suppose the file g4g.txt contains following data: "
},
{
"code": null,
"e": 25696,
"s": 25642,
"text": "Geeks : DS-ALgo \nGfg : DP \nContribute : writearticle "
},
{
"code": null,
"e": 25754,
"s": 25696,
"text": "Then, when you will run the program, the output will be "
},
{
"code": null,
"e": 25830,
"s": 25754,
"text": "Harry Potter : Specs\nHermione : Smart\nWeasley : FlyingCar\nDumbledore : Wand"
},
{
"code": null,
"e": 25844,
"s": 25830,
"text": "Program 2 : "
},
{
"code": null,
"e": 25848,
"s": 25844,
"text": "CPP"
},
{
"code": "// C++ program to illustrate fread() function// when file's size or count is equal to 0#include <bits/stdc++.h>#include <cstdio>using namespace std; int main(){ FILE* file_; char buffer[100]; file_ = fopen(\"g4g.txt\", \"aman\"); cout << \"count = 0, return value = \" << fread(buffer, sizeof(buffer), 0, file_); cout << \"\\nsize = 0, return value = \" << fread(buffer, 0, 1, file_) << endl; return 0;}",
"e": 26268,
"s": 25848,
"text": null
},
{
"code": null,
"e": 26323,
"s": 26268,
"text": "count = 0, return value = 0\nsize = 0, return value = 0"
},
{
"code": null,
"e": 26342,
"s": 26325,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26358,
"s": 26342,
"text": "C-File Handling"
},
{
"code": null,
"e": 26376,
"s": 26358,
"text": "cpp-file-handling"
},
{
"code": null,
"e": 26390,
"s": 26376,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26404,
"s": 26390,
"text": "File Handling"
},
{
"code": null,
"e": 26408,
"s": 26404,
"text": "C++"
},
{
"code": null,
"e": 26422,
"s": 26408,
"text": "File Handling"
},
{
"code": null,
"e": 26426,
"s": 26422,
"text": "CPP"
},
{
"code": null,
"e": 26524,
"s": 26426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26533,
"s": 26524,
"text": "Comments"
},
{
"code": null,
"e": 26546,
"s": 26533,
"text": "Old Comments"
},
{
"code": null,
"e": 26565,
"s": 26546,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26589,
"s": 26565,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26609,
"s": 26589,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26636,
"s": 26609,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26664,
"s": 26636,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26692,
"s": 26664,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26727,
"s": 26692,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26751,
"s": 26727,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 26775,
"s": 26751,
"text": "Virtual Function in C++"
}
] |
Learn how to master groupby function in Python now | by WY Fok | Towards Data Science | One popular feature in the Pandas package is groupby function. I believe that almost everyone using Pandas before must use groupby function also. It is so popular because it provides summarized but detailed results efficiently. As described by the doc of Pandas package,
By “group by” we are referring to a process involving one or more of the following steps:
Splitting the data into groups based on some criteria.
Applying a function to each group independently.
Combining the results into a data structure. [1]
There is also a groupby function in SQL. Therefore for someone experienced in SQL, learning groupby function in Python is not a difficult thing. But the thing is groupby in Pandas can perform way more analysis than in SQL and this makes groupby in Pandas a common but essential function.
The reason that groupby in Pandas is more powerful is because of the second step “Applying”. In SQL, most actions in “Applying” steps are statistically related, like min, max, count, etc. However, in Pandas, “Applying” can perform much more.
From the doc of Pandas,
In the apply step, we might wish to one of the following:
Aggregation: compute a summary statistic (or statistics) for each group.
Transformation: perform some group-specific computations and return a like-indexed object.
Filtration: discard some groups, according to a group-wise computation that evaluates True or False. [1]
In this article, I will cover some groupby applications. These applications do not only show me the insights from the data but also help me identify my next move on analyzing the data.
Let’s begin.
The data used in this article is “student-por.csv” in “Student Alcohol Consumption” from Kaggle. You can download the data from this link.
# Inputimport pandas as pd data = pd.read_csv('student-por.csv')data.info()# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 649 entries, 0 to 648Data columns (total 33 columns):school 649 non-null objectsex 649 non-null objectage 649 non-null int64address 649 non-null objectfamsize 649 non-null objectPstatus 649 non-null objectMedu 649 non-null int64Fedu 649 non-null int64Mjob 649 non-null objectFjob 649 non-null objectreason 649 non-null objectguardian 649 non-null objecttraveltime 649 non-null int64studytime 649 non-null int64failures 649 non-null int64schoolsup 649 non-null objectfamsup 649 non-null objectpaid 649 non-null objectactivities 649 non-null objectnursery 649 non-null objecthigher 649 non-null objectinternet 649 non-null objectromantic 649 non-null objectfamrel 649 non-null int64freetime 649 non-null int64goout 649 non-null int64Dalc 649 non-null int64Walc 649 non-null int64health 649 non-null int64absences 649 non-null int64G1 649 non-null int64G2 649 non-null int64G3 649 non-null int64dtypes: int64(16), object(17)memory usage: 167.4+ KB
The first step is rather simple, grouping data based on the value in one or more columns. You only need to specify how to perform the grouping. Most people already know that a column name or a list of column names can be used for grouping. However, you can also pass a function for the grouping. The function will use the index value as the parameter and perform the grouping. For further info, [2]
The object returned from the groupby function is “DataFrameGroupBy object”. After the grouping, you can use groupto see the groupings.
#Groupby one column# Inputdata.groupby('school')# Output<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000024D28C9DF98># Inputdata.groupby('school').groups# Output{'GP': Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,...413, 414, 415, 416, 417, 418, 419, 420, 421, 422],dtype='int64', length=423), 'MS': Int64Index([423, 424, 425, 426, 427, 428, 429, 430, 431, 432,...639, 640, 641, 642, 643, 644, 645, 646, 647, 648],dtype='int64', length=226)}# Groupby a function # Inputdef grouping(int): if int%10==0: return 'Group1' if int%5==0: return 'Group2' return 'Group3'data.groupby(grouping).groups# Output{'Group1': Int64Index([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640], dtype='int64'), 'Group2': Int64Index([ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 105, 115, 125,135, 145, 155, 165, 175, 185, 195, 205, 215, 225, 235, 245, 255, 265, 275, 285, 295, 305, 315, 325, 335, 345, 355, 365, 375, 385, 395, 405, 415, 425, 435, 445, 455, 465, 475, 485, 495, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 605, 615, 625, 635, 645], dtype='int64'), 'Group3': Int64Index([ 1, 2, 3, 4, 6, 7, 8, 9, 11, 12,... 637, 638, 639, 641, 642, 643, 644, 646, 647, 648],dtype='int64', length=519)}
In the above example using a function for grouping, the index in the dataframe is the row number. Therefore, a row is assigned to one of three groups based on the row number. And then groupby function groups these three groups.
To get the data for each group, you can then use the get_group()function and input the group name.
#Inputdata.groupby(grouping).get_group('Group1')
Furthermore, if you want to groupby the data by a non-index column, you can use apply and lambda functions together for the grouping.
# Inputdata.groupby(data['famsize'].apply(lambda x: x.startswith('GT'))).get_group(False)
After grouping, you can already apply a number of computation or statistics functions. For example, size()can give you the numbers of rows for each group; sum()returns the sum for all numeric columns for each group. To know more applicable functions, [3]
#Inputdata.groupby(data['famsize'].apply(lambda x: x.startswith('GT'))).size()#OutputfamsizeFalse 192True 457dtype: int64
It is time to cover the important part of groupby. Groupby function in Pandas is way more powerful than in SQL because you can not only use common statistics functions like min(), max(), mean(),... but also lots of more complex functions. You can also apply your defined functions. In the below section, I will explain the three actions separately.
An easy explanation about aggregation is to perform a computation based on previously grouped data. The aggregation is applied to each group and return its respective result.
Some common computations are like sum, min, max, ... You can perform the computation to all numeric columns, or you can also specify a column to perform the computation.
#Input mjob_gp = data.groupby('Mjob')mjob_gp.agg('mean')
#Inputmjob_gp['age'].agg('mean')#OutputMjobat_home 16.955556health 16.312500other 16.802326services 16.661765teacher 16.583333Name: age, dtype: float64
One less commonly known about aggregation is that you can perform multiple computations on one or more columns together. This one is useful if you want to investigate the statistics of a column.
#Input mjob_gp.agg({'age':['mean','max']})
However, one problem is that the columns are in multi-index which is not so good for further processing(and I don't like multi-index personally). Therefore, we can take one step further and include pd.NamedAgg (New from 0.25.0 version of Pandas) to aggfunction. For further information about pd.NamedAgg, [4]
#Inputmjob_gp.agg(avg_age=pd.NamedAgg(column='age', aggfunc='mean'), min_age=pd.NamedAgg(column='age', aggfunc='min'), max_age=pd.NamedAgg(column='age', aggfunc='max'))
There are two advantages using pd.NamedAgg. The first advantage is, of course, no multi-index on the columns. And the second advantage is that you can custom define the column names.
Not surprisingly, you can also use custom-defined functions in the aggregation.
#Input def range_function(x): return max(x) - min(x)mjob_gp.agg(max_age = pd.NamedAgg(column='age',aggfunc='max'), min_age = pd.NamedAgg(column='age',aggfunc='min'), range_age = pd.NamedAgg(column='age',aggfunc=range_function),)
Back to the description of transformation,
Transformation: perform some group-specific computations and return a like-indexed object.
The key part is “group-specific computations”. The computations are different across different groups. For example, maxwill give you the maximum of a column for each group, but not across the whole dataset.
Another characteristic of transformation is that the computation applies to each row and returns back the results with the same length of each group, not like aggregation with reduced lengths. If you are familiar with window function in SQL, transformation in Pandas is similar to that. (PS: You still don't know window function in SQL?!?! Check my previous article that helps you understand why window function in SQL is so important)
towardsdatascience.com
#Input mjob_gp['G1','G2','G3'].transform(lambda x: (x-x.mean())/x.std())
In the above example, for each group, the values of G1 to G3 are normalized based on the mean and standard deviation for the respective group.
From the description in Pandas,
Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func. [5]
You can use filterfunction to filter out any groups that do not satisfy the criteria.
#Input mjob_gp.filter(lambda x: x['G1'].mean() > 12)
In the above example, only Mjob under “health” and “teacher” are returned because their means of “G1” are larger than 12.
#Input mjob_gp['G1'].mean()#OutputMjobat_home 10.451852health 12.395833other 11.275194services 11.610294teacher 12.555556Name: G1, dtype: float64
Groupby function in Pandas is a handy tool to perform lots of analyses and data transformations. I hope this article helps you understand the power and usefulness of groupby in Pandas. I am sure you now know more about how to use groupby in your usual data analysis. Have fun with Pandas and see you next time.
Bookmark this if you are new to Python (especially if you self-learn Python)
(Part 2) Bookmark this if you are new to Python (especially if you self-learn Python)
How to use Pandas to analyze numeric data?
Web Scrape Twitter by Python Selenium (Part 1)
Web Scrape Twitter by Python Selenium (Part 2)
[1]: Group By: split-apply-combine
[2]: pandas.DataFrame.groupby
[3]: Computations / descriptive stats
[4]: Named aggregation | [
{
"code": null,
"e": 442,
"s": 171,
"text": "One popular feature in the Pandas package is groupby function. I believe that almost everyone using Pandas before must use groupby function also. It is so popular because it provides summarized but detailed results efficiently. As described by the doc of Pandas package,"
},
{
"code": null,
"e": 532,
"s": 442,
"text": "By “group by” we are referring to a process involving one or more of the following steps:"
},
{
"code": null,
"e": 587,
"s": 532,
"text": "Splitting the data into groups based on some criteria."
},
{
"code": null,
"e": 636,
"s": 587,
"text": "Applying a function to each group independently."
},
{
"code": null,
"e": 685,
"s": 636,
"text": "Combining the results into a data structure. [1]"
},
{
"code": null,
"e": 973,
"s": 685,
"text": "There is also a groupby function in SQL. Therefore for someone experienced in SQL, learning groupby function in Python is not a difficult thing. But the thing is groupby in Pandas can perform way more analysis than in SQL and this makes groupby in Pandas a common but essential function."
},
{
"code": null,
"e": 1215,
"s": 973,
"text": "The reason that groupby in Pandas is more powerful is because of the second step “Applying”. In SQL, most actions in “Applying” steps are statistically related, like min, max, count, etc. However, in Pandas, “Applying” can perform much more."
},
{
"code": null,
"e": 1239,
"s": 1215,
"text": "From the doc of Pandas,"
},
{
"code": null,
"e": 1297,
"s": 1239,
"text": "In the apply step, we might wish to one of the following:"
},
{
"code": null,
"e": 1370,
"s": 1297,
"text": "Aggregation: compute a summary statistic (or statistics) for each group."
},
{
"code": null,
"e": 1461,
"s": 1370,
"text": "Transformation: perform some group-specific computations and return a like-indexed object."
},
{
"code": null,
"e": 1566,
"s": 1461,
"text": "Filtration: discard some groups, according to a group-wise computation that evaluates True or False. [1]"
},
{
"code": null,
"e": 1751,
"s": 1566,
"text": "In this article, I will cover some groupby applications. These applications do not only show me the insights from the data but also help me identify my next move on analyzing the data."
},
{
"code": null,
"e": 1764,
"s": 1751,
"text": "Let’s begin."
},
{
"code": null,
"e": 1903,
"s": 1764,
"text": "The data used in this article is “student-por.csv” in “Student Alcohol Consumption” from Kaggle. You can download the data from this link."
},
{
"code": null,
"e": 3214,
"s": 1903,
"text": "# Inputimport pandas as pd data = pd.read_csv('student-por.csv')data.info()# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 649 entries, 0 to 648Data columns (total 33 columns):school 649 non-null objectsex 649 non-null objectage 649 non-null int64address 649 non-null objectfamsize 649 non-null objectPstatus 649 non-null objectMedu 649 non-null int64Fedu 649 non-null int64Mjob 649 non-null objectFjob 649 non-null objectreason 649 non-null objectguardian 649 non-null objecttraveltime 649 non-null int64studytime 649 non-null int64failures 649 non-null int64schoolsup 649 non-null objectfamsup 649 non-null objectpaid 649 non-null objectactivities 649 non-null objectnursery 649 non-null objecthigher 649 non-null objectinternet 649 non-null objectromantic 649 non-null objectfamrel 649 non-null int64freetime 649 non-null int64goout 649 non-null int64Dalc 649 non-null int64Walc 649 non-null int64health 649 non-null int64absences 649 non-null int64G1 649 non-null int64G2 649 non-null int64G3 649 non-null int64dtypes: int64(16), object(17)memory usage: 167.4+ KB"
},
{
"code": null,
"e": 3613,
"s": 3214,
"text": "The first step is rather simple, grouping data based on the value in one or more columns. You only need to specify how to perform the grouping. Most people already know that a column name or a list of column names can be used for grouping. However, you can also pass a function for the grouping. The function will use the index value as the parameter and perform the grouping. For further info, [2]"
},
{
"code": null,
"e": 3748,
"s": 3613,
"text": "The object returned from the groupby function is “DataFrameGroupBy object”. After the grouping, you can use groupto see the groupings."
},
{
"code": null,
"e": 5281,
"s": 3748,
"text": "#Groupby one column# Inputdata.groupby('school')# Output<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000024D28C9DF98># Inputdata.groupby('school').groups# Output{'GP': Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,...413, 414, 415, 416, 417, 418, 419, 420, 421, 422],dtype='int64', length=423), 'MS': Int64Index([423, 424, 425, 426, 427, 428, 429, 430, 431, 432,...639, 640, 641, 642, 643, 644, 645, 646, 647, 648],dtype='int64', length=226)}# Groupby a function # Inputdef grouping(int): if int%10==0: return 'Group1' if int%5==0: return 'Group2' return 'Group3'data.groupby(grouping).groups# Output{'Group1': Int64Index([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640], dtype='int64'), 'Group2': Int64Index([ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 105, 115, 125,135, 145, 155, 165, 175, 185, 195, 205, 215, 225, 235, 245, 255, 265, 275, 285, 295, 305, 315, 325, 335, 345, 355, 365, 375, 385, 395, 405, 415, 425, 435, 445, 455, 465, 475, 485, 495, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 605, 615, 625, 635, 645], dtype='int64'), 'Group3': Int64Index([ 1, 2, 3, 4, 6, 7, 8, 9, 11, 12,... 637, 638, 639, 641, 642, 643, 644, 646, 647, 648],dtype='int64', length=519)}"
},
{
"code": null,
"e": 5509,
"s": 5281,
"text": "In the above example using a function for grouping, the index in the dataframe is the row number. Therefore, a row is assigned to one of three groups based on the row number. And then groupby function groups these three groups."
},
{
"code": null,
"e": 5608,
"s": 5509,
"text": "To get the data for each group, you can then use the get_group()function and input the group name."
},
{
"code": null,
"e": 5657,
"s": 5608,
"text": "#Inputdata.groupby(grouping).get_group('Group1')"
},
{
"code": null,
"e": 5791,
"s": 5657,
"text": "Furthermore, if you want to groupby the data by a non-index column, you can use apply and lambda functions together for the grouping."
},
{
"code": null,
"e": 5881,
"s": 5791,
"text": "# Inputdata.groupby(data['famsize'].apply(lambda x: x.startswith('GT'))).get_group(False)"
},
{
"code": null,
"e": 6136,
"s": 5881,
"text": "After grouping, you can already apply a number of computation or statistics functions. For example, size()can give you the numbers of rows for each group; sum()returns the sum for all numeric columns for each group. To know more applicable functions, [3]"
},
{
"code": null,
"e": 6265,
"s": 6136,
"text": "#Inputdata.groupby(data['famsize'].apply(lambda x: x.startswith('GT'))).size()#OutputfamsizeFalse 192True 457dtype: int64"
},
{
"code": null,
"e": 6614,
"s": 6265,
"text": "It is time to cover the important part of groupby. Groupby function in Pandas is way more powerful than in SQL because you can not only use common statistics functions like min(), max(), mean(),... but also lots of more complex functions. You can also apply your defined functions. In the below section, I will explain the three actions separately."
},
{
"code": null,
"e": 6789,
"s": 6614,
"text": "An easy explanation about aggregation is to perform a computation based on previously grouped data. The aggregation is applied to each group and return its respective result."
},
{
"code": null,
"e": 6959,
"s": 6789,
"text": "Some common computations are like sum, min, max, ... You can perform the computation to all numeric columns, or you can also specify a column to perform the computation."
},
{
"code": null,
"e": 7016,
"s": 6959,
"text": "#Input mjob_gp = data.groupby('Mjob')mjob_gp.agg('mean')"
},
{
"code": null,
"e": 7190,
"s": 7016,
"text": "#Inputmjob_gp['age'].agg('mean')#OutputMjobat_home 16.955556health 16.312500other 16.802326services 16.661765teacher 16.583333Name: age, dtype: float64"
},
{
"code": null,
"e": 7385,
"s": 7190,
"text": "One less commonly known about aggregation is that you can perform multiple computations on one or more columns together. This one is useful if you want to investigate the statistics of a column."
},
{
"code": null,
"e": 7428,
"s": 7385,
"text": "#Input mjob_gp.agg({'age':['mean','max']})"
},
{
"code": null,
"e": 7737,
"s": 7428,
"text": "However, one problem is that the columns are in multi-index which is not so good for further processing(and I don't like multi-index personally). Therefore, we can take one step further and include pd.NamedAgg (New from 0.25.0 version of Pandas) to aggfunction. For further information about pd.NamedAgg, [4]"
},
{
"code": null,
"e": 7928,
"s": 7737,
"text": "#Inputmjob_gp.agg(avg_age=pd.NamedAgg(column='age', aggfunc='mean'), min_age=pd.NamedAgg(column='age', aggfunc='min'), max_age=pd.NamedAgg(column='age', aggfunc='max'))"
},
{
"code": null,
"e": 8111,
"s": 7928,
"text": "There are two advantages using pd.NamedAgg. The first advantage is, of course, no multi-index on the columns. And the second advantage is that you can custom define the column names."
},
{
"code": null,
"e": 8191,
"s": 8111,
"text": "Not surprisingly, you can also use custom-defined functions in the aggregation."
},
{
"code": null,
"e": 8445,
"s": 8191,
"text": "#Input def range_function(x): return max(x) - min(x)mjob_gp.agg(max_age = pd.NamedAgg(column='age',aggfunc='max'), min_age = pd.NamedAgg(column='age',aggfunc='min'), range_age = pd.NamedAgg(column='age',aggfunc=range_function),)"
},
{
"code": null,
"e": 8488,
"s": 8445,
"text": "Back to the description of transformation,"
},
{
"code": null,
"e": 8579,
"s": 8488,
"text": "Transformation: perform some group-specific computations and return a like-indexed object."
},
{
"code": null,
"e": 8786,
"s": 8579,
"text": "The key part is “group-specific computations”. The computations are different across different groups. For example, maxwill give you the maximum of a column for each group, but not across the whole dataset."
},
{
"code": null,
"e": 9222,
"s": 8786,
"text": "Another characteristic of transformation is that the computation applies to each row and returns back the results with the same length of each group, not like aggregation with reduced lengths. If you are familiar with window function in SQL, transformation in Pandas is similar to that. (PS: You still don't know window function in SQL?!?! Check my previous article that helps you understand why window function in SQL is so important)"
},
{
"code": null,
"e": 9245,
"s": 9222,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9318,
"s": 9245,
"text": "#Input mjob_gp['G1','G2','G3'].transform(lambda x: (x-x.mean())/x.std())"
},
{
"code": null,
"e": 9461,
"s": 9318,
"text": "In the above example, for each group, the values of G1 to G3 are normalized based on the mean and standard deviation for the respective group."
},
{
"code": null,
"e": 9493,
"s": 9461,
"text": "From the description in Pandas,"
},
{
"code": null,
"e": 9618,
"s": 9493,
"text": "Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func. [5]"
},
{
"code": null,
"e": 9704,
"s": 9618,
"text": "You can use filterfunction to filter out any groups that do not satisfy the criteria."
},
{
"code": null,
"e": 9757,
"s": 9704,
"text": "#Input mjob_gp.filter(lambda x: x['G1'].mean() > 12)"
},
{
"code": null,
"e": 9879,
"s": 9757,
"text": "In the above example, only Mjob under “health” and “teacher” are returned because their means of “G1” are larger than 12."
},
{
"code": null,
"e": 10047,
"s": 9879,
"text": "#Input mjob_gp['G1'].mean()#OutputMjobat_home 10.451852health 12.395833other 11.275194services 11.610294teacher 12.555556Name: G1, dtype: float64"
},
{
"code": null,
"e": 10358,
"s": 10047,
"text": "Groupby function in Pandas is a handy tool to perform lots of analyses and data transformations. I hope this article helps you understand the power and usefulness of groupby in Pandas. I am sure you now know more about how to use groupby in your usual data analysis. Have fun with Pandas and see you next time."
},
{
"code": null,
"e": 10435,
"s": 10358,
"text": "Bookmark this if you are new to Python (especially if you self-learn Python)"
},
{
"code": null,
"e": 10521,
"s": 10435,
"text": "(Part 2) Bookmark this if you are new to Python (especially if you self-learn Python)"
},
{
"code": null,
"e": 10564,
"s": 10521,
"text": "How to use Pandas to analyze numeric data?"
},
{
"code": null,
"e": 10611,
"s": 10564,
"text": "Web Scrape Twitter by Python Selenium (Part 1)"
},
{
"code": null,
"e": 10658,
"s": 10611,
"text": "Web Scrape Twitter by Python Selenium (Part 2)"
},
{
"code": null,
"e": 10693,
"s": 10658,
"text": "[1]: Group By: split-apply-combine"
},
{
"code": null,
"e": 10723,
"s": 10693,
"text": "[2]: pandas.DataFrame.groupby"
},
{
"code": null,
"e": 10761,
"s": 10723,
"text": "[3]: Computations / descriptive stats"
}
] |
Kernel Regression from Scratch | Kunj Mehta | Towards Data Science | Every beginner in Machine Learning starts by studying what regression means and how the linear regression algorithm works. In fact, the ease of understanding, explainability and the vast effective real-world use cases of linear regression is what makes the algorithm so famous. However, there are some situations to which linear regression is not suited. In this article, we will see what these situations are, what the kernel regression algorithm is and how it fits into the scenario. Finally, we will code the kernel regression algorithm with a Gaussian kernel from scratch. Basic knowledge of Python and numpy is required to follow the article.
Given data in the form of N feature vectors x=[x1, x2, ..., xn] consisting of n features and the corresponding label vector y, linear regression tries to fit a line that best describes the data. For this, it tries to find the optimal coefficients ci, i∈{0, ..., n} of the line equation y = c0 + c1x1+c2x2+...+cnxn usually by gradient descent with the model accuracy measured on the RMSE metric. The equation obtained is then used to predict the target yt for new unseen input vector xt.
Linear regression is a simple algorithm that cannot model very complex relationships between the features. Mathematically, this is because well, it is linear with the degree of the equation being 1, which means that linear regression will always model a straight line. Indeed, this linearity is the weakness of the linear regression algorithm. Why?
Well, let’s consider a situation where our data doesn’t have the form of a straight line: let’s take data generated using the function f(x) = x3. If we use linear regression to fit a model to this data, we will never get anywhere close to the true cubic function because the equation for which we are finding the coefficients does not have a cubic term! So, for any data not generated using a linear function, linear regression is very likely to underfit. So, what do we do?
We can use another type of regression called polynomial regression which tries to find optimal coefficients of a (as the name suggests) polynomial equation with the degree of the equation being n, n⪈1. However, with polynomial regression another problem arises: as a data analyst, you cannot know what the degree of the equation should be so that the resulting equation fits best to the data. This can only be determined by trial and error which is made more difficult by the fact that above degree 3, the model built using polynomial regression is difficult to visualize.
This is where kernel regression can come to the rescue!
Seeing the name, you may ask that if ‘linear’ in linear regression meant a linear function and ‘polynomial’ in polynomial regression meant a polynomial function, what does ‘kernel’ mean? Turns out, it means a kernel function! So, what is a kernel function? Simply, it is a similarity function that takes two inputs and spits out how similar they are. We will see shortly how a kernel function is used in kernel regression.
Now about kernel regression. Unlike linear and polynomial regression in which the optimal parameter vector c=[c1, c2, ..., cn] needs to be learnt, kernel regression is non-parametric, meaning that it calculates the target yt by performing computations directly on the input xt.
How?
Given data points (xi, yi) Kernel Regression goes about predicting by first constructing a kernel k for each data point xi. Then for a given new input xt, it computes a similarity score with each xi (given by xi-xt) using the kernel ; the similarity score acts as a weight wi that represents the importance of that kernel (and corresponding label yi) in predicting the target yt. The prediction is then obtained by multiplying the weight vector w= [w1, w2, ..., wn] with the label vector y= [y1, y2, ..., yn].
Now, there can be different kernel functions which give rise to different types of kernel regressions. One such type is the Gaussian Kernel Regression in which the shape of the constructed kernel is the Gaussian curve also known as the bell-shaped curve. In the context of Gaussian Kernel Regression, each constructed kernel can also be viewed as a normal distribution with mean value xi and standard deviation b. Here, b is a hyperparameter that controls the shape (in particular, the width of the Gaussian curve in Gaussian kernels) of the curve. The equation for the Gaussian kernel k is given below. Notice the similarity between this equation and that of the Gaussian (also called normal) distribution.
We will code this type of kernel regression next.
We will first look at the case of a one-dimensional feature vector and then extend it to n dimensions.
from scipy.stats import normimport numpy as np import pandas as pdimport matplotlib.pyplot as pltimport mathclass GKR: def __init__(self, x, y, b): self.x = x self.y = y self.b = b '''Implement the Gaussian Kernel''' def gaussian_kernel(self, z): return (1/math.sqrt(2*math.pi))*math.exp(-0.5*z**2) '''Calculate weights and return prediction''' def predict(self, X): kernels = [self.gaussian_kernel((xi-X)/self.b) for xi in self.x] weights = [len(self.x) * (kernel/np.sum(kernels)) for kernel in kernels] return np.dot(weights, self.y)/len(self.x)
We define a class for Gaussian Kernel Regression which takes in the feature vector x, the label vector y and the hyperparameter b during initialization. Inside the class, we define a function gaussian_kernel() that implements the Gaussian kernel. You can see that we just write out the mathematical equation as code. Next, we define the function predict() that takes in the feature vector xt (referred to in code as X) whose target value has to be predicted. Inside the function, we construct kernels for each xi, calculate the weights and return the prediction, again by plugging in the mathematical equations into code as-is.
Now, let’s pass in some dummy data and see the prediction that is output. We predict the value for xt = 50 (by ignoring for demonstration purposes that it is already present in training data)
gkr = GKR([10,20,30,40,50,60,70,80,90,100,110,120], [2337,2750,2301,2500,1700,2100,1100,1750,1000,1642, 2000,1932], 10)gkr.predict(50)
This gives us an output of 1995.285
Now, let’s extend the code for the case of n dimensional feature vectors. The only modification we need to make is in the similarity score calculation. Instead of obtaining the difference between xi and xt, we calculate the similarity score in the n dimensional case as the Euclidean distance ||xi-xt|| between them. Note that for the purposes of handling n dimensional vectors, we use numpy wherever needed.
from scipy.stats import multivariate_normal'''Class for Gaussian Kernel Regression'''class GKR: def __init__(self, x, y, b): self.x = np.array(x) self.y = np.array(y) self.b = b '''Implement the Gaussian Kernel''' def gaussian_kernel(self, z): return (1/np.sqrt(2*np.pi))*np.exp(-0.5*z**2) '''Calculate weights and return prediction''' def predict(self, X): kernels = np.array([self.gaussian_kernel((np.linalg.norm(xi-X))/self.b) for xi in self.x]) weights = np.array([len(self.x) * (kernel/np.sum(kernels)) for kernel in kernels]) return np.dot(weights.T, self.y)/len(self.x)
Again, let’s pass in some 2D dummy data and predict for xt = [20, 40].
gkr = GKR([[11,15],[22,30],[33,45],[44,60],[50,52],[67,92],[78,107],[89,123],[100,137]], [2337,2750,2301,2500,1700,1100,1000,1642, 1932], 10)gkr.predict([20,40])
We get yt = 2563.086.
The extended code (including for visualizations) for this article can be found on GitHub and Kaggle.
We saw where and why linear regression and polynomial regression cannot be used and with that background understood the intuition behind and the working of kernel regression and how it can be used as an alternative. We went into the details of the Gaussian kernel regression and coded it from scratch in Python by simply plugging in the mathematical equations to code.
I would love to connect with you on Linkedin!
[1] A. Burkov, The Hundred-Page Machine Learning Book (2019), Published by Andriy Burkov. | [
{
"code": null,
"e": 820,
"s": 172,
"text": "Every beginner in Machine Learning starts by studying what regression means and how the linear regression algorithm works. In fact, the ease of understanding, explainability and the vast effective real-world use cases of linear regression is what makes the algorithm so famous. However, there are some situations to which linear regression is not suited. In this article, we will see what these situations are, what the kernel regression algorithm is and how it fits into the scenario. Finally, we will code the kernel regression algorithm with a Gaussian kernel from scratch. Basic knowledge of Python and numpy is required to follow the article."
},
{
"code": null,
"e": 1307,
"s": 820,
"text": "Given data in the form of N feature vectors x=[x1, x2, ..., xn] consisting of n features and the corresponding label vector y, linear regression tries to fit a line that best describes the data. For this, it tries to find the optimal coefficients ci, i∈{0, ..., n} of the line equation y = c0 + c1x1+c2x2+...+cnxn usually by gradient descent with the model accuracy measured on the RMSE metric. The equation obtained is then used to predict the target yt for new unseen input vector xt."
},
{
"code": null,
"e": 1656,
"s": 1307,
"text": "Linear regression is a simple algorithm that cannot model very complex relationships between the features. Mathematically, this is because well, it is linear with the degree of the equation being 1, which means that linear regression will always model a straight line. Indeed, this linearity is the weakness of the linear regression algorithm. Why?"
},
{
"code": null,
"e": 2131,
"s": 1656,
"text": "Well, let’s consider a situation where our data doesn’t have the form of a straight line: let’s take data generated using the function f(x) = x3. If we use linear regression to fit a model to this data, we will never get anywhere close to the true cubic function because the equation for which we are finding the coefficients does not have a cubic term! So, for any data not generated using a linear function, linear regression is very likely to underfit. So, what do we do?"
},
{
"code": null,
"e": 2704,
"s": 2131,
"text": "We can use another type of regression called polynomial regression which tries to find optimal coefficients of a (as the name suggests) polynomial equation with the degree of the equation being n, n⪈1. However, with polynomial regression another problem arises: as a data analyst, you cannot know what the degree of the equation should be so that the resulting equation fits best to the data. This can only be determined by trial and error which is made more difficult by the fact that above degree 3, the model built using polynomial regression is difficult to visualize."
},
{
"code": null,
"e": 2760,
"s": 2704,
"text": "This is where kernel regression can come to the rescue!"
},
{
"code": null,
"e": 3183,
"s": 2760,
"text": "Seeing the name, you may ask that if ‘linear’ in linear regression meant a linear function and ‘polynomial’ in polynomial regression meant a polynomial function, what does ‘kernel’ mean? Turns out, it means a kernel function! So, what is a kernel function? Simply, it is a similarity function that takes two inputs and spits out how similar they are. We will see shortly how a kernel function is used in kernel regression."
},
{
"code": null,
"e": 3461,
"s": 3183,
"text": "Now about kernel regression. Unlike linear and polynomial regression in which the optimal parameter vector c=[c1, c2, ..., cn] needs to be learnt, kernel regression is non-parametric, meaning that it calculates the target yt by performing computations directly on the input xt."
},
{
"code": null,
"e": 3466,
"s": 3461,
"text": "How?"
},
{
"code": null,
"e": 3976,
"s": 3466,
"text": "Given data points (xi, yi) Kernel Regression goes about predicting by first constructing a kernel k for each data point xi. Then for a given new input xt, it computes a similarity score with each xi (given by xi-xt) using the kernel ; the similarity score acts as a weight wi that represents the importance of that kernel (and corresponding label yi) in predicting the target yt. The prediction is then obtained by multiplying the weight vector w= [w1, w2, ..., wn] with the label vector y= [y1, y2, ..., yn]."
},
{
"code": null,
"e": 4684,
"s": 3976,
"text": "Now, there can be different kernel functions which give rise to different types of kernel regressions. One such type is the Gaussian Kernel Regression in which the shape of the constructed kernel is the Gaussian curve also known as the bell-shaped curve. In the context of Gaussian Kernel Regression, each constructed kernel can also be viewed as a normal distribution with mean value xi and standard deviation b. Here, b is a hyperparameter that controls the shape (in particular, the width of the Gaussian curve in Gaussian kernels) of the curve. The equation for the Gaussian kernel k is given below. Notice the similarity between this equation and that of the Gaussian (also called normal) distribution."
},
{
"code": null,
"e": 4734,
"s": 4684,
"text": "We will code this type of kernel regression next."
},
{
"code": null,
"e": 4837,
"s": 4734,
"text": "We will first look at the case of a one-dimensional feature vector and then extend it to n dimensions."
},
{
"code": null,
"e": 5461,
"s": 4837,
"text": "from scipy.stats import normimport numpy as np import pandas as pdimport matplotlib.pyplot as pltimport mathclass GKR: def __init__(self, x, y, b): self.x = x self.y = y self.b = b '''Implement the Gaussian Kernel''' def gaussian_kernel(self, z): return (1/math.sqrt(2*math.pi))*math.exp(-0.5*z**2) '''Calculate weights and return prediction''' def predict(self, X): kernels = [self.gaussian_kernel((xi-X)/self.b) for xi in self.x] weights = [len(self.x) * (kernel/np.sum(kernels)) for kernel in kernels] return np.dot(weights, self.y)/len(self.x)"
},
{
"code": null,
"e": 6089,
"s": 5461,
"text": "We define a class for Gaussian Kernel Regression which takes in the feature vector x, the label vector y and the hyperparameter b during initialization. Inside the class, we define a function gaussian_kernel() that implements the Gaussian kernel. You can see that we just write out the mathematical equation as code. Next, we define the function predict() that takes in the feature vector xt (referred to in code as X) whose target value has to be predicted. Inside the function, we construct kernels for each xi, calculate the weights and return the prediction, again by plugging in the mathematical equations into code as-is."
},
{
"code": null,
"e": 6281,
"s": 6089,
"text": "Now, let’s pass in some dummy data and see the prediction that is output. We predict the value for xt = 50 (by ignoring for demonstration purposes that it is already present in training data)"
},
{
"code": null,
"e": 6416,
"s": 6281,
"text": "gkr = GKR([10,20,30,40,50,60,70,80,90,100,110,120], [2337,2750,2301,2500,1700,2100,1100,1750,1000,1642, 2000,1932], 10)gkr.predict(50)"
},
{
"code": null,
"e": 6452,
"s": 6416,
"text": "This gives us an output of 1995.285"
},
{
"code": null,
"e": 6861,
"s": 6452,
"text": "Now, let’s extend the code for the case of n dimensional feature vectors. The only modification we need to make is in the similarity score calculation. Instead of obtaining the difference between xi and xt, we calculate the similarity score in the n dimensional case as the Euclidean distance ||xi-xt|| between them. Note that for the purposes of handling n dimensional vectors, we use numpy wherever needed."
},
{
"code": null,
"e": 7514,
"s": 6861,
"text": "from scipy.stats import multivariate_normal'''Class for Gaussian Kernel Regression'''class GKR: def __init__(self, x, y, b): self.x = np.array(x) self.y = np.array(y) self.b = b '''Implement the Gaussian Kernel''' def gaussian_kernel(self, z): return (1/np.sqrt(2*np.pi))*np.exp(-0.5*z**2) '''Calculate weights and return prediction''' def predict(self, X): kernels = np.array([self.gaussian_kernel((np.linalg.norm(xi-X))/self.b) for xi in self.x]) weights = np.array([len(self.x) * (kernel/np.sum(kernels)) for kernel in kernels]) return np.dot(weights.T, self.y)/len(self.x)"
},
{
"code": null,
"e": 7585,
"s": 7514,
"text": "Again, let’s pass in some 2D dummy data and predict for xt = [20, 40]."
},
{
"code": null,
"e": 7747,
"s": 7585,
"text": "gkr = GKR([[11,15],[22,30],[33,45],[44,60],[50,52],[67,92],[78,107],[89,123],[100,137]], [2337,2750,2301,2500,1700,1100,1000,1642, 1932], 10)gkr.predict([20,40])"
},
{
"code": null,
"e": 7769,
"s": 7747,
"text": "We get yt = 2563.086."
},
{
"code": null,
"e": 7870,
"s": 7769,
"text": "The extended code (including for visualizations) for this article can be found on GitHub and Kaggle."
},
{
"code": null,
"e": 8239,
"s": 7870,
"text": "We saw where and why linear regression and polynomial regression cannot be used and with that background understood the intuition behind and the working of kernel regression and how it can be used as an alternative. We went into the details of the Gaussian kernel regression and coded it from scratch in Python by simply plugging in the mathematical equations to code."
},
{
"code": null,
"e": 8285,
"s": 8239,
"text": "I would love to connect with you on Linkedin!"
}
] |
Putting ML in production I: using Apache Kafka in Python. | by Javier Rodriguez Zaurin | Towards Data Science | This is the first of 2 posts where we will illustrate how one could use a series of tools (mostly Kafka and MLFlow) to help productionising ML. To that aim we will set a simple scenario that we hope resembles some real-word use-cases, and then describe a potential solution. The companion repo with all the code can be found here.
A company collects data using a series of services that generate events as the users/customers interact with the the company’s website or app. As these interactions happen, an algorithm needs to run in real time and some immediate action needs to be taken based on the algorithm’s outputs (or predictions). On top of that, after N interactions (or observations) the algorithm needs to be retrained without stopping the prediction service, since users will keep interacting.
For the exercise here we have used the Adult dataset, where the goal is to predict whether individuals earn an income higher/lower than 50k based on their age, native country, etc. To adapt this dataset to the scenario described before, one could assume that age, native country, etc is collected through an online questionnaire/form and we need to predict whether users have high/low income in real time. If high income, then we immediately call/email them with some offer, for example. Then, after N new observations we retrain the algorithm while we keep predicting on new users.
The solution
Figure 1 is an illustration of a potential solution. To implement this solution we have used Kafka-Python (a nice tutorial can be found here), along with LightGBM and Hyperopt or HyperparameterHunter.
The only Python “outsider” we will use in this exercise is Apache-Kafka (we will use the python API Kafka-Python but still, Kafka needs to be installed in your system). If you are on a mac, just use Homebrew:
brew install kafka
which will also install the zookeeper dependency.
As mentioned before, we have used the Adult dataset. This is because our intention is to illustrate a potential ML pipeline and to provide useful code while keeping it relatively simple. Note however that the pipeline described here is, in principle, data-agnostic. Of course, the preprocessing will change depending on the nature of the data, but the pipeline components will remain similar if not identical.
Initialising the experiment
The code used for this post (and more) can be found in our repo. There, there is a script named initialize.py . This script will download the dataset, set the dir structure, pre-preprocess the data, train an initial model on the training dataset and optimise the hyperparameters of that model. In the real world this would correspond to the usual experimentation phase and the process of training the initial algorithm offline.
In this post we want to focus mostly on the pipeline and the corresponding components more than on the ML. Nonetheless, let us just briefly mention the ML tooling we use for this exercise.
The data preprocessing is rather simple given the dataset that we are using. We have coded a customised class called FeatureTools that can be found in the utils module in the repo. This class has.fitand .transform methods that will normalise/scale numerical features, encode categorical features and generate what we call “crossed columns”, which are the result of the cartesian product between two (or more) categorical features.
Once the data is processed we use LightGBM to fit the model along with either Hyperopt or HyperparameterHunter to perform hyperparameter optimisation. The code related to this task can be found in the train module, where one can find two scripts train_hyperop.py and train_hyperparameterhunter.py .
We might write a separate post comparing hyperparameter optimisation packages in python (Skopt, Hyperopt and HyperparameterHunder), but for now, know this: if you want speed then use Hyperopt. If you are not concerned about speed and you want to keep detailed track of your optimisation routine, then use HyperparameterHunter. In the words of Hunter McGushion, the creator of the package:
“For so long, hyperparameter optimisation has been such a time consuming process that just pointed you in a direction for further optimization, then you basically had to start over.”
HyperparameterHunter is here to solve that problem, and it does it very well. Currently, the package is built on top of Skopt, which is why is notably slower than Hyperopt. However, I am aware that there are efforts to include Hyperopt as another backend for HyperparameterHunter. When this happens there will be no debate, HyperparameterHunter should be your tool of choice.
Nonetheless, in case someone is interested, I have included a notebook in the repo comparing Skopt and Hyperopt performances.
Let’s move now to the pipeline processes themselves.
The App Messages Producer
This is meant to be a relatively simple illustration of what part of a production pipeline could look like. Therefore, we directly use the Adult dataset to generate messages (JSON objects).
In the real world, one would have a number of services that would generate events. From there, one has a couple of options. The information in those events might be stored in a database and then aggregated through your usual queries. From there, a Kafka service will publish messages into the pipeline. Alternatively, all the information in those events might be directly published into different topics and an “aggregation service” might store all the information in a single message, which will then be published into the pipeline (of course, one could also have a combination of the two).
For example, users might be allowed to register through Facebook or Google, collecting their names and email addresses. Then they might be asked to fill a questionnaire and we keep collecting events as they progress. At some point during the process, all these events will be aggregated in a single message and then published via a Kafka producer. The pipeline in this post would start from the point where all the relevant information has been aggregated. Our messages here are individual observations in the Adult dataset. Below we include an example of the content of our messages:
’{“age”:25,”workclass”:”Private”,”fnlwgt”:226802,”education”:”11th”,”marital_status”:”Never-married”,”occupation”:”Machine-op-inspct”,”relationship”:”Own-child”,”race”:”Black”,”gender”:”Male”,”capital_gain”:0,”capital_loss”:0,”hours_per_week”:40,”native_country”:”United-States”,”income_bracket”:”<=50K.”}’
The core of the App/Service (grey, left-most box in Figure 1) is the snippet below:
Note that we use the testing dataset to generate the messages. This is because we have designed an scenario that tries to resemble as much as possible the real world (within certain limits). With that in mind, we have used the training dataset to build the initial model and dataprocessor objects. We then use the test dataset to generate messages with the aim of simulating the process of receiving new information through time.
Regarding to the snippet above, simply, a producer will publish messages into the pipeline ( start_producing()) and will consume messages with the final prediction ( start_consuming()). The same way that the pipeline we describe here does not include the very beginning of the process (events collection and aggregation), we also skip the very end, i.e. what to do with the final prediction. Nonetheless, we briefly discuss some use cases where this pipeline could be useful towards the end of the post that will illustrate that final stage.
In reality, apart from ignoring the very beginning and end of the process we believe that this pipeline resembles reasonably well to one that could be used in the real world. In consequence, we hope that the code included in our repo is useful for some of your projects.
Predictor and Trainer
The main goal of this implementation is running the algorithm in real time and retrain it every N observations without stopping the prediction service. To that aim we implemented two components, the Predictor ( predictor.py in the repo) and the Trainer ( trainer.py).
Let’s now describe one by one the numbers shown in Figure 1, using code snippets as our guidelines. Note that the process below assumes one has run the initialize.py script, so an initial model.pand dataprocessor.pfiles exist in the corresponding directory. Also, emphasise that the code below comprises the core of the Predictor and the Trainer. For the full code refer to the repo.
Predictor
The core of the Predictor’s code is shown below
(1a) Line 12 in the predictor.py snippet. The Predictor will receive the message from the App/Service, it will do the data processing and run the model in real time as it receives the messages. All this happens using the existing dataprocessor and model objects within the predict function.
(1b) Line 13 in the predictor.pysnippet. Once we have run the prediction, the Predictor will publish the result ( publish_prediction()) that will be eventually be received by the App/Service.
(2 ) Lines 17–20 in the predictor.pysnippet. Every RETRAIN_EVERY messages, the Predictor will publish a “retrain” message ( send_retrain_message()) to be read by the Trainer.
Trainer
(3) Line 12 in the trainer.py snippet. The Trainer will read the message and trigger a retraining process with the new, accumulated dataset ( train()) . This is, the original dataset plus RETRAIN_EVERYnew observations. The train function will run the entire process described in the “Initialising the experiment” section independently from the processes described in 1a and 1b. In other words, the Trainer will retrain a model while the Predictor keeps serving predictions as messages arrive.
At this stage it is worth mentioning that here we find a further difference between our implementation and one that would be used in the real world. In our implementation, it is possible to retrain the algorithm as soon as RETRAIN_EVERY number of observations have been processed. This is because we are using the Adult testing dataset to generate messages, which includes the target column (“income_braket”). In the real word the real outcome of the action taken based on the output of the algorithm would normally not be readily accessible just after the algorithm runs, but some time later. In that scenario, another process should be collecting the true outcome and, once the number of true outcomes collected equals RETRAIN_EVERY the algorithm will be retrained.
For example, let’s say that this pipeline implements a real-time recommendation system for an e-commerce. We have trained a recommendation algorithm offline and the target column is a categorical representation of how much our users like our recommendations: 0, 1, 2 and 3 for users that did not like or interacted with the item, liked the item (e.g. hit a like button), added the item to their basket, and bought the item respectively. By the time the system serves the recommendations we will still don’t know what will the user eventually do.
Therefore, along with a process collecting and storing the user information as they navigate the website (or app), a second process should collect what is the final outcome of our recommendation. Only when both processes have collected RETRAIN_EVERY messages and outcomes, the algorithm will be retrained.
(4) Line 13 in the trainer.py snippet. Once the retraining is done, a message with the corresponding information will be published ( published_training_completed()).
(5) Lines 5–8 in the predictor.py snippet. The Predictor’s consumer is subscribed to two topics: [‘app_messages’, ‘retrain_topic’]. Once it receives the information that the retraining is completed through the “retrain_topic” it will load the new model and keep with the process as usual, without stopping at any time during the process.
In the companion repo we have included instructions on how to run the pipeline (locally). Is actually quite simple.
Start zookeper and kafka:
Start zookeper and kafka:
$ brew services start zookeeper==> Successfully started `zookeeper` (label: homebrew.mxcl.zookeeper)$ brew services start kafka==> Successfully started `kafka` (label: homebrew.mxcl.kafka)
2. Run initialize.py:
python initialize.py
3. In Terminal#1 run the Predictor (or the Trainer):
python predictor.py
4. In Terminal#2 run the Trainer (or the Predictor):
python trainer.py
5. In Terminal#3 run the Sample App
python samplea_app.py
Then, once N number of messages have been processed you should see something like this:
Upper right terminal: we have retrained the model and Hyperopt has run 10 evaluations (in a real exercise these should be a few hundred). Upper left terminal: once the model is retrained and optimised we see how the predictor has loaded the new model (after the annoying warning message from the new LightGBM version). Bottom terminal: the service proceeds as usual.
Here are a couple of potential use cases, among (many) others.
Adapting online journeys in real time
Adapting online journeys in real time
Let’s consider an e-commerce selling some items. As users navigate through the website we collect events with information on their actions. We have previously trained an algorithm and we know that after, let’s say, 10 interactions, we are in a good position to know whether a customer will end up buying our products. Moreover, we also know that the products they will potentially buy will possibly be expensive. Therefore, we would like to customise their journey “on-the-go” to facilitate their shopping experience. Customisation here can mean anything, from shortening the journey to change the page layout.
2. Email/call your customers
Similarly to the use-case before, let’s assume now that the customer decides to stop the journey (bored, lack of time, maybe too complex, etc). We could use a pipeline like the one described in this post to either immediately, or with a controlled delay, send an email or call them if the algorithm predicts that this customer is of great potential.
Loggings and monitoring: in an upcoming post we will insert in the pipeline loggings and monitoring functionalities via MLFlow. Along with HyperparameterHunter, this solution will automatically keep full track of both model performance and hyperparameter optimization, while offering visual monitoring.Flow management: the solution described here, and the corresponding code, has been designed so it can easily run in a laptop, locally. However, one would assume that in real life this will have to run the cloud, at scale. This specific part will not be covered in the two posts. However, I can assure you that moving the structure described here to AWS (for example) and run it automatically at your convenience (using EC2s, S3 and whatever the front end has to be for your particular case) is not particularly complex.
Loggings and monitoring: in an upcoming post we will insert in the pipeline loggings and monitoring functionalities via MLFlow. Along with HyperparameterHunter, this solution will automatically keep full track of both model performance and hyperparameter optimization, while offering visual monitoring.
Flow management: the solution described here, and the corresponding code, has been designed so it can easily run in a laptop, locally. However, one would assume that in real life this will have to run the cloud, at scale. This specific part will not be covered in the two posts. However, I can assure you that moving the structure described here to AWS (for example) and run it automatically at your convenience (using EC2s, S3 and whatever the front end has to be for your particular case) is not particularly complex.
Any questions/suggestions, please email: [email protected] | [
{
"code": null,
"e": 502,
"s": 171,
"text": "This is the first of 2 posts where we will illustrate how one could use a series of tools (mostly Kafka and MLFlow) to help productionising ML. To that aim we will set a simple scenario that we hope resembles some real-word use-cases, and then describe a potential solution. The companion repo with all the code can be found here."
},
{
"code": null,
"e": 976,
"s": 502,
"text": "A company collects data using a series of services that generate events as the users/customers interact with the the company’s website or app. As these interactions happen, an algorithm needs to run in real time and some immediate action needs to be taken based on the algorithm’s outputs (or predictions). On top of that, after N interactions (or observations) the algorithm needs to be retrained without stopping the prediction service, since users will keep interacting."
},
{
"code": null,
"e": 1559,
"s": 976,
"text": "For the exercise here we have used the Adult dataset, where the goal is to predict whether individuals earn an income higher/lower than 50k based on their age, native country, etc. To adapt this dataset to the scenario described before, one could assume that age, native country, etc is collected through an online questionnaire/form and we need to predict whether users have high/low income in real time. If high income, then we immediately call/email them with some offer, for example. Then, after N new observations we retrain the algorithm while we keep predicting on new users."
},
{
"code": null,
"e": 1572,
"s": 1559,
"text": "The solution"
},
{
"code": null,
"e": 1773,
"s": 1572,
"text": "Figure 1 is an illustration of a potential solution. To implement this solution we have used Kafka-Python (a nice tutorial can be found here), along with LightGBM and Hyperopt or HyperparameterHunter."
},
{
"code": null,
"e": 1982,
"s": 1773,
"text": "The only Python “outsider” we will use in this exercise is Apache-Kafka (we will use the python API Kafka-Python but still, Kafka needs to be installed in your system). If you are on a mac, just use Homebrew:"
},
{
"code": null,
"e": 2001,
"s": 1982,
"text": "brew install kafka"
},
{
"code": null,
"e": 2051,
"s": 2001,
"text": "which will also install the zookeeper dependency."
},
{
"code": null,
"e": 2461,
"s": 2051,
"text": "As mentioned before, we have used the Adult dataset. This is because our intention is to illustrate a potential ML pipeline and to provide useful code while keeping it relatively simple. Note however that the pipeline described here is, in principle, data-agnostic. Of course, the preprocessing will change depending on the nature of the data, but the pipeline components will remain similar if not identical."
},
{
"code": null,
"e": 2489,
"s": 2461,
"text": "Initialising the experiment"
},
{
"code": null,
"e": 2917,
"s": 2489,
"text": "The code used for this post (and more) can be found in our repo. There, there is a script named initialize.py . This script will download the dataset, set the dir structure, pre-preprocess the data, train an initial model on the training dataset and optimise the hyperparameters of that model. In the real world this would correspond to the usual experimentation phase and the process of training the initial algorithm offline."
},
{
"code": null,
"e": 3106,
"s": 2917,
"text": "In this post we want to focus mostly on the pipeline and the corresponding components more than on the ML. Nonetheless, let us just briefly mention the ML tooling we use for this exercise."
},
{
"code": null,
"e": 3537,
"s": 3106,
"text": "The data preprocessing is rather simple given the dataset that we are using. We have coded a customised class called FeatureTools that can be found in the utils module in the repo. This class has.fitand .transform methods that will normalise/scale numerical features, encode categorical features and generate what we call “crossed columns”, which are the result of the cartesian product between two (or more) categorical features."
},
{
"code": null,
"e": 3836,
"s": 3537,
"text": "Once the data is processed we use LightGBM to fit the model along with either Hyperopt or HyperparameterHunter to perform hyperparameter optimisation. The code related to this task can be found in the train module, where one can find two scripts train_hyperop.py and train_hyperparameterhunter.py ."
},
{
"code": null,
"e": 4225,
"s": 3836,
"text": "We might write a separate post comparing hyperparameter optimisation packages in python (Skopt, Hyperopt and HyperparameterHunder), but for now, know this: if you want speed then use Hyperopt. If you are not concerned about speed and you want to keep detailed track of your optimisation routine, then use HyperparameterHunter. In the words of Hunter McGushion, the creator of the package:"
},
{
"code": null,
"e": 4408,
"s": 4225,
"text": "“For so long, hyperparameter optimisation has been such a time consuming process that just pointed you in a direction for further optimization, then you basically had to start over.”"
},
{
"code": null,
"e": 4784,
"s": 4408,
"text": "HyperparameterHunter is here to solve that problem, and it does it very well. Currently, the package is built on top of Skopt, which is why is notably slower than Hyperopt. However, I am aware that there are efforts to include Hyperopt as another backend for HyperparameterHunter. When this happens there will be no debate, HyperparameterHunter should be your tool of choice."
},
{
"code": null,
"e": 4910,
"s": 4784,
"text": "Nonetheless, in case someone is interested, I have included a notebook in the repo comparing Skopt and Hyperopt performances."
},
{
"code": null,
"e": 4963,
"s": 4910,
"text": "Let’s move now to the pipeline processes themselves."
},
{
"code": null,
"e": 4989,
"s": 4963,
"text": "The App Messages Producer"
},
{
"code": null,
"e": 5179,
"s": 4989,
"text": "This is meant to be a relatively simple illustration of what part of a production pipeline could look like. Therefore, we directly use the Adult dataset to generate messages (JSON objects)."
},
{
"code": null,
"e": 5771,
"s": 5179,
"text": "In the real world, one would have a number of services that would generate events. From there, one has a couple of options. The information in those events might be stored in a database and then aggregated through your usual queries. From there, a Kafka service will publish messages into the pipeline. Alternatively, all the information in those events might be directly published into different topics and an “aggregation service” might store all the information in a single message, which will then be published into the pipeline (of course, one could also have a combination of the two)."
},
{
"code": null,
"e": 6356,
"s": 5771,
"text": "For example, users might be allowed to register through Facebook or Google, collecting their names and email addresses. Then they might be asked to fill a questionnaire and we keep collecting events as they progress. At some point during the process, all these events will be aggregated in a single message and then published via a Kafka producer. The pipeline in this post would start from the point where all the relevant information has been aggregated. Our messages here are individual observations in the Adult dataset. Below we include an example of the content of our messages:"
},
{
"code": null,
"e": 6663,
"s": 6356,
"text": "’{“age”:25,”workclass”:”Private”,”fnlwgt”:226802,”education”:”11th”,”marital_status”:”Never-married”,”occupation”:”Machine-op-inspct”,”relationship”:”Own-child”,”race”:”Black”,”gender”:”Male”,”capital_gain”:0,”capital_loss”:0,”hours_per_week”:40,”native_country”:”United-States”,”income_bracket”:”<=50K.”}’"
},
{
"code": null,
"e": 6747,
"s": 6663,
"text": "The core of the App/Service (grey, left-most box in Figure 1) is the snippet below:"
},
{
"code": null,
"e": 7177,
"s": 6747,
"text": "Note that we use the testing dataset to generate the messages. This is because we have designed an scenario that tries to resemble as much as possible the real world (within certain limits). With that in mind, we have used the training dataset to build the initial model and dataprocessor objects. We then use the test dataset to generate messages with the aim of simulating the process of receiving new information through time."
},
{
"code": null,
"e": 7719,
"s": 7177,
"text": "Regarding to the snippet above, simply, a producer will publish messages into the pipeline ( start_producing()) and will consume messages with the final prediction ( start_consuming()). The same way that the pipeline we describe here does not include the very beginning of the process (events collection and aggregation), we also skip the very end, i.e. what to do with the final prediction. Nonetheless, we briefly discuss some use cases where this pipeline could be useful towards the end of the post that will illustrate that final stage."
},
{
"code": null,
"e": 7990,
"s": 7719,
"text": "In reality, apart from ignoring the very beginning and end of the process we believe that this pipeline resembles reasonably well to one that could be used in the real world. In consequence, we hope that the code included in our repo is useful for some of your projects."
},
{
"code": null,
"e": 8012,
"s": 7990,
"text": "Predictor and Trainer"
},
{
"code": null,
"e": 8280,
"s": 8012,
"text": "The main goal of this implementation is running the algorithm in real time and retrain it every N observations without stopping the prediction service. To that aim we implemented two components, the Predictor ( predictor.py in the repo) and the Trainer ( trainer.py)."
},
{
"code": null,
"e": 8664,
"s": 8280,
"text": "Let’s now describe one by one the numbers shown in Figure 1, using code snippets as our guidelines. Note that the process below assumes one has run the initialize.py script, so an initial model.pand dataprocessor.pfiles exist in the corresponding directory. Also, emphasise that the code below comprises the core of the Predictor and the Trainer. For the full code refer to the repo."
},
{
"code": null,
"e": 8674,
"s": 8664,
"text": "Predictor"
},
{
"code": null,
"e": 8722,
"s": 8674,
"text": "The core of the Predictor’s code is shown below"
},
{
"code": null,
"e": 9013,
"s": 8722,
"text": "(1a) Line 12 in the predictor.py snippet. The Predictor will receive the message from the App/Service, it will do the data processing and run the model in real time as it receives the messages. All this happens using the existing dataprocessor and model objects within the predict function."
},
{
"code": null,
"e": 9205,
"s": 9013,
"text": "(1b) Line 13 in the predictor.pysnippet. Once we have run the prediction, the Predictor will publish the result ( publish_prediction()) that will be eventually be received by the App/Service."
},
{
"code": null,
"e": 9380,
"s": 9205,
"text": "(2 ) Lines 17–20 in the predictor.pysnippet. Every RETRAIN_EVERY messages, the Predictor will publish a “retrain” message ( send_retrain_message()) to be read by the Trainer."
},
{
"code": null,
"e": 9388,
"s": 9380,
"text": "Trainer"
},
{
"code": null,
"e": 9881,
"s": 9388,
"text": "(3) Line 12 in the trainer.py snippet. The Trainer will read the message and trigger a retraining process with the new, accumulated dataset ( train()) . This is, the original dataset plus RETRAIN_EVERYnew observations. The train function will run the entire process described in the “Initialising the experiment” section independently from the processes described in 1a and 1b. In other words, the Trainer will retrain a model while the Predictor keeps serving predictions as messages arrive."
},
{
"code": null,
"e": 10649,
"s": 9881,
"text": "At this stage it is worth mentioning that here we find a further difference between our implementation and one that would be used in the real world. In our implementation, it is possible to retrain the algorithm as soon as RETRAIN_EVERY number of observations have been processed. This is because we are using the Adult testing dataset to generate messages, which includes the target column (“income_braket”). In the real word the real outcome of the action taken based on the output of the algorithm would normally not be readily accessible just after the algorithm runs, but some time later. In that scenario, another process should be collecting the true outcome and, once the number of true outcomes collected equals RETRAIN_EVERY the algorithm will be retrained."
},
{
"code": null,
"e": 11195,
"s": 10649,
"text": "For example, let’s say that this pipeline implements a real-time recommendation system for an e-commerce. We have trained a recommendation algorithm offline and the target column is a categorical representation of how much our users like our recommendations: 0, 1, 2 and 3 for users that did not like or interacted with the item, liked the item (e.g. hit a like button), added the item to their basket, and bought the item respectively. By the time the system serves the recommendations we will still don’t know what will the user eventually do."
},
{
"code": null,
"e": 11501,
"s": 11195,
"text": "Therefore, along with a process collecting and storing the user information as they navigate the website (or app), a second process should collect what is the final outcome of our recommendation. Only when both processes have collected RETRAIN_EVERY messages and outcomes, the algorithm will be retrained."
},
{
"code": null,
"e": 11667,
"s": 11501,
"text": "(4) Line 13 in the trainer.py snippet. Once the retraining is done, a message with the corresponding information will be published ( published_training_completed())."
},
{
"code": null,
"e": 12005,
"s": 11667,
"text": "(5) Lines 5–8 in the predictor.py snippet. The Predictor’s consumer is subscribed to two topics: [‘app_messages’, ‘retrain_topic’]. Once it receives the information that the retraining is completed through the “retrain_topic” it will load the new model and keep with the process as usual, without stopping at any time during the process."
},
{
"code": null,
"e": 12121,
"s": 12005,
"text": "In the companion repo we have included instructions on how to run the pipeline (locally). Is actually quite simple."
},
{
"code": null,
"e": 12147,
"s": 12121,
"text": "Start zookeper and kafka:"
},
{
"code": null,
"e": 12173,
"s": 12147,
"text": "Start zookeper and kafka:"
},
{
"code": null,
"e": 12362,
"s": 12173,
"text": "$ brew services start zookeeper==> Successfully started `zookeeper` (label: homebrew.mxcl.zookeeper)$ brew services start kafka==> Successfully started `kafka` (label: homebrew.mxcl.kafka)"
},
{
"code": null,
"e": 12384,
"s": 12362,
"text": "2. Run initialize.py:"
},
{
"code": null,
"e": 12405,
"s": 12384,
"text": "python initialize.py"
},
{
"code": null,
"e": 12458,
"s": 12405,
"text": "3. In Terminal#1 run the Predictor (or the Trainer):"
},
{
"code": null,
"e": 12478,
"s": 12458,
"text": "python predictor.py"
},
{
"code": null,
"e": 12531,
"s": 12478,
"text": "4. In Terminal#2 run the Trainer (or the Predictor):"
},
{
"code": null,
"e": 12549,
"s": 12531,
"text": "python trainer.py"
},
{
"code": null,
"e": 12585,
"s": 12549,
"text": "5. In Terminal#3 run the Sample App"
},
{
"code": null,
"e": 12607,
"s": 12585,
"text": "python samplea_app.py"
},
{
"code": null,
"e": 12695,
"s": 12607,
"text": "Then, once N number of messages have been processed you should see something like this:"
},
{
"code": null,
"e": 13062,
"s": 12695,
"text": "Upper right terminal: we have retrained the model and Hyperopt has run 10 evaluations (in a real exercise these should be a few hundred). Upper left terminal: once the model is retrained and optimised we see how the predictor has loaded the new model (after the annoying warning message from the new LightGBM version). Bottom terminal: the service proceeds as usual."
},
{
"code": null,
"e": 13125,
"s": 13062,
"text": "Here are a couple of potential use cases, among (many) others."
},
{
"code": null,
"e": 13163,
"s": 13125,
"text": "Adapting online journeys in real time"
},
{
"code": null,
"e": 13201,
"s": 13163,
"text": "Adapting online journeys in real time"
},
{
"code": null,
"e": 13812,
"s": 13201,
"text": "Let’s consider an e-commerce selling some items. As users navigate through the website we collect events with information on their actions. We have previously trained an algorithm and we know that after, let’s say, 10 interactions, we are in a good position to know whether a customer will end up buying our products. Moreover, we also know that the products they will potentially buy will possibly be expensive. Therefore, we would like to customise their journey “on-the-go” to facilitate their shopping experience. Customisation here can mean anything, from shortening the journey to change the page layout."
},
{
"code": null,
"e": 13841,
"s": 13812,
"text": "2. Email/call your customers"
},
{
"code": null,
"e": 14191,
"s": 13841,
"text": "Similarly to the use-case before, let’s assume now that the customer decides to stop the journey (bored, lack of time, maybe too complex, etc). We could use a pipeline like the one described in this post to either immediately, or with a controlled delay, send an email or call them if the algorithm predicts that this customer is of great potential."
},
{
"code": null,
"e": 15013,
"s": 14191,
"text": "Loggings and monitoring: in an upcoming post we will insert in the pipeline loggings and monitoring functionalities via MLFlow. Along with HyperparameterHunter, this solution will automatically keep full track of both model performance and hyperparameter optimization, while offering visual monitoring.Flow management: the solution described here, and the corresponding code, has been designed so it can easily run in a laptop, locally. However, one would assume that in real life this will have to run the cloud, at scale. This specific part will not be covered in the two posts. However, I can assure you that moving the structure described here to AWS (for example) and run it automatically at your convenience (using EC2s, S3 and whatever the front end has to be for your particular case) is not particularly complex."
},
{
"code": null,
"e": 15316,
"s": 15013,
"text": "Loggings and monitoring: in an upcoming post we will insert in the pipeline loggings and monitoring functionalities via MLFlow. Along with HyperparameterHunter, this solution will automatically keep full track of both model performance and hyperparameter optimization, while offering visual monitoring."
},
{
"code": null,
"e": 15836,
"s": 15316,
"text": "Flow management: the solution described here, and the corresponding code, has been designed so it can easily run in a laptop, locally. However, one would assume that in real life this will have to run the cloud, at scale. This specific part will not be covered in the two posts. However, I can assure you that moving the structure described here to AWS (for example) and run it automatically at your convenience (using EC2s, S3 and whatever the front end has to be for your particular case) is not particularly complex."
}
] |
Build Log Analytics Application using Apache Spark | by Raman Ahuja | Towards Data Science | Step by step process of developing a real world application using Apache Spark, along with main focus on explaining the architecture of Spark.
Why Apache Spark Architecture if we have Hadoop?
The Hadoop Distributed File System (HDFS), which stores files in a Hadoop-native format and parallelizes them across a cluster, and applies MapReduce the algorithm that actually processes the data in parallel. The catch here is Data Nodes are stored on disk and processing has to happen in Memory. Thus we need to do lot of I/O operations to process and also Network transfer operations happen to transfer data across the data nodes. These operations in all may be a hindrance for faster processing of data.
Above Image describes, blocks are stored on data notes which reside on disk and for Map operation or other processing has to happen in RAM. This requires to and fro I/O Operation which causes a delay in overall result.
Apache Spark: Official website describes it as : “Apache Spark is a fast and general-purpose cluster computing system”.
Fast: Apache spark is fast because computations are carried out in memory and stored there. Thus there is no picture of I/O operations as discussed in Hadoop architecture.
General-Purpose: It is an optimized engine that supports general execution graphs. It also supports a rich SQL and structured data processing, MLlib for machine learning, GraphX for graph processing, and Spark Streaming for live data processing.
Entry point to Spark is Spark Context which handles the executors nodes. The main abstraction data structure of Spark is Resilient Distributed Dataset (RDD), which represents an immutable collection of elements that can be operated on in parallel.
Lets discuss the above example to understand better: A file consists of numbers, task is find the prime numbers from this huge chunk of numbers. If we divide them into three blocks B1,B2,B3. These blocks are immutable are stored in Memory by spark. Here the replication factor=2, thus we can see that a copy of other node is stored in corresponding other partitions. This makes it to have a fault-tolerant architecture.
Step 1 : Create RDD using Spark Context
Step 2 : Tranformation: When a map() operation is applied on these RDD, new blocks i.e B4, B5, B6 get created as new RDD’s which are immutable again. This all operations happen in Memory. Note: B1,B2,B3 still exist as original.
Step 3: Action: When collect(), this when the actual results are collected and returned.
LAZY EVALUATION: Spark does not evaluate each transformation right away, but instead batch them together and evaluate all at once. At its core, it optimizes the query execution by planning out the sequence of computation and skipping potentially unnecessary steps. Main Advantages : Increases Manageability, Saves Computation and increases Speed, Reduces Complexities, Optimization.
How it works ? When it we execute the code to create Spark Context, then create RDD using sc, then perform tranformation using map to create new RDD. In actual these operations are not executed in backend, rather a Directed Acyclic Graph(DAG) Lineage is created. Only when the action is performed i.e. to fetch results, example : collect() operation is called then it refers to DAG and climbs up to get the results, refer the figure, as climbing up it sees that filter RDD is not yet created, it climbs up to get upper results and finally reverse calculates to get the exact results.
RDD — Resilient : i.e. fault-tolerant with the help of RDD lineage graph. RDD’s are a deterministic function of their input. This plus immutability also means the RDD’s parts can be recreated at any time. This makes caching, sharing and replication easy.
Distributed : Data resides on multiple nodes.
Datasets : Represents records of the data you work with. The user can load the data set externally which can be either JSON file, CSV file, text file or database via JDBC with no specific data structure.
In part of article we will create a Apache Access Log Analytics Application from scratch using pyspark and SQL functionality of Apache Spark. Python3 and latest version of pyspark. Data Source: ApacheAccessLog
Prerequisite Libraries
pip install pysparkpip install matplotlibpip install numpy
Step 1 : As the Log Data is unstructured, we parse and create a structure from each line, which will in turn become each row while analysis.
Step 2: Create Spark Context, SQL Context, DataFrame( is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database)
Step 3 : Analyze Top 10 Endpoints which Transfer Maximum Content in MB
Outliers can be clearly detected by analysis the spikes and which end points were been hit at time by what IP Addresses.
Here, we can see an unusual spike on 8th March, which can be analyzed further for identifying discrepancy.
Code for Plot Analysis:
To get the full application code: https://github.com/ahujaraman/live_log_analyzer_spark | [
{
"code": null,
"e": 315,
"s": 172,
"text": "Step by step process of developing a real world application using Apache Spark, along with main focus on explaining the architecture of Spark."
},
{
"code": null,
"e": 364,
"s": 315,
"text": "Why Apache Spark Architecture if we have Hadoop?"
},
{
"code": null,
"e": 872,
"s": 364,
"text": "The Hadoop Distributed File System (HDFS), which stores files in a Hadoop-native format and parallelizes them across a cluster, and applies MapReduce the algorithm that actually processes the data in parallel. The catch here is Data Nodes are stored on disk and processing has to happen in Memory. Thus we need to do lot of I/O operations to process and also Network transfer operations happen to transfer data across the data nodes. These operations in all may be a hindrance for faster processing of data."
},
{
"code": null,
"e": 1091,
"s": 872,
"text": "Above Image describes, blocks are stored on data notes which reside on disk and for Map operation or other processing has to happen in RAM. This requires to and fro I/O Operation which causes a delay in overall result."
},
{
"code": null,
"e": 1211,
"s": 1091,
"text": "Apache Spark: Official website describes it as : “Apache Spark is a fast and general-purpose cluster computing system”."
},
{
"code": null,
"e": 1383,
"s": 1211,
"text": "Fast: Apache spark is fast because computations are carried out in memory and stored there. Thus there is no picture of I/O operations as discussed in Hadoop architecture."
},
{
"code": null,
"e": 1629,
"s": 1383,
"text": "General-Purpose: It is an optimized engine that supports general execution graphs. It also supports a rich SQL and structured data processing, MLlib for machine learning, GraphX for graph processing, and Spark Streaming for live data processing."
},
{
"code": null,
"e": 1877,
"s": 1629,
"text": "Entry point to Spark is Spark Context which handles the executors nodes. The main abstraction data structure of Spark is Resilient Distributed Dataset (RDD), which represents an immutable collection of elements that can be operated on in parallel."
},
{
"code": null,
"e": 2297,
"s": 1877,
"text": "Lets discuss the above example to understand better: A file consists of numbers, task is find the prime numbers from this huge chunk of numbers. If we divide them into three blocks B1,B2,B3. These blocks are immutable are stored in Memory by spark. Here the replication factor=2, thus we can see that a copy of other node is stored in corresponding other partitions. This makes it to have a fault-tolerant architecture."
},
{
"code": null,
"e": 2337,
"s": 2297,
"text": "Step 1 : Create RDD using Spark Context"
},
{
"code": null,
"e": 2565,
"s": 2337,
"text": "Step 2 : Tranformation: When a map() operation is applied on these RDD, new blocks i.e B4, B5, B6 get created as new RDD’s which are immutable again. This all operations happen in Memory. Note: B1,B2,B3 still exist as original."
},
{
"code": null,
"e": 2654,
"s": 2565,
"text": "Step 3: Action: When collect(), this when the actual results are collected and returned."
},
{
"code": null,
"e": 3037,
"s": 2654,
"text": "LAZY EVALUATION: Spark does not evaluate each transformation right away, but instead batch them together and evaluate all at once. At its core, it optimizes the query execution by planning out the sequence of computation and skipping potentially unnecessary steps. Main Advantages : Increases Manageability, Saves Computation and increases Speed, Reduces Complexities, Optimization."
},
{
"code": null,
"e": 3621,
"s": 3037,
"text": "How it works ? When it we execute the code to create Spark Context, then create RDD using sc, then perform tranformation using map to create new RDD. In actual these operations are not executed in backend, rather a Directed Acyclic Graph(DAG) Lineage is created. Only when the action is performed i.e. to fetch results, example : collect() operation is called then it refers to DAG and climbs up to get the results, refer the figure, as climbing up it sees that filter RDD is not yet created, it climbs up to get upper results and finally reverse calculates to get the exact results."
},
{
"code": null,
"e": 3876,
"s": 3621,
"text": "RDD — Resilient : i.e. fault-tolerant with the help of RDD lineage graph. RDD’s are a deterministic function of their input. This plus immutability also means the RDD’s parts can be recreated at any time. This makes caching, sharing and replication easy."
},
{
"code": null,
"e": 3922,
"s": 3876,
"text": "Distributed : Data resides on multiple nodes."
},
{
"code": null,
"e": 4126,
"s": 3922,
"text": "Datasets : Represents records of the data you work with. The user can load the data set externally which can be either JSON file, CSV file, text file or database via JDBC with no specific data structure."
},
{
"code": null,
"e": 4336,
"s": 4126,
"text": "In part of article we will create a Apache Access Log Analytics Application from scratch using pyspark and SQL functionality of Apache Spark. Python3 and latest version of pyspark. Data Source: ApacheAccessLog"
},
{
"code": null,
"e": 4359,
"s": 4336,
"text": "Prerequisite Libraries"
},
{
"code": null,
"e": 4418,
"s": 4359,
"text": "pip install pysparkpip install matplotlibpip install numpy"
},
{
"code": null,
"e": 4559,
"s": 4418,
"text": "Step 1 : As the Log Data is unstructured, we parse and create a structure from each line, which will in turn become each row while analysis."
},
{
"code": null,
"e": 4746,
"s": 4559,
"text": "Step 2: Create Spark Context, SQL Context, DataFrame( is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database)"
},
{
"code": null,
"e": 4817,
"s": 4746,
"text": "Step 3 : Analyze Top 10 Endpoints which Transfer Maximum Content in MB"
},
{
"code": null,
"e": 4938,
"s": 4817,
"text": "Outliers can be clearly detected by analysis the spikes and which end points were been hit at time by what IP Addresses."
},
{
"code": null,
"e": 5045,
"s": 4938,
"text": "Here, we can see an unusual spike on 8th March, which can be analyzed further for identifying discrepancy."
},
{
"code": null,
"e": 5069,
"s": 5045,
"text": "Code for Plot Analysis:"
}
] |
How to Create Query Parameters in JavaScript ? - GeeksforGeeks | 18 Mar, 2020
The task is to create a query URL for GET request given a JSON object using javaScript. GET query parameters in an URL are just a string of key-value pairs connected with the symbol &. To convert a JSON object into a GET query parameter we can use the following approach.
Make a variable query.
Loop through all the keys and values of the json and attach them together with ‘&’ symbol.
Examples:
Input: {'website':'geeks', 'location':'india'}
Output: website=geeks&location=india
Syntax:
function encodeQuery(data){
let query = ""
for (let d in data)
query += encodeURIComponent(d) + '=' +
encodeURIComponent(data[d]) + '&'
return query.slice(0, -1)
}
Below examples implements the above approach:
Example 1:
<script>function encodeQuery(data){ let query = "" for (let d in data) query += encodeURIComponent(d) + '=' + encodeURIComponent(data[d]) + '&' return query.slice(0, -1)} // Json object that should be// converted to query parameterdata = { 'website':'geeks', 'location':'india'}queryParam = encodeQuery(data)console.log(queryParam)</script>
Output:
website=geeks&location=india
Example 2: In this example, we will create a complete URL from the given JSON data.
<script>function encodeQuery(data){ let query = data.url for (let d in data.params) query += encodeURIComponent(d) + '=' + encodeURIComponent(data.params[d]) + '&'; return query.slice(0, -1)} // Json object that should be// converted to query parameterdata = { url : 'www.geeksforgeeks.com/', params : { 'website':'geeks', 'location':'india' }}queryParam = encodeQuery(data)console.log(queryParam)</script>
Output:
www.geeksforgeeks.com/website=geeks&location=india
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n18 Mar, 2020"
},
{
"code": null,
"e": 25257,
"s": 24985,
"text": "The task is to create a query URL for GET request given a JSON object using javaScript. GET query parameters in an URL are just a string of key-value pairs connected with the symbol &. To convert a JSON object into a GET query parameter we can use the following approach."
},
{
"code": null,
"e": 25280,
"s": 25257,
"text": "Make a variable query."
},
{
"code": null,
"e": 25371,
"s": 25280,
"text": "Loop through all the keys and values of the json and attach them together with ‘&’ symbol."
},
{
"code": null,
"e": 25381,
"s": 25371,
"text": "Examples:"
},
{
"code": null,
"e": 25465,
"s": 25381,
"text": "Input: {'website':'geeks', 'location':'india'}\nOutput: website=geeks&location=india"
},
{
"code": null,
"e": 25473,
"s": 25465,
"text": "Syntax:"
},
{
"code": null,
"e": 25671,
"s": 25473,
"text": "function encodeQuery(data){\n let query = \"\"\n for (let d in data)\n query += encodeURIComponent(d) + '=' + \n encodeURIComponent(data[d]) + '&'\n return query.slice(0, -1)\n}"
},
{
"code": null,
"e": 25717,
"s": 25671,
"text": "Below examples implements the above approach:"
},
{
"code": null,
"e": 25728,
"s": 25717,
"text": "Example 1:"
},
{
"code": "<script>function encodeQuery(data){ let query = \"\" for (let d in data) query += encodeURIComponent(d) + '=' + encodeURIComponent(data[d]) + '&' return query.slice(0, -1)} // Json object that should be// converted to query parameterdata = { 'website':'geeks', 'location':'india'}queryParam = encodeQuery(data)console.log(queryParam)</script>",
"e": 26112,
"s": 25728,
"text": null
},
{
"code": null,
"e": 26120,
"s": 26112,
"text": "Output:"
},
{
"code": null,
"e": 26149,
"s": 26120,
"text": "website=geeks&location=india"
},
{
"code": null,
"e": 26233,
"s": 26149,
"text": "Example 2: In this example, we will create a complete URL from the given JSON data."
},
{
"code": "<script>function encodeQuery(data){ let query = data.url for (let d in data.params) query += encodeURIComponent(d) + '=' + encodeURIComponent(data.params[d]) + '&'; return query.slice(0, -1)} // Json object that should be// converted to query parameterdata = { url : 'www.geeksforgeeks.com/', params : { 'website':'geeks', 'location':'india' }}queryParam = encodeQuery(data)console.log(queryParam)</script>",
"e": 26695,
"s": 26233,
"text": null
},
{
"code": null,
"e": 26703,
"s": 26695,
"text": "Output:"
},
{
"code": null,
"e": 26754,
"s": 26703,
"text": "www.geeksforgeeks.com/website=geeks&location=india"
},
{
"code": null,
"e": 26770,
"s": 26754,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 26777,
"s": 26770,
"text": "Picked"
},
{
"code": null,
"e": 26788,
"s": 26777,
"text": "JavaScript"
},
{
"code": null,
"e": 26805,
"s": 26788,
"text": "Web Technologies"
},
{
"code": null,
"e": 26832,
"s": 26805,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26930,
"s": 26832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26939,
"s": 26930,
"text": "Comments"
},
{
"code": null,
"e": 26952,
"s": 26939,
"text": "Old Comments"
},
{
"code": null,
"e": 27013,
"s": 26952,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27058,
"s": 27013,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27130,
"s": 27058,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27182,
"s": 27130,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27228,
"s": 27182,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27284,
"s": 27228,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27317,
"s": 27284,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27379,
"s": 27317,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27422,
"s": 27379,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML | DOM Window opener Properties - GeeksforGeeks | 26 Jul, 2019
The Window opener property in HTML DOM is used to return the reference of newly created windows. This property is used to return the details of the source (parent) window. A window is opened using the window.open() method and closed using the window.opener.close() method.
Syntax:
window.opener
Return Value: It returns the reference of created window.
Example 1:
<!DOCTYPE html><html> <head> <title> HTML DOM Window opener Property </title></head> <body> <h2> HTML DOM Window opener Property </h2> <button onclick = "myGeeks()"> Click Here! </button> <!-- script to open new windows --> <script> function myGeeks() { var win = window.open("", "win", "width = 500, height = 300"); win.document.write("<p>New Window</p>"); win.opener.document.write("<p>Parent Window</p>"); } </script></body> </html>
Output:Before click on the button:After click on the button:
Example 2:
<!DOCTYPE html><html> <head> <title> HTML DOM Window opener Property </title></head> <body> <h2> HTML DOM Window opener Property </h2> <button onclick = "myGeeks()"> Click Here! </button> <!-- script to create two window --> <script> function myGeeks() { var win1 = window.open("", "win1", "width = 500, height = 300"); var win2 = window.open("", "win2", "width = 400, height = 250"); win1.document.write("<p>New Window 1</p>"); win2.document.write("<p>New Window 2</p>"); win1.opener.document.write("<p>Parent Window</p>"); win2.opener.document.write("<p>Parent Window</p>"); } </script></body> </html>
Output:Before click on the button:After click on the button:
Supported Browsers: The browser supported by DOM Window opener property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25357,
"s": 25329,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 25630,
"s": 25357,
"text": "The Window opener property in HTML DOM is used to return the reference of newly created windows. This property is used to return the details of the source (parent) window. A window is opened using the window.open() method and closed using the window.opener.close() method."
},
{
"code": null,
"e": 25638,
"s": 25630,
"text": "Syntax:"
},
{
"code": null,
"e": 25652,
"s": 25638,
"text": "window.opener"
},
{
"code": null,
"e": 25710,
"s": 25652,
"text": "Return Value: It returns the reference of created window."
},
{
"code": null,
"e": 25721,
"s": 25710,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Window opener Property </title></head> <body> <h2> HTML DOM Window opener Property </h2> <button onclick = \"myGeeks()\"> Click Here! </button> <!-- script to open new windows --> <script> function myGeeks() { var win = window.open(\"\", \"win\", \"width = 500, height = 300\"); win.document.write(\"<p>New Window</p>\"); win.opener.document.write(\"<p>Parent Window</p>\"); } </script></body> </html> ",
"e": 26372,
"s": 25721,
"text": null
},
{
"code": null,
"e": 26433,
"s": 26372,
"text": "Output:Before click on the button:After click on the button:"
},
{
"code": null,
"e": 26444,
"s": 26433,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Window opener Property </title></head> <body> <h2> HTML DOM Window opener Property </h2> <button onclick = \"myGeeks()\"> Click Here! </button> <!-- script to create two window --> <script> function myGeeks() { var win1 = window.open(\"\", \"win1\", \"width = 500, height = 300\"); var win2 = window.open(\"\", \"win2\", \"width = 400, height = 250\"); win1.document.write(\"<p>New Window 1</p>\"); win2.document.write(\"<p>New Window 2</p>\"); win1.opener.document.write(\"<p>Parent Window</p>\"); win2.opener.document.write(\"<p>Parent Window</p>\"); } </script></body> </html> ",
"e": 27318,
"s": 26444,
"text": null
},
{
"code": null,
"e": 27379,
"s": 27318,
"text": "Output:Before click on the button:After click on the button:"
},
{
"code": null,
"e": 27469,
"s": 27379,
"text": "Supported Browsers: The browser supported by DOM Window opener property are listed below:"
},
{
"code": null,
"e": 27483,
"s": 27469,
"text": "Google Chrome"
},
{
"code": null,
"e": 27501,
"s": 27483,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27509,
"s": 27501,
"text": "Firefox"
},
{
"code": null,
"e": 27515,
"s": 27509,
"text": "Opera"
},
{
"code": null,
"e": 27522,
"s": 27515,
"text": "Safari"
},
{
"code": null,
"e": 27659,
"s": 27522,
"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": 27668,
"s": 27659,
"text": "HTML-DOM"
},
{
"code": null,
"e": 27675,
"s": 27668,
"text": "Picked"
},
{
"code": null,
"e": 27680,
"s": 27675,
"text": "HTML"
},
{
"code": null,
"e": 27697,
"s": 27680,
"text": "Web Technologies"
},
{
"code": null,
"e": 27702,
"s": 27697,
"text": "HTML"
},
{
"code": null,
"e": 27800,
"s": 27702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27850,
"s": 27800,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27912,
"s": 27850,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27960,
"s": 27912,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28020,
"s": 27960,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28073,
"s": 28020,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28113,
"s": 28073,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28146,
"s": 28113,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28191,
"s": 28146,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28234,
"s": 28191,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
PostgreSQL - Copy a Table - GeeksforGeeks | 24 Jan, 2021
This article will be focusing on copying an existing table to a new table in PostgreSQL. This might come in handy while creating new tables that would either have the same data or data of the same table with certain operations performed on them.
We will discuss the following 3 cases:
Copy Table with the same structure and data.Copy Table with the same structure and no data.Copy Table with the same structure and partial data.
Copy Table with the same structure and data.
Copy Table with the same structure and no data.
Copy Table with the same structure and partial data.
To copy a table with all its structure and data, use the following query:
Syntax:
CREATE TABLE new_table AS TABLE old_table;
Example:
Let’s add a table with columns id, first_name, last_name, and email to the database:
CREATE TABLE students(
id SERIAL PRIMARY KEY,
first_name VARCHAR,
last_name VARCHAR,
email VARCHAR UNIQUE
);
Let’s insert some data into our students table:
INSERT INTO students(first_name, last_name, email)
VALUES('Virender', 'Sehwag', '[email protected]'),
('Hardik', 'Pandiya', '[email protected]');
Now check the data in the table:
SELECT * FROM students;
If everything works fine, the output will as below:
Now copy the students table to a new table named copy_students table.
CREATE TABLE copy_students AS TABLE students;
The above query will create a new table named copy_students with the same structure and data as the students table.
Now check the data of the copy_students table:
SELECT * FROM copy_students;
Output:
WITH NO DATA clause is used to copy a table structure without the data using the below query:
Syntax:
CREATE TABLE new_table AS TABLE old_table WITH NO DATA;
Example:
Let’s use the students table that we created before:
CREATE TABLE without_data_students AS TABLE students WITH NO DATA;
Execute the above query to get the table without_data_students with the same structure as students with no data.
SELECT * FROM without_data_students;
Output:
The below query can be used to copy a table according to a specified condition:
Syntax:
CREATE TABLE new_table AS TABLE old_table WHERE condition;
Example:
Let’s insert some more rows into the students table:
INSERT INTO students(first_name, last_name, email)
VALUES('Shreyas', 'Iyer', '[email protected]'),
('Rishabh', 'Pant', '[email protected]');
Now the students table will have the following data:
SELECT * FROM students;
Now the students table will look like this:
Let’s create a table copy_partial_students with id 1 and 3 only:
CREATE TABLE copy_partial_students AS SELECT * FROM students WHERE id IN (1, 3);
Instead of *, you can also define the column names that you want to copy. The result table columns will have the names and data types as same as the output columns of the SELECT clause.
Now check the data of the copy_partial_students table:
SELECT * FROM copy_partial_students;
Output:
Picked
postgreSQL-basics
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - Function Returning A Table
PostgreSQL - Interval Data Type
PostgreSQL - For Loops
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Copy Table | [
{
"code": null,
"e": 28000,
"s": 27972,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 28246,
"s": 28000,
"text": "This article will be focusing on copying an existing table to a new table in PostgreSQL. This might come in handy while creating new tables that would either have the same data or data of the same table with certain operations performed on them."
},
{
"code": null,
"e": 28285,
"s": 28246,
"text": "We will discuss the following 3 cases:"
},
{
"code": null,
"e": 28429,
"s": 28285,
"text": "Copy Table with the same structure and data.Copy Table with the same structure and no data.Copy Table with the same structure and partial data."
},
{
"code": null,
"e": 28474,
"s": 28429,
"text": "Copy Table with the same structure and data."
},
{
"code": null,
"e": 28522,
"s": 28474,
"text": "Copy Table with the same structure and no data."
},
{
"code": null,
"e": 28575,
"s": 28522,
"text": "Copy Table with the same structure and partial data."
},
{
"code": null,
"e": 28649,
"s": 28575,
"text": "To copy a table with all its structure and data, use the following query:"
},
{
"code": null,
"e": 28700,
"s": 28649,
"text": "Syntax:\nCREATE TABLE new_table AS TABLE old_table;"
},
{
"code": null,
"e": 28709,
"s": 28700,
"text": "Example:"
},
{
"code": null,
"e": 28794,
"s": 28709,
"text": "Let’s add a table with columns id, first_name, last_name, and email to the database:"
},
{
"code": null,
"e": 28915,
"s": 28794,
"text": "CREATE TABLE students(\n id SERIAL PRIMARY KEY,\n first_name VARCHAR,\n last_name VARCHAR,\n email VARCHAR UNIQUE\n);"
},
{
"code": null,
"e": 28963,
"s": 28915,
"text": "Let’s insert some data into our students table:"
},
{
"code": null,
"e": 29124,
"s": 28963,
"text": "INSERT INTO students(first_name, last_name, email)\nVALUES('Virender', 'Sehwag', '[email protected]'),\n ('Hardik', 'Pandiya', '[email protected]');"
},
{
"code": null,
"e": 29157,
"s": 29124,
"text": "Now check the data in the table:"
},
{
"code": null,
"e": 29181,
"s": 29157,
"text": "SELECT * FROM students;"
},
{
"code": null,
"e": 29233,
"s": 29181,
"text": "If everything works fine, the output will as below:"
},
{
"code": null,
"e": 29303,
"s": 29233,
"text": "Now copy the students table to a new table named copy_students table."
},
{
"code": null,
"e": 29349,
"s": 29303,
"text": "CREATE TABLE copy_students AS TABLE students;"
},
{
"code": null,
"e": 29465,
"s": 29349,
"text": "The above query will create a new table named copy_students with the same structure and data as the students table."
},
{
"code": null,
"e": 29512,
"s": 29465,
"text": "Now check the data of the copy_students table:"
},
{
"code": null,
"e": 29541,
"s": 29512,
"text": "SELECT * FROM copy_students;"
},
{
"code": null,
"e": 29549,
"s": 29541,
"text": "Output:"
},
{
"code": null,
"e": 29643,
"s": 29549,
"text": "WITH NO DATA clause is used to copy a table structure without the data using the below query:"
},
{
"code": null,
"e": 29707,
"s": 29643,
"text": "Syntax:\nCREATE TABLE new_table AS TABLE old_table WITH NO DATA;"
},
{
"code": null,
"e": 29716,
"s": 29707,
"text": "Example:"
},
{
"code": null,
"e": 29769,
"s": 29716,
"text": "Let’s use the students table that we created before:"
},
{
"code": null,
"e": 29836,
"s": 29769,
"text": "CREATE TABLE without_data_students AS TABLE students WITH NO DATA;"
},
{
"code": null,
"e": 29949,
"s": 29836,
"text": "Execute the above query to get the table without_data_students with the same structure as students with no data."
},
{
"code": null,
"e": 29986,
"s": 29949,
"text": "SELECT * FROM without_data_students;"
},
{
"code": null,
"e": 29994,
"s": 29986,
"text": "Output:"
},
{
"code": null,
"e": 30074,
"s": 29994,
"text": "The below query can be used to copy a table according to a specified condition:"
},
{
"code": null,
"e": 30141,
"s": 30074,
"text": "Syntax:\nCREATE TABLE new_table AS TABLE old_table WHERE condition;"
},
{
"code": null,
"e": 30151,
"s": 30141,
"text": "Example: "
},
{
"code": null,
"e": 30204,
"s": 30151,
"text": "Let’s insert some more rows into the students table:"
},
{
"code": null,
"e": 30355,
"s": 30204,
"text": "INSERT INTO students(first_name, last_name, email)\nVALUES('Shreyas', 'Iyer', '[email protected]'),\n ('Rishabh', 'Pant', '[email protected]');"
},
{
"code": null,
"e": 30408,
"s": 30355,
"text": "Now the students table will have the following data:"
},
{
"code": null,
"e": 30432,
"s": 30408,
"text": "SELECT * FROM students;"
},
{
"code": null,
"e": 30476,
"s": 30432,
"text": "Now the students table will look like this:"
},
{
"code": null,
"e": 30541,
"s": 30476,
"text": "Let’s create a table copy_partial_students with id 1 and 3 only:"
},
{
"code": null,
"e": 30623,
"s": 30541,
"text": "CREATE TABLE copy_partial_students AS SELECT * FROM students WHERE id IN (1, 3);"
},
{
"code": null,
"e": 30810,
"s": 30623,
"text": "Instead of *, you can also define the column names that you want to copy. The result table columns will have the names and data types as same as the output columns of the SELECT clause."
},
{
"code": null,
"e": 30865,
"s": 30810,
"text": "Now check the data of the copy_partial_students table:"
},
{
"code": null,
"e": 30902,
"s": 30865,
"text": "SELECT * FROM copy_partial_students;"
},
{
"code": null,
"e": 30910,
"s": 30902,
"text": "Output:"
},
{
"code": null,
"e": 30917,
"s": 30910,
"text": "Picked"
},
{
"code": null,
"e": 30935,
"s": 30917,
"text": "postgreSQL-basics"
},
{
"code": null,
"e": 30946,
"s": 30935,
"text": "PostgreSQL"
},
{
"code": null,
"e": 31044,
"s": 30946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31053,
"s": 31044,
"text": "Comments"
},
{
"code": null,
"e": 31066,
"s": 31053,
"text": "Old Comments"
},
{
"code": null,
"e": 31098,
"s": 31066,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 31125,
"s": 31098,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 31165,
"s": 31125,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 31197,
"s": 31165,
"text": "PostgreSQL - Interval Data Type"
},
{
"code": null,
"e": 31220,
"s": 31197,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 31275,
"s": 31220,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 31309,
"s": 31275,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 31333,
"s": 31309,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 31366,
"s": 31333,
"text": "PostgreSQL - ROW_NUMBER Function"
}
] |
Get super class of an object in Java | The immediate superclass of any entity such as an object, class, primitive type, interface etc. can be obtained using the method java.lang.Class.getSuperclass(). This method contains no parameters.
A program that demonstrates this is given as follows −
Live Demo
public class Main {
public static void main(String[] args) {
Object obj1 = new String("Hello");
Object obj2 = new Integer(15);
Class c1 = obj1.getClass().getSuperclass();
System.out.println("Super Class = " + c1);
Class c2 = obj2.getClass().getSuperclass();
System.out.println("Super Class = " + c2);
}
}
Super Class = class java.lang.Object
Super Class = class java.lang.Number
Now let us understand the above program.
In the method main(), getClass() is used to obtain the class and getSuperclass() is used to obtain the super class of objects obj1 and obj2. Then the super class is printed. A code snippet which demonstrates this is as follows −
Object obj1 = new String("Hello");
Object obj2 = new Integer(15);
Class c1 = obj1.getClass().getSuperclass();
System.out.println("Super Class = " + c1);
Class c2 = obj2.getClass().getSuperclass();
System.out.println("Super Class = " + c2); | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "The immediate superclass of any entity such as an object, class, primitive type, interface etc. can be obtained using the method java.lang.Class.getSuperclass(). This method contains no parameters."
},
{
"code": null,
"e": 1315,
"s": 1260,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": " Live Demo"
},
{
"code": null,
"e": 1673,
"s": 1326,
"text": "public class Main {\n public static void main(String[] args) {\n Object obj1 = new String(\"Hello\");\n Object obj2 = new Integer(15);\n Class c1 = obj1.getClass().getSuperclass();\n System.out.println(\"Super Class = \" + c1);\n Class c2 = obj2.getClass().getSuperclass();\n System.out.println(\"Super Class = \" + c2);\n }\n}"
},
{
"code": null,
"e": 1747,
"s": 1673,
"text": "Super Class = class java.lang.Object\nSuper Class = class java.lang.Number"
},
{
"code": null,
"e": 1788,
"s": 1747,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2017,
"s": 1788,
"text": "In the method main(), getClass() is used to obtain the class and getSuperclass() is used to obtain the super class of objects obj1 and obj2. Then the super class is printed. A code snippet which demonstrates this is as follows −"
},
{
"code": null,
"e": 2257,
"s": 2017,
"text": "Object obj1 = new String(\"Hello\");\nObject obj2 = new Integer(15);\nClass c1 = obj1.getClass().getSuperclass();\nSystem.out.println(\"Super Class = \" + c1);\nClass c2 = obj2.getClass().getSuperclass();\nSystem.out.println(\"Super Class = \" + c2);"
}
] |
Java program to swap first and last characters of words in a sentence | Following is the Java program to swap first and last characters of word in a sentence −
Live Demo
public class Demo {
static String swap_chars(String my_str) {
char[] my_ch = my_str.toCharArray();
for (int i = 0; i < my_ch.length; i++) {
int k = i;
while (i < my_ch.length && my_ch[i] != ' ')
i++;
char temp = my_ch[k];
my_ch[k] = my_ch[i - 1];
my_ch[i - 1] = temp;
}
return new String(my_ch);
}
public static void main(String[] args) {
String my_str = "Thas is a sample";
System.out.println("The string after swapping the last characters of every word is : ");
System.out.println(swap_chars(my_str));
}
}
The string after swapping the last characters of every word is :
shaT si a eampls
A class named Demo contains a function named ‘swap_chars’ which returns a string as output. In this function, the string is converted to a character array. The character array is iterated over, and if the next element in the word is not a space, the first and the last elements are swapped, and this string is returned as output of the function. The same is repeated for all words in a sentence. In the main function, the string is defined, and the function is called by passing this string as a parameter to it. | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "Following is the Java program to swap first and last characters of word in a sentence −"
},
{
"code": null,
"e": 1161,
"s": 1150,
"text": " Live Demo"
},
{
"code": null,
"e": 1789,
"s": 1161,
"text": "public class Demo {\n static String swap_chars(String my_str) {\n char[] my_ch = my_str.toCharArray();\n for (int i = 0; i < my_ch.length; i++) {\n int k = i;\n while (i < my_ch.length && my_ch[i] != ' ')\n i++;\n char temp = my_ch[k];\n my_ch[k] = my_ch[i - 1];\n my_ch[i - 1] = temp;\n }\n return new String(my_ch);\n }\n public static void main(String[] args) {\n String my_str = \"Thas is a sample\";\n System.out.println(\"The string after swapping the last characters of every word is : \");\n System.out.println(swap_chars(my_str));\n }\n}"
},
{
"code": null,
"e": 1871,
"s": 1789,
"text": "The string after swapping the last characters of every word is :\nshaT si a eampls"
},
{
"code": null,
"e": 2384,
"s": 1871,
"text": "A class named Demo contains a function named ‘swap_chars’ which returns a string as output. In this function, the string is converted to a character array. The character array is iterated over, and if the next element in the word is not a space, the first and the last elements are swapped, and this string is returned as output of the function. The same is repeated for all words in a sentence. In the main function, the string is defined, and the function is called by passing this string as a parameter to it."
}
] |
Single Number in Python | Suppose we have an array A. In this array there are many numbers that occur twice. Only one element can be found a single time. We have to find that element from that array. Suppose A = [1, 1, 5, 3, 2, 5, 2], then the output will be 3. As there is each number twice, we can perform XOR to cancel out that element. because we know y XOR y = 0
To solve this, we will follow these steps.
Take one variable res = 0
for each element e in array A, preform res = res XOR e
return res
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = nums[0]
for i in range(1,len(nums)):
ans ^=nums[i]
return ans
ob1 = Solution()
print(ob1.singleNumber([1,1,5,3,2,5,2]))
nums = [1,1,5,3,2,5,2]
3 | [
{
"code": null,
"e": 1404,
"s": 1062,
"text": "Suppose we have an array A. In this array there are many numbers that occur twice. Only one element can be found a single time. We have to find that element from that array. Suppose A = [1, 1, 5, 3, 2, 5, 2], then the output will be 3. As there is each number twice, we can perform XOR to cancel out that element. because we know y XOR y = 0"
},
{
"code": null,
"e": 1447,
"s": 1404,
"text": "To solve this, we will follow these steps."
},
{
"code": null,
"e": 1473,
"s": 1447,
"text": "Take one variable res = 0"
},
{
"code": null,
"e": 1528,
"s": 1473,
"text": "for each element e in array A, preform res = res XOR e"
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": "return res"
},
{
"code": null,
"e": 1611,
"s": 1539,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1622,
"s": 1611,
"text": " Live Demo"
},
{
"code": null,
"e": 1898,
"s": 1622,
"text": "class Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ans = nums[0]\n for i in range(1,len(nums)):\n ans ^=nums[i]\n return ans\nob1 = Solution()\nprint(ob1.singleNumber([1,1,5,3,2,5,2]))"
},
{
"code": null,
"e": 1921,
"s": 1898,
"text": "nums = [1,1,5,3,2,5,2]"
},
{
"code": null,
"e": 1923,
"s": 1921,
"text": "3"
}
] |
Matplotlib - Working with Images | The image module in Matplotlib package provides functionalities required for loading, rescaling and displaying image.
Loading image data is supported by the Pillow library. Natively, Matplotlib only supports PNG images. The commands shown below fall back on Pillow if the native read fails.
The image used in this example is a PNG file, but keep that Pillow requirement in mind for your own data. The imread() function is used to read image data in an ndarray object of float32 dtype.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('mtplogo.png')
Assuming that following image named as mtplogo.png is present in the current working directory.
Any array containing image data can be saved to a disk file by executing the imsave() function. Here a vertically flipped version of the original png file is saved by giving origin parameter as lower.
plt.imsave("logo.png", img, cmap = 'gray', origin = 'lower')
The new image appears as below if opened in any image viewer.
To draw the image on Matplotlib viewer, execute the imshow() function.
imgplot = plt.imshow(img)
63 Lectures
6 hours
Abhilash Nelson
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
9 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
32 Lectures
4 hours
Aipython
10 Lectures
2.5 hours
Akbar Khan
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2634,
"s": 2516,
"text": "The image module in Matplotlib package provides functionalities required for loading, rescaling and displaying image."
},
{
"code": null,
"e": 2807,
"s": 2634,
"text": "Loading image data is supported by the Pillow library. Natively, Matplotlib only supports PNG images. The commands shown below fall back on Pillow if the native read fails."
},
{
"code": null,
"e": 3001,
"s": 2807,
"text": "The image used in this example is a PNG file, but keep that Pillow requirement in mind for your own data. The imread() function is used to read image data in an ndarray object of float32 dtype."
},
{
"code": null,
"e": 3119,
"s": 3001,
"text": "import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimg = mpimg.imread('mtplogo.png')"
},
{
"code": null,
"e": 3215,
"s": 3119,
"text": "Assuming that following image named as mtplogo.png is present in the current working directory."
},
{
"code": null,
"e": 3416,
"s": 3215,
"text": "Any array containing image data can be saved to a disk file by executing the imsave() function. Here a vertically flipped version of the original png file is saved by giving origin parameter as lower."
},
{
"code": null,
"e": 3477,
"s": 3416,
"text": "plt.imsave(\"logo.png\", img, cmap = 'gray', origin = 'lower')"
},
{
"code": null,
"e": 3539,
"s": 3477,
"text": "The new image appears as below if opened in any image viewer."
},
{
"code": null,
"e": 3610,
"s": 3539,
"text": "To draw the image on Matplotlib viewer, execute the imshow() function."
},
{
"code": null,
"e": 3636,
"s": 3610,
"text": "imgplot = plt.imshow(img)"
},
{
"code": null,
"e": 3669,
"s": 3636,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3686,
"s": 3669,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3719,
"s": 3686,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3754,
"s": 3719,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3788,
"s": 3754,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3823,
"s": 3788,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3856,
"s": 3823,
"text": "\n 32 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3866,
"s": 3856,
"text": " Aipython"
},
{
"code": null,
"e": 3901,
"s": 3866,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3913,
"s": 3901,
"text": " Akbar Khan"
},
{
"code": null,
"e": 3946,
"s": 3913,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3953,
"s": 3946,
"text": " Anmol"
},
{
"code": null,
"e": 3960,
"s": 3953,
"text": " Print"
},
{
"code": null,
"e": 3971,
"s": 3960,
"text": " Add Notes"
}
] |
Several Model Validation Techniques in Python | by Terence Shin | Towards Data Science | I wanted to write this article because I think a lot of people tend to overlook the validation and testing stage of machine learning. Similar to experimental design, it’s important that you spend enough time and use the right technique(s) to validate your ML models. Model validation goes far beyond train_test_split(), which you’ll soon find out if you keep reading!
Model validation is a method of checking how close the predictions of a model is to reality. Likewise, model validation means to calculate the accuracy (or metric of evaluation) of the model that you’re training.
There are several different methods that you can use to validate your ML models, which we’ll dive into below:
While this isn’t necessarily a technique, I would consider this a bonus because it can be used as an additional validation step for almost any ML model that you create.
I came across Gradio about a month ago, and I have been a big advocate for it, and rightfully so. It is extremely useful for a number of reasons including the ability to validate and test your model with your own inputs.
I find Gradio incredibly useful when validating my models for the following reasons:
It allows me to interactively test different inputs into the model.It allows me to get feedback from domain users and domain experts (who may be non-coders)It takes 3 lines of code to implement and it can be easily distributed via a public link.
It allows me to interactively test different inputs into the model.
It allows me to get feedback from domain users and domain experts (who may be non-coders)
It takes 3 lines of code to implement and it can be easily distributed via a public link.
This type of “validation” is something that I always do on top of the following validation techniques...
This method is the most commonly used in model validation. Here, the dataset for the model is split into training, validation, and the test sample. All these sets are defined below:
Training set: The dataset on which a model trains. All the learning happens on this set of data.
Validation set: This dataset is used to tune the model(s) trained from the dataset. Here, this is also when a final model is chosen to be tested using the test set.
Test set: The generalizability of a model is tested against the test set. It is the final stage of evaluation as it gives a signal if the model is ready for real-life application or not.
The goal of this method is to check the behavior of the model for the new data. The dataset is split into different percentages that mainly depend on your project and the number of resources you have.
The image below gives a clear demonstration of this example.
The following python code implements this method. The training, validation, and test set will be 60%, 20%, and 20% of the total dataset respectively:
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1)X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, test_size=0.25, random_state=1)
This method does not apply to every situation and it has its pros and cons.
It is very simple to implement.
The execution is relatively quick in comparison to other methods.
For the models with small datasets, this method can decrease the accuracy if there are not enough data points in each set.
For the accurate evaluation metrics, the split should be random or it becomes inaccurate.
It can cause models to overfit the validation set.
K-fold cross-validation solves all the problems of the train/test split. With K-fold cross-validation, the dataset is split into K folds or sections and each of the fold is used as a test set at some position.
For example, imagine having a 4-fold cross-validation set — with four folds, the model will be tested four times, where each fold is used as the test set and the other folds are used as the training set. Then, the model’s final evaluation is simply the average of all k tests. The image below gives a clear demonstration of the process.
Here is how you can implement it in Python for a fold of size 5:
from sklearn.datasets import load_irisimport pandas as pdfrom sklearn.model_selection import KFoldfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoredata = load_iris(as_frame = True)df = data.frameX = df.iloc[:,:-1]y = df.iloc[:,-1]kf = KFold(n_splits=5, random_state=None)model = LogisticRegression(solver= ‘liblinear’)acc_score = []for train_index , test_index in kf.split(X): X_train , X_test = X.iloc[train_index,:],X.iloc[test_index,:] y_train , y_test = y[train_index] , y[test_index] model.fit(X_train,y_train) pred_values = model.predict(X_test) acc = accuracy_score(pred_values , y_test) acc_score.append(acc)avg_acc_score = sum(acc_score)/kprint(‘accuracy of each fold — {}’.format(acc_score))print(‘Avg accuracy : {}’.format(avg_acc_score))
This method has the following pros and cons:
The evaluation metrics generated by this method are a lot more realistic.
The overfitting problem is solved to a great extent.
This results in reduced bias.
It takes a lot of computational power as more calculations are needed to be done.
Similarly the time required is greater as well.
Leave-one-out is a special case of K fold validation where the training set has all the instances minus one data point of the dataset and the test set the remaining observation left out. Let us suppose we have a dataset of M instances, the training set will be M-1 and the test set will be one.
This explains the name of this approach. In LOOCV, K=N where one model is created and evaluated for each instance in the dataset. As every instant is used for the process, this removes the need for the sampling of data.
The python implementation of it is given as follows:
from sklearn.datasets import make_blobsfrom sklearn.model_selection import LeaveOneOutfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score# create datasetX, y = make_blobs(n_samples=100, random_state=1)# create loocv procedurecv = LeaveOneOut()# enumerate splitsy_true, y_pred = list(), list()for train_ix, test_ix in cv.split(X): # split data X_train, X_test = X[train_ix, :], X[test_ix, :] y_train, y_test = y[train_ix], y[test_ix] # fit model model = RandomForestClassifier(random_state=1) model.fit(X_train, y_train) # evaluate model yhat = model.predict(X_test) # store y_true.append(y_test[0]) y_pred.append(yhat[0])# calculate accuracyacc = accuracy_score(y_true, y_pred)print('Accuracy: %.3f' % acc)
Pros:
Highly accurate and unbiased models can be generated with leave one out cross-validation.
We do not have to divide the data into random samples.
It is perfect for smaller data sets.
Cons:
It is the most computationally expensive version of k-folds cross-validation as the model has to be fitted M times.
It is not suitable for larger datasets.
Mean squared error will vary due to a single instant of test data which can result in higher variability (high variance)
The stratified k-fold method is the extension of the simple k-cross-validation which is mainly used for classification problems. The splits in this method are not random like the k-cross-validation. Stratification ensures that each fold is representative of all strata of the data — specifically, it aims to ensure that each class is equally represented across each test fold.
Let us take a simple example for a classification problem where our machine learning model identifies a cat or a dog from the image. If we have a dataset where 70% of pictures are of cats and the other 30% are dogs, in the stratified k-Fold, we will maintain the 70/30 ratio for each fold.
This technique is ideal when we have smaller datasets and we have to maintain the class ratio as well. Sometimes, the data is over or undersampled to match the required criteria.
The python implementation works as follows. Sklearn provides us with the StratifiedKFold function.
import numpy as npfrom sklearn.model_selection import StratifiedKFoldX = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])y = np.array([0, 0, 1, 1])skf = StratifiedKFold(n_splits=2)skf.get_n_splits(X, y)print(skf)for train_index, test_index in skf.split(X, y): print(“TRAIN:”, train_index, “TEST:”, test_index) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index]
The pros and cons of this method are as follows:
It works well for a dataset with few training examples and imbalanced data.
The class ratio is preserved.
It is not an ideal approach for regression problems.
It struggles with larger datasets for the best results.
In this article, we have seen different model validation techniques, each serving different purposes and are best suited in different scenarios. Before using any of these validation techniques, always take account of your computational resources, time limit, and the type of problem you are trying to solve.
As always, I wish you the best in your learning endeavors! :)
Not sure what to read next? I’ve picked another article for you:
towardsdatascience.com
and another one!
towardsdatascience.com
If you enjoyed this, follow me on Medium for more
Interested in collaborating? Let’s connect on LinkedIn
Sign up for my email list here! | [
{
"code": null,
"e": 540,
"s": 172,
"text": "I wanted to write this article because I think a lot of people tend to overlook the validation and testing stage of machine learning. Similar to experimental design, it’s important that you spend enough time and use the right technique(s) to validate your ML models. Model validation goes far beyond train_test_split(), which you’ll soon find out if you keep reading!"
},
{
"code": null,
"e": 753,
"s": 540,
"text": "Model validation is a method of checking how close the predictions of a model is to reality. Likewise, model validation means to calculate the accuracy (or metric of evaluation) of the model that you’re training."
},
{
"code": null,
"e": 863,
"s": 753,
"text": "There are several different methods that you can use to validate your ML models, which we’ll dive into below:"
},
{
"code": null,
"e": 1032,
"s": 863,
"text": "While this isn’t necessarily a technique, I would consider this a bonus because it can be used as an additional validation step for almost any ML model that you create."
},
{
"code": null,
"e": 1253,
"s": 1032,
"text": "I came across Gradio about a month ago, and I have been a big advocate for it, and rightfully so. It is extremely useful for a number of reasons including the ability to validate and test your model with your own inputs."
},
{
"code": null,
"e": 1338,
"s": 1253,
"text": "I find Gradio incredibly useful when validating my models for the following reasons:"
},
{
"code": null,
"e": 1584,
"s": 1338,
"text": "It allows me to interactively test different inputs into the model.It allows me to get feedback from domain users and domain experts (who may be non-coders)It takes 3 lines of code to implement and it can be easily distributed via a public link."
},
{
"code": null,
"e": 1652,
"s": 1584,
"text": "It allows me to interactively test different inputs into the model."
},
{
"code": null,
"e": 1742,
"s": 1652,
"text": "It allows me to get feedback from domain users and domain experts (who may be non-coders)"
},
{
"code": null,
"e": 1832,
"s": 1742,
"text": "It takes 3 lines of code to implement and it can be easily distributed via a public link."
},
{
"code": null,
"e": 1937,
"s": 1832,
"text": "This type of “validation” is something that I always do on top of the following validation techniques..."
},
{
"code": null,
"e": 2119,
"s": 1937,
"text": "This method is the most commonly used in model validation. Here, the dataset for the model is split into training, validation, and the test sample. All these sets are defined below:"
},
{
"code": null,
"e": 2216,
"s": 2119,
"text": "Training set: The dataset on which a model trains. All the learning happens on this set of data."
},
{
"code": null,
"e": 2381,
"s": 2216,
"text": "Validation set: This dataset is used to tune the model(s) trained from the dataset. Here, this is also when a final model is chosen to be tested using the test set."
},
{
"code": null,
"e": 2568,
"s": 2381,
"text": "Test set: The generalizability of a model is tested against the test set. It is the final stage of evaluation as it gives a signal if the model is ready for real-life application or not."
},
{
"code": null,
"e": 2769,
"s": 2568,
"text": "The goal of this method is to check the behavior of the model for the new data. The dataset is split into different percentages that mainly depend on your project and the number of resources you have."
},
{
"code": null,
"e": 2830,
"s": 2769,
"text": "The image below gives a clear demonstration of this example."
},
{
"code": null,
"e": 2980,
"s": 2830,
"text": "The following python code implements this method. The training, validation, and test set will be 60%, 20%, and 20% of the total dataset respectively:"
},
{
"code": null,
"e": 3222,
"s": 2980,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1)X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, test_size=0.25, random_state=1)"
},
{
"code": null,
"e": 3298,
"s": 3222,
"text": "This method does not apply to every situation and it has its pros and cons."
},
{
"code": null,
"e": 3330,
"s": 3298,
"text": "It is very simple to implement."
},
{
"code": null,
"e": 3396,
"s": 3330,
"text": "The execution is relatively quick in comparison to other methods."
},
{
"code": null,
"e": 3519,
"s": 3396,
"text": "For the models with small datasets, this method can decrease the accuracy if there are not enough data points in each set."
},
{
"code": null,
"e": 3609,
"s": 3519,
"text": "For the accurate evaluation metrics, the split should be random or it becomes inaccurate."
},
{
"code": null,
"e": 3660,
"s": 3609,
"text": "It can cause models to overfit the validation set."
},
{
"code": null,
"e": 3870,
"s": 3660,
"text": "K-fold cross-validation solves all the problems of the train/test split. With K-fold cross-validation, the dataset is split into K folds or sections and each of the fold is used as a test set at some position."
},
{
"code": null,
"e": 4207,
"s": 3870,
"text": "For example, imagine having a 4-fold cross-validation set — with four folds, the model will be tested four times, where each fold is used as the test set and the other folds are used as the training set. Then, the model’s final evaluation is simply the average of all k tests. The image below gives a clear demonstration of the process."
},
{
"code": null,
"e": 4272,
"s": 4207,
"text": "Here is how you can implement it in Python for a fold of size 5:"
},
{
"code": null,
"e": 5078,
"s": 4272,
"text": "from sklearn.datasets import load_irisimport pandas as pdfrom sklearn.model_selection import KFoldfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoredata = load_iris(as_frame = True)df = data.frameX = df.iloc[:,:-1]y = df.iloc[:,-1]kf = KFold(n_splits=5, random_state=None)model = LogisticRegression(solver= ‘liblinear’)acc_score = []for train_index , test_index in kf.split(X): X_train , X_test = X.iloc[train_index,:],X.iloc[test_index,:] y_train , y_test = y[train_index] , y[test_index] model.fit(X_train,y_train) pred_values = model.predict(X_test) acc = accuracy_score(pred_values , y_test) acc_score.append(acc)avg_acc_score = sum(acc_score)/kprint(‘accuracy of each fold — {}’.format(acc_score))print(‘Avg accuracy : {}’.format(avg_acc_score))"
},
{
"code": null,
"e": 5123,
"s": 5078,
"text": "This method has the following pros and cons:"
},
{
"code": null,
"e": 5197,
"s": 5123,
"text": "The evaluation metrics generated by this method are a lot more realistic."
},
{
"code": null,
"e": 5250,
"s": 5197,
"text": "The overfitting problem is solved to a great extent."
},
{
"code": null,
"e": 5280,
"s": 5250,
"text": "This results in reduced bias."
},
{
"code": null,
"e": 5362,
"s": 5280,
"text": "It takes a lot of computational power as more calculations are needed to be done."
},
{
"code": null,
"e": 5410,
"s": 5362,
"text": "Similarly the time required is greater as well."
},
{
"code": null,
"e": 5705,
"s": 5410,
"text": "Leave-one-out is a special case of K fold validation where the training set has all the instances minus one data point of the dataset and the test set the remaining observation left out. Let us suppose we have a dataset of M instances, the training set will be M-1 and the test set will be one."
},
{
"code": null,
"e": 5925,
"s": 5705,
"text": "This explains the name of this approach. In LOOCV, K=N where one model is created and evaluated for each instance in the dataset. As every instant is used for the process, this removes the need for the sampling of data."
},
{
"code": null,
"e": 5978,
"s": 5925,
"text": "The python implementation of it is given as follows:"
},
{
"code": null,
"e": 6750,
"s": 5978,
"text": "from sklearn.datasets import make_blobsfrom sklearn.model_selection import LeaveOneOutfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score# create datasetX, y = make_blobs(n_samples=100, random_state=1)# create loocv procedurecv = LeaveOneOut()# enumerate splitsy_true, y_pred = list(), list()for train_ix, test_ix in cv.split(X): # split data X_train, X_test = X[train_ix, :], X[test_ix, :] y_train, y_test = y[train_ix], y[test_ix] # fit model model = RandomForestClassifier(random_state=1) model.fit(X_train, y_train) # evaluate model yhat = model.predict(X_test) # store y_true.append(y_test[0]) y_pred.append(yhat[0])# calculate accuracyacc = accuracy_score(y_true, y_pred)print('Accuracy: %.3f' % acc)"
},
{
"code": null,
"e": 6756,
"s": 6750,
"text": "Pros:"
},
{
"code": null,
"e": 6846,
"s": 6756,
"text": "Highly accurate and unbiased models can be generated with leave one out cross-validation."
},
{
"code": null,
"e": 6901,
"s": 6846,
"text": "We do not have to divide the data into random samples."
},
{
"code": null,
"e": 6938,
"s": 6901,
"text": "It is perfect for smaller data sets."
},
{
"code": null,
"e": 6944,
"s": 6938,
"text": "Cons:"
},
{
"code": null,
"e": 7060,
"s": 6944,
"text": "It is the most computationally expensive version of k-folds cross-validation as the model has to be fitted M times."
},
{
"code": null,
"e": 7100,
"s": 7060,
"text": "It is not suitable for larger datasets."
},
{
"code": null,
"e": 7221,
"s": 7100,
"text": "Mean squared error will vary due to a single instant of test data which can result in higher variability (high variance)"
},
{
"code": null,
"e": 7598,
"s": 7221,
"text": "The stratified k-fold method is the extension of the simple k-cross-validation which is mainly used for classification problems. The splits in this method are not random like the k-cross-validation. Stratification ensures that each fold is representative of all strata of the data — specifically, it aims to ensure that each class is equally represented across each test fold."
},
{
"code": null,
"e": 7888,
"s": 7598,
"text": "Let us take a simple example for a classification problem where our machine learning model identifies a cat or a dog from the image. If we have a dataset where 70% of pictures are of cats and the other 30% are dogs, in the stratified k-Fold, we will maintain the 70/30 ratio for each fold."
},
{
"code": null,
"e": 8067,
"s": 7888,
"text": "This technique is ideal when we have smaller datasets and we have to maintain the class ratio as well. Sometimes, the data is over or undersampled to match the required criteria."
},
{
"code": null,
"e": 8166,
"s": 8067,
"text": "The python implementation works as follows. Sklearn provides us with the StratifiedKFold function."
},
{
"code": null,
"e": 8572,
"s": 8166,
"text": "import numpy as npfrom sklearn.model_selection import StratifiedKFoldX = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])y = np.array([0, 0, 1, 1])skf = StratifiedKFold(n_splits=2)skf.get_n_splits(X, y)print(skf)for train_index, test_index in skf.split(X, y): print(“TRAIN:”, train_index, “TEST:”, test_index) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index]"
},
{
"code": null,
"e": 8621,
"s": 8572,
"text": "The pros and cons of this method are as follows:"
},
{
"code": null,
"e": 8697,
"s": 8621,
"text": "It works well for a dataset with few training examples and imbalanced data."
},
{
"code": null,
"e": 8727,
"s": 8697,
"text": "The class ratio is preserved."
},
{
"code": null,
"e": 8780,
"s": 8727,
"text": "It is not an ideal approach for regression problems."
},
{
"code": null,
"e": 8836,
"s": 8780,
"text": "It struggles with larger datasets for the best results."
},
{
"code": null,
"e": 9144,
"s": 8836,
"text": "In this article, we have seen different model validation techniques, each serving different purposes and are best suited in different scenarios. Before using any of these validation techniques, always take account of your computational resources, time limit, and the type of problem you are trying to solve."
},
{
"code": null,
"e": 9206,
"s": 9144,
"text": "As always, I wish you the best in your learning endeavors! :)"
},
{
"code": null,
"e": 9271,
"s": 9206,
"text": "Not sure what to read next? I’ve picked another article for you:"
},
{
"code": null,
"e": 9294,
"s": 9271,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9311,
"s": 9294,
"text": "and another one!"
},
{
"code": null,
"e": 9334,
"s": 9311,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9384,
"s": 9334,
"text": "If you enjoyed this, follow me on Medium for more"
},
{
"code": null,
"e": 9439,
"s": 9384,
"text": "Interested in collaborating? Let’s connect on LinkedIn"
}
] |
Number of Distinct Islands in C++ | Suppose we have a binary 2D array grid, here an island is a group of 1's (land) connected 4- directionally (horizontal or vertical.) We can assume all four edges of the grid are surrounded by water. We have to count the number of distinct islands.
An island is considered to be the same as another when one island can be translated (and not rotated or reflected) to equal the other.
So, if the input is like
then the output will be 3
To solve this, we will follow these steps −
Define a function dfs(), this will take x, y, grid, temp, c,
Define a function dfs(), this will take x, y, grid, temp, c,
if x and y not in inside the grid rows and columns and grid[x,y] is 0, then −return
if x and y not in inside the grid rows and columns and grid[x,y] is 0, then −
return
return
grid[x, y] := 0
grid[x, y] := 0
temp := temp concatenate c
temp := temp concatenate c
dfs(x + 1, y, grid, temp, 'r')
dfs(x + 1, y, grid, temp, 'r')
dfs(x - 1, y, grid, temp, 'l')
dfs(x - 1, y, grid, temp, 'l')
dfs(x, y + 1, grid, temp, 'd')
dfs(x, y + 1, grid, temp, 'd')
dfs(x, y - 1, grid, temp, 'u')
dfs(x, y - 1, grid, temp, 'u')
temp := temp concatenate 'b'
temp := temp concatenate 'b'
From the main method do the following −
From the main method do the following −
ret := 0
ret := 0
Define one set visited
Define one set visited
for initialize i := 0, when i < row count of grid, update (increase i by 1), do −for initialize j := 0, when j < col count of grid, update (increase j by 1), do −if grid[i, j] is non-zero, then −aux := empty stringdfs(i, j, grid, aux, 's')if aux is not in visited, then −(increase ret by 1)insert aux into visited
for initialize i := 0, when i < row count of grid, update (increase i by 1), do −
for initialize j := 0, when j < col count of grid, update (increase j by 1), do −if grid[i, j] is non-zero, then −aux := empty stringdfs(i, j, grid, aux, 's')if aux is not in visited, then −(increase ret by 1)insert aux into visited
for initialize j := 0, when j < col count of grid, update (increase j by 1), do −
if grid[i, j] is non-zero, then −aux := empty stringdfs(i, j, grid, aux, 's')if aux is not in visited, then −(increase ret by 1)insert aux into visited
if grid[i, j] is non-zero, then −
aux := empty string
aux := empty string
dfs(i, j, grid, aux, 's')
dfs(i, j, grid, aux, 's')
if aux is not in visited, then −(increase ret by 1)insert aux into visited
if aux is not in visited, then −
(increase ret by 1)
(increase ret by 1)
insert aux into visited
insert aux into visited
return ret
return ret
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
class Solution {
public:
void dfs(int x, int y, vector < vector <int> >& grid, string& temp, char c){
if (x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || !grid[x][y])
return;
grid[x][y] = 0;
temp += c;
dfs(x + 1, y, grid, temp, 'r');
dfs(x - 1, y, grid, temp, 'l');
dfs(x, y + 1, grid, temp, 'd');
dfs(x, y - 1, grid, temp, 'u');
temp += 'b';
}
int numDistinctIslands(vector<vector<int>>& grid) {
int ret = 0;
set<string> visited;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j]) {
string aux = "";
dfs(i, j, grid, aux, 's');
if (!visited.count(aux)) {
ret++;
visited.insert(aux);
}
}
}
}
return ret;
}
};
main(){
Solution ob;
vector<vector<int>> v =
{{1,1,0,1,1},{1,0,0,0,0},{0,0,0,0,1},{1,1,0,1,1}};
cout<<(ob.numDistinctIslands(v));
}
{{1,1,0,1,1},{1,0,0,0,0},{0,0,0,0,1},{1,1,0,1,1}}
3 | [
{
"code": null,
"e": 1310,
"s": 1062,
"text": "Suppose we have a binary 2D array grid, here an island is a group of 1's (land) connected 4- directionally (horizontal or vertical.) We can assume all four edges of the grid are surrounded by water. We have to count the number of distinct islands."
},
{
"code": null,
"e": 1445,
"s": 1310,
"text": "An island is considered to be the same as another when one island can be translated (and not rotated or reflected) to equal the other."
},
{
"code": null,
"e": 1470,
"s": 1445,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1496,
"s": 1470,
"text": "then the output will be 3"
},
{
"code": null,
"e": 1540,
"s": 1496,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1601,
"s": 1540,
"text": "Define a function dfs(), this will take x, y, grid, temp, c,"
},
{
"code": null,
"e": 1662,
"s": 1601,
"text": "Define a function dfs(), this will take x, y, grid, temp, c,"
},
{
"code": null,
"e": 1746,
"s": 1662,
"text": "if x and y not in inside the grid rows and columns and grid[x,y] is 0, then −return"
},
{
"code": null,
"e": 1824,
"s": 1746,
"text": "if x and y not in inside the grid rows and columns and grid[x,y] is 0, then −"
},
{
"code": null,
"e": 1831,
"s": 1824,
"text": "return"
},
{
"code": null,
"e": 1838,
"s": 1831,
"text": "return"
},
{
"code": null,
"e": 1854,
"s": 1838,
"text": "grid[x, y] := 0"
},
{
"code": null,
"e": 1870,
"s": 1854,
"text": "grid[x, y] := 0"
},
{
"code": null,
"e": 1897,
"s": 1870,
"text": "temp := temp concatenate c"
},
{
"code": null,
"e": 1924,
"s": 1897,
"text": "temp := temp concatenate c"
},
{
"code": null,
"e": 1955,
"s": 1924,
"text": "dfs(x + 1, y, grid, temp, 'r')"
},
{
"code": null,
"e": 1986,
"s": 1955,
"text": "dfs(x + 1, y, grid, temp, 'r')"
},
{
"code": null,
"e": 2017,
"s": 1986,
"text": "dfs(x - 1, y, grid, temp, 'l')"
},
{
"code": null,
"e": 2048,
"s": 2017,
"text": "dfs(x - 1, y, grid, temp, 'l')"
},
{
"code": null,
"e": 2079,
"s": 2048,
"text": "dfs(x, y + 1, grid, temp, 'd')"
},
{
"code": null,
"e": 2110,
"s": 2079,
"text": "dfs(x, y + 1, grid, temp, 'd')"
},
{
"code": null,
"e": 2141,
"s": 2110,
"text": "dfs(x, y - 1, grid, temp, 'u')"
},
{
"code": null,
"e": 2172,
"s": 2141,
"text": "dfs(x, y - 1, grid, temp, 'u')"
},
{
"code": null,
"e": 2201,
"s": 2172,
"text": "temp := temp concatenate 'b'"
},
{
"code": null,
"e": 2230,
"s": 2201,
"text": "temp := temp concatenate 'b'"
},
{
"code": null,
"e": 2270,
"s": 2230,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 2310,
"s": 2270,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 2319,
"s": 2310,
"text": "ret := 0"
},
{
"code": null,
"e": 2328,
"s": 2319,
"text": "ret := 0"
},
{
"code": null,
"e": 2351,
"s": 2328,
"text": "Define one set visited"
},
{
"code": null,
"e": 2374,
"s": 2351,
"text": "Define one set visited"
},
{
"code": null,
"e": 2688,
"s": 2374,
"text": "for initialize i := 0, when i < row count of grid, update (increase i by 1), do −for initialize j := 0, when j < col count of grid, update (increase j by 1), do −if grid[i, j] is non-zero, then −aux := empty stringdfs(i, j, grid, aux, 's')if aux is not in visited, then −(increase ret by 1)insert aux into visited"
},
{
"code": null,
"e": 2770,
"s": 2688,
"text": "for initialize i := 0, when i < row count of grid, update (increase i by 1), do −"
},
{
"code": null,
"e": 3003,
"s": 2770,
"text": "for initialize j := 0, when j < col count of grid, update (increase j by 1), do −if grid[i, j] is non-zero, then −aux := empty stringdfs(i, j, grid, aux, 's')if aux is not in visited, then −(increase ret by 1)insert aux into visited"
},
{
"code": null,
"e": 3085,
"s": 3003,
"text": "for initialize j := 0, when j < col count of grid, update (increase j by 1), do −"
},
{
"code": null,
"e": 3237,
"s": 3085,
"text": "if grid[i, j] is non-zero, then −aux := empty stringdfs(i, j, grid, aux, 's')if aux is not in visited, then −(increase ret by 1)insert aux into visited"
},
{
"code": null,
"e": 3271,
"s": 3237,
"text": "if grid[i, j] is non-zero, then −"
},
{
"code": null,
"e": 3291,
"s": 3271,
"text": "aux := empty string"
},
{
"code": null,
"e": 3311,
"s": 3291,
"text": "aux := empty string"
},
{
"code": null,
"e": 3337,
"s": 3311,
"text": "dfs(i, j, grid, aux, 's')"
},
{
"code": null,
"e": 3363,
"s": 3337,
"text": "dfs(i, j, grid, aux, 's')"
},
{
"code": null,
"e": 3438,
"s": 3363,
"text": "if aux is not in visited, then −(increase ret by 1)insert aux into visited"
},
{
"code": null,
"e": 3471,
"s": 3438,
"text": "if aux is not in visited, then −"
},
{
"code": null,
"e": 3491,
"s": 3471,
"text": "(increase ret by 1)"
},
{
"code": null,
"e": 3511,
"s": 3491,
"text": "(increase ret by 1)"
},
{
"code": null,
"e": 3535,
"s": 3511,
"text": "insert aux into visited"
},
{
"code": null,
"e": 3559,
"s": 3535,
"text": "insert aux into visited"
},
{
"code": null,
"e": 3570,
"s": 3559,
"text": "return ret"
},
{
"code": null,
"e": 3581,
"s": 3570,
"text": "return ret"
},
{
"code": null,
"e": 3653,
"s": 3581,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 3664,
"s": 3653,
"text": " Live Demo"
},
{
"code": null,
"e": 4812,
"s": 3664,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};\nclass Solution {\npublic:\n void dfs(int x, int y, vector < vector <int> >& grid, string& temp, char c){\n if (x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || !grid[x][y])\n return;\n grid[x][y] = 0;\n temp += c;\n dfs(x + 1, y, grid, temp, 'r');\n dfs(x - 1, y, grid, temp, 'l');\n dfs(x, y + 1, grid, temp, 'd');\n dfs(x, y - 1, grid, temp, 'u');\n temp += 'b';\n }\n int numDistinctIslands(vector<vector<int>>& grid) {\n int ret = 0;\n set<string> visited;\n for (int i = 0; i < grid.size(); i++) {\n for (int j = 0; j < grid[0].size(); j++) {\n if (grid[i][j]) {\n string aux = \"\";\n dfs(i, j, grid, aux, 's');\n if (!visited.count(aux)) {\n ret++;\n visited.insert(aux);\n }\n }\n }\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v =\n {{1,1,0,1,1},{1,0,0,0,0},{0,0,0,0,1},{1,1,0,1,1}};\n cout<<(ob.numDistinctIslands(v));\n}"
},
{
"code": null,
"e": 4862,
"s": 4812,
"text": "{{1,1,0,1,1},{1,0,0,0,0},{0,0,0,0,1},{1,1,0,1,1}}"
},
{
"code": null,
"e": 4864,
"s": 4862,
"text": "3"
}
] |
C++ Switch Case Statement | Practice | GeeksforGeeks | Given a number N, if the number is between 1 and 10 both inclusive then return the number in words (Lower case English Alphabets) otherwise return "not in range".
Example 1:
Input:
5
Output:
five
Example 2:
Input:
11
Output:
not in range
Your Task:
You don't need to read input or print anything. Your task is to complete the function isInRange() which takes an integer and if the number is between 1 and 10 both inclusive then return the number in words otherwise return "not in range".
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1<=N<=10000
0
avijit1126be203 weeks ago
class Solution{ static String isInRange(int N){ // code here String str = ""; switch(N) { case 1: str = "one"; break; case 2: str = "two"; break; case 3: str = "three"; break; case 4: str = "four"; break; case 5: str = "five"; break; case 6: str = "six"; break; case 7: str = "seven"; break; case 8: str = "eight"; break; case 9: str = "nine"; break; case 10: str = "ten"; break; default: str = "not in range"; } return str; }}
0
anushavennapoosa20021 month ago
// JAVA SOLUTION
class Solution{ static String isInRange(int N){ // code here
switch(N){ case 1: return "one";
case 2: return "two";
case 3: return "three";
case 4: return "four";
case 5: return "five";
case 6: return "six";
case 7: return "seven";
case 8: return "eight";
case 9: return "nine";
case 10: return "ten";
default: return "not in range"; }
}}
0
shorouqehab0761 month ago
#include<iostream>
using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << "one"; break; case 2: cout << "two"; break; case 3: cout << "three"; break; case 4: cout << "four"; break; case 5: cout << "five"; break; case 6: cout << "six"; break; case 7: cout << "seven"; break; case 8: cout << "eight"; break; case 9: cout << "nine"; break; case 10: cout << "ten"; break; default: cout << "not in range"; } return 0;}
0
shorouqehab0761 month ago
#include<iostream>
using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << "one"; break; case 2: cout << "two"; break; case 3: cout << "three"; break; case 4: cout << "four"; break; case 5: cout << "five"; break; case 6: cout << "six"; break; case 7: cout << "seven"; break; case 8: cout << "eight"; break; case 9: cout << "nine"; break; case 10: cout << "ten"; break; default: cout << "not in range"; } return 0;}
0
shorouqehab0761 month ago
#include<iostream>
using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << "one"; break; case 2: cout << "two"; break; case 3: cout << "three"; break; case 4: cout << "four"; break; case 5: cout << "five"; break; case 6: cout << "six"; break; case 7: cout << "seven"; break; case 8: cout << "eight"; break; case 9: cout << "nine"; break; case 10: cout << "ten"; break; default: cout << "out of range"; } return 0;}
0
imranmbhd24122 months ago
###CPP IMRAN
string isInRange(int N){ string a[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" }; if(N>= 1 && N<=10) return a[N-1]; return "not in range"; }
0
0niharika22 months ago
switch(N){ case 1: return "one";
case 2: return "two";
case 3: return "three";
case 4: return "four";
case 5: return "five";
case 6: return "six";
case 7: return "seven";
case 8: return "eight";
case 9: return "nine";
case 10: return "ten";
default: return "not in range"; }
0
arunuppal20032 months ago
#include <iostream>
using namespace std;
int main(){ int a; cout<<"Enter the number"; cin>>a; switch(a){ case 1: cout<<"one"; break; case 2 : cout<<"two"; break; case 3 : cout<<"three"; break; case 4 : cout<<"four"; break; case 5 : cout<<"five"; break; case 6 : cout<<"six"; break; case 7 : cout<<"seven"; break; case 8 : cout<<"eight"; break; case 9 : cout<<"nine"; break; case 10: cout<<"ten"; break; default: cout<<"not in range"; }
return 0;}
0
tonroyjptt3 months ago
(switch(N){ case 1: cout<<"one"<<endl; break;
.....
default:cout<<"not in range":
break;)
}
write code like this might gives you errors in more test cases... but not in available test cases...
write like this----
string isInRange(int N){ // code here switch(N){ case 1: //cout<<"one"<<endl; return "one"; break; case 2: //cout<<"two"<<endl; return "two"; break; case 3: //cout<<"three"<<endl; return "three"; break; case 4: //cout<<"four"<<endl; return "four"; break; case 5: //cout<<"five"<<endl; return "five"; break; case 6: //cout<<"six"<<endl; return "six"; break; case 7: //cout<<"seven"<<endl; return "seven"; break; case 8: //cout<<"eight"<<endl; return "eight"; break; case 9: //cout<<"nine"<<endl; return "nine"; break; case 10: //cout<<"ten"<<endl; return "ten"; break; default: //cout<<"not in range"; return "not in range"; break; } }
+1
anilkumarug213 months ago
My code is right but showing incorrect
// { Driver Code Starts#include<bits/stdc++.h> using namespace std;
// } Driver Code Endsclass Solution{ public: string isInRange(int N){ // code here int N; cin>>N switch ( N) { case 1: cout<<" one "; break; case 2 : cout<< " two"; break; case 3: cout <<" three "; break ; case 4: cout <<" four"; break ; case 5: cout <<" five "; break ; case 6: cout << " six "; break; case 7: cout<< " seven "; break ; case 8: cout << " Eight "; break ; case 9: cout << " nine "; break ; case 10: cout<< " ten "; break ; default: cout <<" not in range "; break ; } }};
// { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int N; cin >> N; Solution ob; cout << ob.isInRange(N) << endl; } return 0; } // } Driver Code Ends
it is better to give a blank coding screen😠😡
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": 401,
"s": 238,
"text": "Given a number N, if the number is between 1 and 10 both inclusive then return the number in words (Lower case English Alphabets) otherwise return \"not in range\"."
},
{
"code": null,
"e": 414,
"s": 403,
"text": "Example 1:"
},
{
"code": null,
"e": 436,
"s": 414,
"text": "Input:\n5\nOutput:\nfive"
},
{
"code": null,
"e": 449,
"s": 438,
"text": "Example 2:"
},
{
"code": null,
"e": 480,
"s": 449,
"text": "Input:\n11\nOutput:\nnot in range"
},
{
"code": null,
"e": 495,
"s": 484,
"text": "Your Task:"
},
{
"code": null,
"e": 734,
"s": 495,
"text": "You don't need to read input or print anything. Your task is to complete the function isInRange() which takes an integer and if the number is between 1 and 10 both inclusive then return the number in words otherwise return \"not in range\"."
},
{
"code": null,
"e": 798,
"s": 736,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 812,
"s": 798,
"text": "\nConstraints:"
},
{
"code": null,
"e": 824,
"s": 812,
"text": "1<=N<=10000"
},
{
"code": null,
"e": 828,
"s": 826,
"text": "0"
},
{
"code": null,
"e": 854,
"s": 828,
"text": "avijit1126be203 weeks ago"
},
{
"code": null,
"e": 1733,
"s": 854,
"text": "class Solution{ static String isInRange(int N){ // code here String str = \"\"; switch(N) { case 1: str = \"one\"; break; case 2: str = \"two\"; break; case 3: str = \"three\"; break; case 4: str = \"four\"; break; case 5: str = \"five\"; break; case 6: str = \"six\"; break; case 7: str = \"seven\"; break; case 8: str = \"eight\"; break; case 9: str = \"nine\"; break; case 10: str = \"ten\"; break; default: str = \"not in range\"; } return str; }}"
},
{
"code": null,
"e": 1735,
"s": 1733,
"text": "0"
},
{
"code": null,
"e": 1767,
"s": 1735,
"text": "anushavennapoosa20021 month ago"
},
{
"code": null,
"e": 1784,
"s": 1767,
"text": "// JAVA SOLUTION"
},
{
"code": null,
"e": 1853,
"s": 1784,
"text": "class Solution{ static String isInRange(int N){ // code here"
},
{
"code": null,
"e": 1896,
"s": 1853,
"text": " switch(N){ case 1: return \"one\";"
},
{
"code": null,
"e": 1924,
"s": 1896,
"text": " case 2: return \"two\";"
},
{
"code": null,
"e": 1954,
"s": 1924,
"text": " case 3: return \"three\";"
},
{
"code": null,
"e": 1983,
"s": 1954,
"text": " case 4: return \"four\";"
},
{
"code": null,
"e": 2012,
"s": 1983,
"text": " case 5: return \"five\";"
},
{
"code": null,
"e": 2040,
"s": 2012,
"text": " case 6: return \"six\";"
},
{
"code": null,
"e": 2070,
"s": 2040,
"text": " case 7: return \"seven\";"
},
{
"code": null,
"e": 2100,
"s": 2070,
"text": " case 8: return \"eight\";"
},
{
"code": null,
"e": 2129,
"s": 2100,
"text": " case 9: return \"nine\";"
},
{
"code": null,
"e": 2158,
"s": 2129,
"text": " case 10: return \"ten\";"
},
{
"code": null,
"e": 2199,
"s": 2158,
"text": " default: return \"not in range\"; }"
},
{
"code": null,
"e": 2205,
"s": 2199,
"text": " }}"
},
{
"code": null,
"e": 2207,
"s": 2205,
"text": "0"
},
{
"code": null,
"e": 2233,
"s": 2207,
"text": "shorouqehab0761 month ago"
},
{
"code": null,
"e": 2252,
"s": 2233,
"text": "#include<iostream>"
},
{
"code": null,
"e": 2782,
"s": 2252,
"text": "using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << \"one\"; break; case 2: cout << \"two\"; break; case 3: cout << \"three\"; break; case 4: cout << \"four\"; break; case 5: cout << \"five\"; break; case 6: cout << \"six\"; break; case 7: cout << \"seven\"; break; case 8: cout << \"eight\"; break; case 9: cout << \"nine\"; break; case 10: cout << \"ten\"; break; default: cout << \"not in range\"; } return 0;}"
},
{
"code": null,
"e": 2784,
"s": 2782,
"text": "0"
},
{
"code": null,
"e": 2810,
"s": 2784,
"text": "shorouqehab0761 month ago"
},
{
"code": null,
"e": 2829,
"s": 2810,
"text": "#include<iostream>"
},
{
"code": null,
"e": 3359,
"s": 2829,
"text": "using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << \"one\"; break; case 2: cout << \"two\"; break; case 3: cout << \"three\"; break; case 4: cout << \"four\"; break; case 5: cout << \"five\"; break; case 6: cout << \"six\"; break; case 7: cout << \"seven\"; break; case 8: cout << \"eight\"; break; case 9: cout << \"nine\"; break; case 10: cout << \"ten\"; break; default: cout << \"not in range\"; } return 0;}"
},
{
"code": null,
"e": 3361,
"s": 3359,
"text": "0"
},
{
"code": null,
"e": 3387,
"s": 3361,
"text": "shorouqehab0761 month ago"
},
{
"code": null,
"e": 3406,
"s": 3387,
"text": "#include<iostream>"
},
{
"code": null,
"e": 3936,
"s": 3406,
"text": "using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << \"one\"; break; case 2: cout << \"two\"; break; case 3: cout << \"three\"; break; case 4: cout << \"four\"; break; case 5: cout << \"five\"; break; case 6: cout << \"six\"; break; case 7: cout << \"seven\"; break; case 8: cout << \"eight\"; break; case 9: cout << \"nine\"; break; case 10: cout << \"ten\"; break; default: cout << \"out of range\"; } return 0;}"
},
{
"code": null,
"e": 3938,
"s": 3936,
"text": "0"
},
{
"code": null,
"e": 3964,
"s": 3938,
"text": "imranmbhd24122 months ago"
},
{
"code": null,
"e": 3977,
"s": 3964,
"text": "###CPP IMRAN"
},
{
"code": null,
"e": 4210,
"s": 3977,
"text": "string isInRange(int N){ string a[] = { \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\" }; if(N>= 1 && N<=10) return a[N-1]; return \"not in range\"; }"
},
{
"code": null,
"e": 4212,
"s": 4210,
"text": "0"
},
{
"code": null,
"e": 4235,
"s": 4212,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 4274,
"s": 4235,
"text": "switch(N){ case 1: return \"one\";"
},
{
"code": null,
"e": 4303,
"s": 4274,
"text": " case 2: return \"two\";"
},
{
"code": null,
"e": 4334,
"s": 4303,
"text": " case 3: return \"three\";"
},
{
"code": null,
"e": 4364,
"s": 4334,
"text": " case 4: return \"four\";"
},
{
"code": null,
"e": 4394,
"s": 4364,
"text": " case 5: return \"five\";"
},
{
"code": null,
"e": 4423,
"s": 4394,
"text": " case 6: return \"six\";"
},
{
"code": null,
"e": 4454,
"s": 4423,
"text": " case 7: return \"seven\";"
},
{
"code": null,
"e": 4485,
"s": 4454,
"text": " case 8: return \"eight\";"
},
{
"code": null,
"e": 4515,
"s": 4485,
"text": " case 9: return \"nine\";"
},
{
"code": null,
"e": 4545,
"s": 4515,
"text": " case 10: return \"ten\";"
},
{
"code": null,
"e": 4588,
"s": 4545,
"text": " default: return \"not in range\"; }"
},
{
"code": null,
"e": 4590,
"s": 4588,
"text": "0"
},
{
"code": null,
"e": 4616,
"s": 4590,
"text": "arunuppal20032 months ago"
},
{
"code": null,
"e": 4636,
"s": 4616,
"text": "#include <iostream>"
},
{
"code": null,
"e": 4657,
"s": 4636,
"text": "using namespace std;"
},
{
"code": null,
"e": 5420,
"s": 4657,
"text": "int main(){ int a; cout<<\"Enter the number\"; cin>>a; switch(a){ case 1: cout<<\"one\"; break; case 2 : cout<<\"two\"; break; case 3 : cout<<\"three\"; break; case 4 : cout<<\"four\"; break; case 5 : cout<<\"five\"; break; case 6 : cout<<\"six\"; break; case 7 : cout<<\"seven\"; break; case 8 : cout<<\"eight\"; break; case 9 : cout<<\"nine\"; break; case 10: cout<<\"ten\"; break; default: cout<<\"not in range\"; }"
},
{
"code": null,
"e": 5436,
"s": 5422,
"text": " return 0;}"
},
{
"code": null,
"e": 5438,
"s": 5436,
"text": "0"
},
{
"code": null,
"e": 5461,
"s": 5438,
"text": "tonroyjptt3 months ago"
},
{
"code": null,
"e": 5527,
"s": 5461,
"text": "(switch(N){ case 1: cout<<\"one\"<<endl; break;"
},
{
"code": null,
"e": 5543,
"s": 5527,
"text": " ....."
},
{
"code": null,
"e": 5583,
"s": 5543,
"text": " default:cout<<\"not in range\":"
},
{
"code": null,
"e": 5601,
"s": 5583,
"text": " break;)"
},
{
"code": null,
"e": 5603,
"s": 5601,
"text": "}"
},
{
"code": null,
"e": 5704,
"s": 5603,
"text": "write code like this might gives you errors in more test cases... but not in available test cases..."
},
{
"code": null,
"e": 5726,
"s": 5706,
"text": "write like this----"
},
{
"code": null,
"e": 6767,
"s": 5726,
"text": " string isInRange(int N){ // code here switch(N){ case 1: //cout<<\"one\"<<endl; return \"one\"; break; case 2: //cout<<\"two\"<<endl; return \"two\"; break; case 3: //cout<<\"three\"<<endl; return \"three\"; break; case 4: //cout<<\"four\"<<endl; return \"four\"; break; case 5: //cout<<\"five\"<<endl; return \"five\"; break; case 6: //cout<<\"six\"<<endl; return \"six\"; break; case 7: //cout<<\"seven\"<<endl; return \"seven\"; break; case 8: //cout<<\"eight\"<<endl; return \"eight\"; break; case 9: //cout<<\"nine\"<<endl; return \"nine\"; break; case 10: //cout<<\"ten\"<<endl; return \"ten\"; break; default: //cout<<\"not in range\"; return \"not in range\"; break; } }"
},
{
"code": null,
"e": 6770,
"s": 6767,
"text": "+1"
},
{
"code": null,
"e": 6796,
"s": 6770,
"text": "anilkumarug213 months ago"
},
{
"code": null,
"e": 6835,
"s": 6796,
"text": "My code is right but showing incorrect"
},
{
"code": null,
"e": 6903,
"s": 6835,
"text": "// { Driver Code Starts#include<bits/stdc++.h> using namespace std;"
},
{
"code": null,
"e": 7817,
"s": 6903,
"text": "// } Driver Code Endsclass Solution{ public: string isInRange(int N){ // code here int N; cin>>N switch ( N) { case 1: cout<<\" one \"; break; case 2 : cout<< \" two\"; break; case 3: cout <<\" three \"; break ; case 4: cout <<\" four\"; break ; case 5: cout <<\" five \"; break ; case 6: cout << \" six \"; break; case 7: cout<< \" seven \"; break ; case 8: cout << \" Eight \"; break ; case 9: cout << \" nine \"; break ; case 10: cout<< \" ten \"; break ; default: cout <<\" not in range \"; break ; } }};"
},
{
"code": null,
"e": 8020,
"s": 7817,
"text": "// { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int N; cin >> N; Solution ob; cout << ob.isInRange(N) << endl; } return 0; } // } Driver Code Ends"
},
{
"code": null,
"e": 8068,
"s": 8022,
"text": "it is better to give a blank coding screen😠😡"
},
{
"code": null,
"e": 8214,
"s": 8068,
"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": 8250,
"s": 8214,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8260,
"s": 8250,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8270,
"s": 8260,
"text": "\nContest\n"
},
{
"code": null,
"e": 8333,
"s": 8270,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8481,
"s": 8333,
"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": 8689,
"s": 8481,
"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": 8795,
"s": 8689,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Space Science with Python — Around the Sun | Towards Data Science | This is the 6th part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy!
Space can be violent. You have probably heard of Supernovae, Black Holes with an everlasting appetite, or collisions of celestial bodies on a huge scale (even a small asteroid can cause a severe impact on a biosphere like our home planet).
Space can also be calm. Like our very cosmic neighbourhood: The Solar System. We have one star, 4 inner planets, 4 outer gas giants (who partly protect us from larger asteroids), comets, asteroids and dust. Sure there are collisions and other events, but in general, it is quite and we can assume that all bodies revolve around the Sun in a so-called 2-body problem: One large mass M is being revolved by a much smaller mass m. We can assume that in all cases the following inequation applies: m<<M. The resulting problem becomes even simpler.
And thanks to this assumption we can apply functions from the SPICE library, to compute simple orbital mechanics and positions with Python. Today, we will compute and work with the so-called orbital elements. Do not worry, we will work closely with Python and have a brief theory lesson before the programming part begins!
Our home planet revolves the Sun in 365.25 days. During the year, the distance between the Earth and the Sun varies only slightly: Between around 147 and 152 Million kilometres; a variation of only a few percent. Our planet revolves the Sun almost on a perfect circle without any extreme variations, causing a friendly climate and biosphere over millions of years.
What is this “almost perfect circle”? It is an ellipse, described by different parameters that are explained in the following. We will not handle the theoretical derivation of the underlying equations since it would exceed the goal of this tutorial. Generally speaking, the mathematical fundament lies on Newton mechanics of motion. E.g., the semi-major axis (see below) can be derived from the Vis-Viva equation [Murray and Dermott, 2000, p. 30–31]. Chapter 3.1.1. of my thesis [Albin 2019] summarises briefly the derivation of all parameters. A little bit below you can see a sketch that shows the explained parameters:
Semi-major axis (a) This parameter describes the “longest radius” of an ellipse. The smallest radius is called semi-minor axis (b) and is mostly not used in orbit dynamics.
Eccentricity (e) The eccentricity describes the deviation of the orbit from a perfect circle. e has the following definition limits:
e = 0 (Circle)
0 < e < 1 (Ellipse)
e = 1 (Parabola)
e > 1 (Hyperbola)
Eccentricities that are larger or equal 1 describe open orbits. This applies, for example, for objects of interstellar origin, like 1I/ʻOumuamua [Meech et al. 2017, Micheli et al. 2018].
Inclination (i) The inclination is the enclosed angle between the orbit’s plane and a reference frame, like e.g., the ecliptic plane in the Ecliptic Coordinate System (ECLIPJ2000). i describes different orbit cases:
0°≤i<90° (Prograde orbit. Example: The Earth revolves the Sun in a prograde orbit in ECLIPJ2000)
i=90° (Polar orbit. Example: Weather satellites, Earth observation satellites or reconnaissance satellites revolve the Earth on polar orbits. This allows the satellites to scan the Earth on changing longitudes due to Earth’s rotation).
90°<i≤180° (Retrograde orbit. Example: Some meteoroid streams of cometary origin are on a retrograde orbits around the Sun. These meteors enter the Earth’s atmosphere with higher velocities than prograde ones).
Longitude of ascending node (Ω, ☊) This angle parameter describes where the ascending orbit crosses the reference plane with respect to a reference point (In ECLIPJ2000: the Vernal Equinox direction). At this node, the object moves from the southern to the northern hemisphere of the reference frame.
Argument of periapsis (⍵) The argument of periapsis describes the angular distance between the periapsis (as seen from the focal point) and the longitude of ascending node. The periapsis is the closest point around the larger centre mass and can be computed with (1-e)a. The counterpart, the apoapsis, can be computed with (1+e)a.
True Anomaly (v, ν) The true anomaly is the angle between the body’s position (as seen from the focal point) w.r.t. the argument of periapsis. This parameter is not needed to describe the orbit’s shape, but to determine the actual position of the object at a certain time called ...
Epoch (t)
Mean Anomaly (M) The concept of the mean anomaly appears to be confusing is a parameter that is used e.g., by the SPICE library (instead of the true anomaly). The angular speed (degrees per second) of the true anomaly varies with time (higher at the periapsis, lower at the apoapsis). The mean anomaly M describes a virtual position of the object drawn on an imaginary circle around the focal point of the ellipse. The idea: In contrary to the true anomaly, the mean anomaly’s angular speed is constant.
Finally, before we dive into some use cases one needs to know that different systems have different suffixes. For example the periapsis is a general term for an ellipse. In our Solar System, the suffix -apsis is replaced with:
-helion (objects that revolve the Sun)
-gee (objects, like our Moon that revolve the Earth)
-jove (objects that revolve around Jupiter, like Ganymede)
-krone or -saturnium (objects that revolve around Saturn, like Titan)
-astron (exoplanets around their stars)
Now let’s start with some programming fun. Today, we will use the data from SPICE’ spk kernels to derive orbital elements and vice versa. We begin with the dwarf planet / asteroid (1) Ceres. Ceres’ home is the asteroid main belt and with a diameter of over 900 km it is the largest representative in this crowded region. Between 2015 and 2018 NASA’s Dawn mission explored this world (see image above).
What are the orbital elements of Ceres? And can we derive values that are comparable with the literature? Let’s see:
First, as always, we need to import all necessary Python packages like datetime, numpy and spiceypy. From now on a few additional packages (pathlib, urllib, os) are needed to create an auxiliary download function.
The last tutorials required SPICE kernel files that have been uploaded on my GitHub repository. In future tutorials we need more and more kernels, depending on the tutorial’s task. Since the GitHub storage is limited, we create a helper function to download all future kernels in the _kernels directory. We define the function download_kernel in the following part. First, our function requires 2 input variables, a local storage path (dl_path) and the URL (dl_url) of the kernel (line 5). Line 6 to 18 are the docstring of the function. The URL contains the kernel’s file name. To obtain the name line 23 splits the URL at the “/”. Consequently, the very last entry of the resulting list has the file name. Now, the local download (sub-) directory is created, if it is not existing yet (line 27). If the kernel file is not present in this sub-directory (line 30) the kernel is downloaded and stored there (33).
For our Ceres project we need to search for the required spk kernels in the NAIF SPICE repository. Some asteroids data are stored under generic_kernels/spk/asteroids. There you find a readme file called aa_summaries.txt. It lists all spk asteroid data and NAIF IDs that are stored in the spk file codes_300ast_20100725.bsp.
But where do this data come from? Are they reliable? And since there are hundred thousands of asteroids: where are the others? To answer this question let’s take a look at the other readme file AAREADME_Asteroids_SPKs.txt. There you can read:
[...]We have left here a single SPK containing orbits for a set of 300 asteroids, the orbits for which were produced by Jim Baer in 2010 using his own CODES software. Some of these data may also be not very accurate. But the convenience of having data for 300 objects in a single SPK file could be useful for some purposes where high accuracy is not important. Read the *.cmt" file for details about this collection.[...]
So the kernel provides us spk information “for some purposes where high accuracy is not important”. Let’s assume that the accuracy is good enough to compare with the literature. Further, the file states that the “*.cmt file” contains more “details about this collection”. We take a look at codes_300ast_20100725.cmt. There you can find details about the underlying code that computed the spk file and other meta information. Doing science means doing literature research and reading and one detail in this cmt file is quite important:
Usage-------------------------------------------------------- This file should be used together with the DE405 planetary ephemeris since the integration was done using the DE405 ephemeris and with the frames kernel defining the ``ECLIPJ2000_DE405'' frame.
Hold on! Another reference frame called ECLIPJ2000_DE405? How is this frame defined? The files states that:
This frames kernel defines the Ecliptic and Equinox of the J2000 frame using the DE405 obliquity angle value (84381.412 arcseconds).[...]
The corresponding frame kernel is defined as (a detailed explanation will follow in a future tutorial):
\begindata FRAME_ECLIPJ2000_DE405 = 1900017 FRAME_1900017_NAME = 'ECLIPJ2000_DE405' FRAME_1900017_CLASS = 4 FRAME_1900017_CLASS_ID = 1900017 FRAME_1900017_CENTER = 0 TKFRAME_1900017_SPEC = 'ANGLES' TKFRAME_1900017_RELATIVE = 'J2000' TKFRAME_1900017_ANGLES = ( 0.0, 0.0, -84381.412 ) TKFRAME_1900017_AXES = ( 1, 3, 1 ) TKFRAME_1900017_UNITS = 'ARCSECONDS'
It appears to be a reference frame that is based on the Equatorial J2000 system and tilts one axis by 84381.412 arcseconds respectively 23,4°. This is the tilt of Earth’s rotation axis w.r.t. the ecliptic plane! Are ECLIPJ2000 and ECLIPJ2000_DE405 the same reference frame? We will find it out in a moment. First, we download the .bsp kernel and the kernel codes_300ast_20100725.tf. This kernel contains also the reference frame, but also the NAIF ID codes with the corresponding names. Since it contains miscellaneous information we create a new sub-directory called _kernels/_misc.
The SPICE meta file contains already the relative path names to the downloaded kernels, as well as the leap seconds kernel and planetary spk kernel. We load the meta file with furnsh. Our computations will be based on today’s date and the current time (line 5, line 8 converts the UTC date-time to a the Ephemeris time using the SPICE function utc2et).
Let’s take a look at the differences between ECLIPJ2000_DE405 and ECLIPJ2000. We compute in line 4 to 6 a 6x6 transformation matrix that transforms state vectors given in ECLIPJ2000_DE405 to ECLIPJ2000 at the current date-time (SPICE function sxform). Our theory: there is no difference between both systems, so we print (line 10 to 12) the matrix and expect the identity matrix (identity matrix times a vector results in the same vector):
The output is shown below. It is the identify matrix with 1s along the diagonal and 0s elsewhere. So both reference frame names represent the same frame.
Transformation matrix between ECLIPJ2000_DE405 and ECLIPJ2000[1. 0. 0. 0. 0. 0.][0. 1. 0. 0. 0. 0.][0. 0. 1. 0. 0. 0.][0. 0. 0. 1. 0. 0.][0. 0. 0. 0. 1. 0.][0. 0. 0. 0. 0. 1.]
Now let’s compute the state vector of Ceres in ECLIPJ2000. According to the .tf file the NAIF ID of Ceres is 2000001. We set the Sun (10) as the observer. Since we do not apply any light time corrections we can simply use the function spkgeo.
To compute the corresponding orbital elements we need to set the gravitational parameter (G) times the mass of the Sun (M). Line 2 extracts the G*M value from the needed kernel using the function bodvcd. The function requires the NAIF ID of the Sun (10), the requested parameter (GM) and the number of expected returns (1). The returned value is stored in an array and needs to be extracted in line 4.
SPICE provides two functions to determine the orbital elements based on a state vector:
oscelt
oscltx
oscltx requires the same input parameters as oscelt and returns the same values + 2 additional parameters. The input is:
state The state vector of the object (the spatial components x, y, z in km and the corresponding velocity components vx, vy, vz given in km/s)
et The Ephemeris time
mu The gravitational parameter (here: G*M of the Sun)
The output is a single array that contains the following parameters:
Periapsis in km
Eccentricity
Longitude of ascending node in radians
Argument of periapsis in radians
Mean anomaly at the epoch
Epoch
Gravitational parameter (same value as the input)
And the oscltx add-ons:
Semi-major axis in km
Orbital period in seconds
Line 2–4 compute the elements and the lines 7 to 24 assign the elements to individual constant names, where km are converted to AU (with the function convrt) and radians are converted to degrees (using the numpy function numpy.degrees). The very last line converts the orbital period given in seconds to years.
What is a reliable source or reference to compare the results with? It’s the (International Astronomical Union) Minor Planet Center (short: MPC). The MPC gathers all information regarding smaller objects of our Solar System (main belt asteroids, comets, Kuiper belt objects and so on). One section provides some general information for dwarf planets: MPC Dwarf Planets. There we find some data for the orbital elements and compare them with our results in the following coding part.
The results are:
Ceres' Orbital ElementsSemi-major axis in AU: 2.77 (MPC: 2.77)Perihelion in AU: 2.55 (MPC: 2.56)Eccentricity: 0.08 (MPC: 0.08)Inclination in degrees: 10.6 (MPC: 10.6)Long. of. asc. node in degrees: 80.3 (MPC: 80.3)Argument of perih. in degrees: 73.7 (MPC: 73.6)Orbit period in years: 4.61 (MPC: 4.61)
All in all, the orbital elements from the spk kernel file appear to be feasible. Only minor differences can be seen like a 0.01 AU difference for the semi-major axis.
Can we convert the orbital elements now back to a state vector? Sure! For this purpose SPICE provides a function called conics. The function requires two inputs: an array with the orbital elements and the requested ET. The order of the orbital elements are ...
Periapsis in km
Eccentricity
Longitude of ascending node in radians
Argument of periapsis in radians
Mean anomaly at the epoch
Epoch
Gravitational parameter
... so basically the output order of the function oscelt. Line 2 to 9 convert the orbital elements to a state vector and line 11 to 14 print the state vectors from conics and spkgeo.
The output is shown below and you can see that the state vectors are similar!
State vector of Ceres from the kernel:[ 3.07867363e+08 -3.13068701e+08 -6.66012287e+07 1.19236526e+01 1.14721598e+01 -1.83537545e+00]State vector of Ceres based on the determined orbital elements:[ 3.07867363e+08 -3.13068701e+08 -6.66012287e+07 1.19236526e+01 1.14721598e+01 -1.83537545e+00]
Have you seen a meteor? A falling star? Probably. One can observe so-called sporadics or stream meteors (like the Perseids in August). These are small dust particles entering the Earth’s atmosphere with high velocities. The atmospheric friction and ionisation cause a nice glowing effect. The source of these particles: comets, asteroids, collisions of minor bodies, etc. But there are also bigger particles that cross our Earth’s path around the Sun (or at least they come quite close): Near-Earth Objects (NEOs).
On Spaceweather.com you can see a list (bottom of the webpage) where objects are listed that will have a close encounter with Earth. Today (beginning of May 2020) we can see several objects. So let’s pick a larger one, like:
Asteroid | Date(UT) | Miss Distance | Diameter (m)---------|-------------|---------------|------------- 136795 | 2020-May-21 | 16.1 LD | 892
That’s a huge asteroid! Almost 1 km in diameter. Such an impact would be devastating for our home planet. But luckily, the minimum distance between Earth and 136795, respectively 1997 BQ is around 16.1 Lunar Distances (LD; 1 LD = 384401 km).
Before we compute the orbital elements of this object let’s take a quick look whether our planet’s gravitational pull would alter the orbit of the object severely.
One could now develop an N-body numerical simulator that considers all perturbation effects. Or, we could do a first simple approach before we apply any mathematical “overkill”. For this approach we use a simple astrodynamical idea: The Sphere of Influence (SOI). Each object in our Solar System has a SOI: The Earth, the Moon, each asteroid and planet. Within each body’s SOI, the body itself is the major gravitational factor. This means that for simple computations e.g., within Earth’s SOI, we can neglect the gravitational pull of larger objects like the Sun. The SOI is theoretically an ellipsoid, but can be approximated by a sphere. The SOI radius r of a mass m (e.g., the Earth) depends on its semi-major axis a and the larger mass M (e.g., the Sun):
So first, we can compute the Earth’s SOI to determine whether our planet will alter the orbit or not. We set 1 AU as the semi-major axis. Line 10 converts 1 AU to km (SPICE function convrt). In line 13 and 14 we extract the G*M value of Earth using bodvcd. Finally, line 17 computes Earth’s SOI in km. We set 1 LD as 384401 km in line 20 and print the result in line 22.
Earth’s SOI is around 2.4 LD. Consequently, the orbit of 1997 BQ should not be altered to much by the encounter with our home planet.
SOI of the Earth in LD: 2.4054224328225597
JPL’s Small Body Database provides the orbital elements at a certain epoch. However, we need to consider the provided errors (1 sigma deviation) of the values. In science, one has to round values, results or measurements based on the first 2 significant digits of the measurement error. E.g.,: x = 123.98765 with an error of xerr = 0.035 becomes x = 123.987 +/- 0.035.
The JPL database provides several digits for the error. So we build a small lambda function that rounds the values based on the position of the first 2 error digits. First, the log10 value of the error is taken. Example: 0.035 becomes -1.4559. Then the floor function is applied: -1.4559 becomes -2. We multiply the value with -1, and add +1 to the end. The result is 3. And that is what we need: we want to round 123.98765 at the 3rd position based on the error 0.035!
Let’s define all orbital elements with the data from the database. Please note: The database provides the epoch 2459000.5 (Julian Date). Thanks to the mighty utc2et function, this can easily be converted to ET using the string format “2459000.5 JD”.
Now we can compute the state vector of the asteroid after we create an array with orbital elements (line 2 to 9). We use the function conics to determine the state vector for the current date-time (line 12). Finally, the results are printed in line 14+15.
Current state vector of 1997BQ in km and km/s (2020-05-08T15:29:48):[-1.01302335e+08 -9.80403762e+07 2.92324589e+06 2.10287249e+01 -2.97600309e+01 -6.83829911e+00]
What is the current distance between 1997 BQ and the Earth? To find out, we compute Earth’s state vector, too (using spkgeo). The NAIF ID for our planet is 399 and the observer is the Sun (10). We use the same ET (DATETIME_ET) and set the reference frame ECLIPJ2000. The spatial components of both state vectors are then used to determine the length of the resulting vector between Earth and 1997 BQ (line 8+9, function vnorm).
For our timestamp the distance is around 38.69 LD.
Current distance between the Earth and 1997BQ in LD (2020-05-08T15:29:48):38.69205689796575
That was a lot of content to digest! Take your time and use the provided Jupyter Notebook and Python script from my GitHub repository to walk through this tutorial. Reference frames and orbital mechanics as shown in the last two tutorials are used in the future tutorials. Do not worry. The next tutorials will be smaller to give you some time to get familiar with everything. There are a lot of Python functions, concepts and technical terms that need to be understand. If you need support or have any questions do not hesitate to ask.
Thomas
Albin, T. (2019). Machine learning and monte carlo based data analysis methods in cosmic dust research. University of Stuttgart.
Meech, K., Weryk, R., Micheli, M. et al. A brief visit from a red and extremely elongated interstellar asteroid. Nature 552, 378–381 (2017). https://doi.org/10.1038/nature25020
Micheli, M., Farnocchia, D., Meech, K.J. et al. Non-gravitational acceleration in the trajectory of 1I/2017 U1 (‘Oumuamua). Nature 559, 223–226 (2018). https://doi.org/10.1038/s41586-018-0254-4
Carl D. Murray and Stanley F. Dermott. Solar System Dynamics. Cambridge University Press, 2000. ISBN 978–0–521–57597–3. | [
{
"code": null,
"e": 311,
"s": 171,
"text": "This is the 6th part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy!"
},
{
"code": null,
"e": 551,
"s": 311,
"text": "Space can be violent. You have probably heard of Supernovae, Black Holes with an everlasting appetite, or collisions of celestial bodies on a huge scale (even a small asteroid can cause a severe impact on a biosphere like our home planet)."
},
{
"code": null,
"e": 1095,
"s": 551,
"text": "Space can also be calm. Like our very cosmic neighbourhood: The Solar System. We have one star, 4 inner planets, 4 outer gas giants (who partly protect us from larger asteroids), comets, asteroids and dust. Sure there are collisions and other events, but in general, it is quite and we can assume that all bodies revolve around the Sun in a so-called 2-body problem: One large mass M is being revolved by a much smaller mass m. We can assume that in all cases the following inequation applies: m<<M. The resulting problem becomes even simpler."
},
{
"code": null,
"e": 1418,
"s": 1095,
"text": "And thanks to this assumption we can apply functions from the SPICE library, to compute simple orbital mechanics and positions with Python. Today, we will compute and work with the so-called orbital elements. Do not worry, we will work closely with Python and have a brief theory lesson before the programming part begins!"
},
{
"code": null,
"e": 1783,
"s": 1418,
"text": "Our home planet revolves the Sun in 365.25 days. During the year, the distance between the Earth and the Sun varies only slightly: Between around 147 and 152 Million kilometres; a variation of only a few percent. Our planet revolves the Sun almost on a perfect circle without any extreme variations, causing a friendly climate and biosphere over millions of years."
},
{
"code": null,
"e": 2405,
"s": 1783,
"text": "What is this “almost perfect circle”? It is an ellipse, described by different parameters that are explained in the following. We will not handle the theoretical derivation of the underlying equations since it would exceed the goal of this tutorial. Generally speaking, the mathematical fundament lies on Newton mechanics of motion. E.g., the semi-major axis (see below) can be derived from the Vis-Viva equation [Murray and Dermott, 2000, p. 30–31]. Chapter 3.1.1. of my thesis [Albin 2019] summarises briefly the derivation of all parameters. A little bit below you can see a sketch that shows the explained parameters:"
},
{
"code": null,
"e": 2578,
"s": 2405,
"text": "Semi-major axis (a) This parameter describes the “longest radius” of an ellipse. The smallest radius is called semi-minor axis (b) and is mostly not used in orbit dynamics."
},
{
"code": null,
"e": 2711,
"s": 2578,
"text": "Eccentricity (e) The eccentricity describes the deviation of the orbit from a perfect circle. e has the following definition limits:"
},
{
"code": null,
"e": 2726,
"s": 2711,
"text": "e = 0 (Circle)"
},
{
"code": null,
"e": 2746,
"s": 2726,
"text": "0 < e < 1 (Ellipse)"
},
{
"code": null,
"e": 2763,
"s": 2746,
"text": "e = 1 (Parabola)"
},
{
"code": null,
"e": 2781,
"s": 2763,
"text": "e > 1 (Hyperbola)"
},
{
"code": null,
"e": 2968,
"s": 2781,
"text": "Eccentricities that are larger or equal 1 describe open orbits. This applies, for example, for objects of interstellar origin, like 1I/ʻOumuamua [Meech et al. 2017, Micheli et al. 2018]."
},
{
"code": null,
"e": 3184,
"s": 2968,
"text": "Inclination (i) The inclination is the enclosed angle between the orbit’s plane and a reference frame, like e.g., the ecliptic plane in the Ecliptic Coordinate System (ECLIPJ2000). i describes different orbit cases:"
},
{
"code": null,
"e": 3281,
"s": 3184,
"text": "0°≤i<90° (Prograde orbit. Example: The Earth revolves the Sun in a prograde orbit in ECLIPJ2000)"
},
{
"code": null,
"e": 3517,
"s": 3281,
"text": "i=90° (Polar orbit. Example: Weather satellites, Earth observation satellites or reconnaissance satellites revolve the Earth on polar orbits. This allows the satellites to scan the Earth on changing longitudes due to Earth’s rotation)."
},
{
"code": null,
"e": 3728,
"s": 3517,
"text": "90°<i≤180° (Retrograde orbit. Example: Some meteoroid streams of cometary origin are on a retrograde orbits around the Sun. These meteors enter the Earth’s atmosphere with higher velocities than prograde ones)."
},
{
"code": null,
"e": 4029,
"s": 3728,
"text": "Longitude of ascending node (Ω, ☊) This angle parameter describes where the ascending orbit crosses the reference plane with respect to a reference point (In ECLIPJ2000: the Vernal Equinox direction). At this node, the object moves from the southern to the northern hemisphere of the reference frame."
},
{
"code": null,
"e": 4360,
"s": 4029,
"text": "Argument of periapsis (⍵) The argument of periapsis describes the angular distance between the periapsis (as seen from the focal point) and the longitude of ascending node. The periapsis is the closest point around the larger centre mass and can be computed with (1-e)a. The counterpart, the apoapsis, can be computed with (1+e)a."
},
{
"code": null,
"e": 4643,
"s": 4360,
"text": "True Anomaly (v, ν) The true anomaly is the angle between the body’s position (as seen from the focal point) w.r.t. the argument of periapsis. This parameter is not needed to describe the orbit’s shape, but to determine the actual position of the object at a certain time called ..."
},
{
"code": null,
"e": 4653,
"s": 4643,
"text": "Epoch (t)"
},
{
"code": null,
"e": 5157,
"s": 4653,
"text": "Mean Anomaly (M) The concept of the mean anomaly appears to be confusing is a parameter that is used e.g., by the SPICE library (instead of the true anomaly). The angular speed (degrees per second) of the true anomaly varies with time (higher at the periapsis, lower at the apoapsis). The mean anomaly M describes a virtual position of the object drawn on an imaginary circle around the focal point of the ellipse. The idea: In contrary to the true anomaly, the mean anomaly’s angular speed is constant."
},
{
"code": null,
"e": 5384,
"s": 5157,
"text": "Finally, before we dive into some use cases one needs to know that different systems have different suffixes. For example the periapsis is a general term for an ellipse. In our Solar System, the suffix -apsis is replaced with:"
},
{
"code": null,
"e": 5423,
"s": 5384,
"text": "-helion (objects that revolve the Sun)"
},
{
"code": null,
"e": 5476,
"s": 5423,
"text": "-gee (objects, like our Moon that revolve the Earth)"
},
{
"code": null,
"e": 5535,
"s": 5476,
"text": "-jove (objects that revolve around Jupiter, like Ganymede)"
},
{
"code": null,
"e": 5605,
"s": 5535,
"text": "-krone or -saturnium (objects that revolve around Saturn, like Titan)"
},
{
"code": null,
"e": 5645,
"s": 5605,
"text": "-astron (exoplanets around their stars)"
},
{
"code": null,
"e": 6047,
"s": 5645,
"text": "Now let’s start with some programming fun. Today, we will use the data from SPICE’ spk kernels to derive orbital elements and vice versa. We begin with the dwarf planet / asteroid (1) Ceres. Ceres’ home is the asteroid main belt and with a diameter of over 900 km it is the largest representative in this crowded region. Between 2015 and 2018 NASA’s Dawn mission explored this world (see image above)."
},
{
"code": null,
"e": 6164,
"s": 6047,
"text": "What are the orbital elements of Ceres? And can we derive values that are comparable with the literature? Let’s see:"
},
{
"code": null,
"e": 6378,
"s": 6164,
"text": "First, as always, we need to import all necessary Python packages like datetime, numpy and spiceypy. From now on a few additional packages (pathlib, urllib, os) are needed to create an auxiliary download function."
},
{
"code": null,
"e": 7290,
"s": 6378,
"text": "The last tutorials required SPICE kernel files that have been uploaded on my GitHub repository. In future tutorials we need more and more kernels, depending on the tutorial’s task. Since the GitHub storage is limited, we create a helper function to download all future kernels in the _kernels directory. We define the function download_kernel in the following part. First, our function requires 2 input variables, a local storage path (dl_path) and the URL (dl_url) of the kernel (line 5). Line 6 to 18 are the docstring of the function. The URL contains the kernel’s file name. To obtain the name line 23 splits the URL at the “/”. Consequently, the very last entry of the resulting list has the file name. Now, the local download (sub-) directory is created, if it is not existing yet (line 27). If the kernel file is not present in this sub-directory (line 30) the kernel is downloaded and stored there (33)."
},
{
"code": null,
"e": 7614,
"s": 7290,
"text": "For our Ceres project we need to search for the required spk kernels in the NAIF SPICE repository. Some asteroids data are stored under generic_kernels/spk/asteroids. There you find a readme file called aa_summaries.txt. It lists all spk asteroid data and NAIF IDs that are stored in the spk file codes_300ast_20100725.bsp."
},
{
"code": null,
"e": 7857,
"s": 7614,
"text": "But where do this data come from? Are they reliable? And since there are hundred thousands of asteroids: where are the others? To answer this question let’s take a look at the other readme file AAREADME_Asteroids_SPKs.txt. There you can read:"
},
{
"code": null,
"e": 8279,
"s": 7857,
"text": "[...]We have left here a single SPK containing orbits for a set of 300 asteroids, the orbits for which were produced by Jim Baer in 2010 using his own CODES software. Some of these data may also be not very accurate. But the convenience of having data for 300 objects in a single SPK file could be useful for some purposes where high accuracy is not important. Read the *.cmt\" file for details about this collection.[...]"
},
{
"code": null,
"e": 8814,
"s": 8279,
"text": "So the kernel provides us spk information “for some purposes where high accuracy is not important”. Let’s assume that the accuracy is good enough to compare with the literature. Further, the file states that the “*.cmt file” contains more “details about this collection”. We take a look at codes_300ast_20100725.cmt. There you can find details about the underlying code that computed the spk file and other meta information. Doing science means doing literature research and reading and one detail in this cmt file is quite important:"
},
{
"code": null,
"e": 9087,
"s": 8814,
"text": "Usage-------------------------------------------------------- This file should be used together with the DE405 planetary ephemeris since the integration was done using the DE405 ephemeris and with the frames kernel defining the ``ECLIPJ2000_DE405'' frame."
},
{
"code": null,
"e": 9195,
"s": 9087,
"text": "Hold on! Another reference frame called ECLIPJ2000_DE405? How is this frame defined? The files states that:"
},
{
"code": null,
"e": 9333,
"s": 9195,
"text": "This frames kernel defines the Ecliptic and Equinox of the J2000 frame using the DE405 obliquity angle value (84381.412 arcseconds).[...]"
},
{
"code": null,
"e": 9437,
"s": 9333,
"text": "The corresponding frame kernel is defined as (a detailed explanation will follow in a future tutorial):"
},
{
"code": null,
"e": 9937,
"s": 9437,
"text": "\\begindata FRAME_ECLIPJ2000_DE405 = 1900017 FRAME_1900017_NAME = 'ECLIPJ2000_DE405' FRAME_1900017_CLASS = 4 FRAME_1900017_CLASS_ID = 1900017 FRAME_1900017_CENTER = 0 TKFRAME_1900017_SPEC = 'ANGLES' TKFRAME_1900017_RELATIVE = 'J2000' TKFRAME_1900017_ANGLES = ( 0.0, 0.0, -84381.412 ) TKFRAME_1900017_AXES = ( 1, 3, 1 ) TKFRAME_1900017_UNITS = 'ARCSECONDS'"
},
{
"code": null,
"e": 10521,
"s": 9937,
"text": "It appears to be a reference frame that is based on the Equatorial J2000 system and tilts one axis by 84381.412 arcseconds respectively 23,4°. This is the tilt of Earth’s rotation axis w.r.t. the ecliptic plane! Are ECLIPJ2000 and ECLIPJ2000_DE405 the same reference frame? We will find it out in a moment. First, we download the .bsp kernel and the kernel codes_300ast_20100725.tf. This kernel contains also the reference frame, but also the NAIF ID codes with the corresponding names. Since it contains miscellaneous information we create a new sub-directory called _kernels/_misc."
},
{
"code": null,
"e": 10874,
"s": 10521,
"text": "The SPICE meta file contains already the relative path names to the downloaded kernels, as well as the leap seconds kernel and planetary spk kernel. We load the meta file with furnsh. Our computations will be based on today’s date and the current time (line 5, line 8 converts the UTC date-time to a the Ephemeris time using the SPICE function utc2et)."
},
{
"code": null,
"e": 11314,
"s": 10874,
"text": "Let’s take a look at the differences between ECLIPJ2000_DE405 and ECLIPJ2000. We compute in line 4 to 6 a 6x6 transformation matrix that transforms state vectors given in ECLIPJ2000_DE405 to ECLIPJ2000 at the current date-time (SPICE function sxform). Our theory: there is no difference between both systems, so we print (line 10 to 12) the matrix and expect the identity matrix (identity matrix times a vector results in the same vector):"
},
{
"code": null,
"e": 11468,
"s": 11314,
"text": "The output is shown below. It is the identify matrix with 1s along the diagonal and 0s elsewhere. So both reference frame names represent the same frame."
},
{
"code": null,
"e": 11644,
"s": 11468,
"text": "Transformation matrix between ECLIPJ2000_DE405 and ECLIPJ2000[1. 0. 0. 0. 0. 0.][0. 1. 0. 0. 0. 0.][0. 0. 1. 0. 0. 0.][0. 0. 0. 1. 0. 0.][0. 0. 0. 0. 1. 0.][0. 0. 0. 0. 0. 1.]"
},
{
"code": null,
"e": 11887,
"s": 11644,
"text": "Now let’s compute the state vector of Ceres in ECLIPJ2000. According to the .tf file the NAIF ID of Ceres is 2000001. We set the Sun (10) as the observer. Since we do not apply any light time corrections we can simply use the function spkgeo."
},
{
"code": null,
"e": 12289,
"s": 11887,
"text": "To compute the corresponding orbital elements we need to set the gravitational parameter (G) times the mass of the Sun (M). Line 2 extracts the G*M value from the needed kernel using the function bodvcd. The function requires the NAIF ID of the Sun (10), the requested parameter (GM) and the number of expected returns (1). The returned value is stored in an array and needs to be extracted in line 4."
},
{
"code": null,
"e": 12377,
"s": 12289,
"text": "SPICE provides two functions to determine the orbital elements based on a state vector:"
},
{
"code": null,
"e": 12384,
"s": 12377,
"text": "oscelt"
},
{
"code": null,
"e": 12391,
"s": 12384,
"text": "oscltx"
},
{
"code": null,
"e": 12512,
"s": 12391,
"text": "oscltx requires the same input parameters as oscelt and returns the same values + 2 additional parameters. The input is:"
},
{
"code": null,
"e": 12655,
"s": 12512,
"text": "state The state vector of the object (the spatial components x, y, z in km and the corresponding velocity components vx, vy, vz given in km/s)"
},
{
"code": null,
"e": 12677,
"s": 12655,
"text": "et The Ephemeris time"
},
{
"code": null,
"e": 12731,
"s": 12677,
"text": "mu The gravitational parameter (here: G*M of the Sun)"
},
{
"code": null,
"e": 12800,
"s": 12731,
"text": "The output is a single array that contains the following parameters:"
},
{
"code": null,
"e": 12816,
"s": 12800,
"text": "Periapsis in km"
},
{
"code": null,
"e": 12829,
"s": 12816,
"text": "Eccentricity"
},
{
"code": null,
"e": 12868,
"s": 12829,
"text": "Longitude of ascending node in radians"
},
{
"code": null,
"e": 12901,
"s": 12868,
"text": "Argument of periapsis in radians"
},
{
"code": null,
"e": 12927,
"s": 12901,
"text": "Mean anomaly at the epoch"
},
{
"code": null,
"e": 12933,
"s": 12927,
"text": "Epoch"
},
{
"code": null,
"e": 12983,
"s": 12933,
"text": "Gravitational parameter (same value as the input)"
},
{
"code": null,
"e": 13007,
"s": 12983,
"text": "And the oscltx add-ons:"
},
{
"code": null,
"e": 13029,
"s": 13007,
"text": "Semi-major axis in km"
},
{
"code": null,
"e": 13055,
"s": 13029,
"text": "Orbital period in seconds"
},
{
"code": null,
"e": 13366,
"s": 13055,
"text": "Line 2–4 compute the elements and the lines 7 to 24 assign the elements to individual constant names, where km are converted to AU (with the function convrt) and radians are converted to degrees (using the numpy function numpy.degrees). The very last line converts the orbital period given in seconds to years."
},
{
"code": null,
"e": 13849,
"s": 13366,
"text": "What is a reliable source or reference to compare the results with? It’s the (International Astronomical Union) Minor Planet Center (short: MPC). The MPC gathers all information regarding smaller objects of our Solar System (main belt asteroids, comets, Kuiper belt objects and so on). One section provides some general information for dwarf planets: MPC Dwarf Planets. There we find some data for the orbital elements and compare them with our results in the following coding part."
},
{
"code": null,
"e": 13866,
"s": 13849,
"text": "The results are:"
},
{
"code": null,
"e": 14167,
"s": 13866,
"text": "Ceres' Orbital ElementsSemi-major axis in AU: 2.77 (MPC: 2.77)Perihelion in AU: 2.55 (MPC: 2.56)Eccentricity: 0.08 (MPC: 0.08)Inclination in degrees: 10.6 (MPC: 10.6)Long. of. asc. node in degrees: 80.3 (MPC: 80.3)Argument of perih. in degrees: 73.7 (MPC: 73.6)Orbit period in years: 4.61 (MPC: 4.61)"
},
{
"code": null,
"e": 14334,
"s": 14167,
"text": "All in all, the orbital elements from the spk kernel file appear to be feasible. Only minor differences can be seen like a 0.01 AU difference for the semi-major axis."
},
{
"code": null,
"e": 14595,
"s": 14334,
"text": "Can we convert the orbital elements now back to a state vector? Sure! For this purpose SPICE provides a function called conics. The function requires two inputs: an array with the orbital elements and the requested ET. The order of the orbital elements are ..."
},
{
"code": null,
"e": 14611,
"s": 14595,
"text": "Periapsis in km"
},
{
"code": null,
"e": 14624,
"s": 14611,
"text": "Eccentricity"
},
{
"code": null,
"e": 14663,
"s": 14624,
"text": "Longitude of ascending node in radians"
},
{
"code": null,
"e": 14696,
"s": 14663,
"text": "Argument of periapsis in radians"
},
{
"code": null,
"e": 14722,
"s": 14696,
"text": "Mean anomaly at the epoch"
},
{
"code": null,
"e": 14728,
"s": 14722,
"text": "Epoch"
},
{
"code": null,
"e": 14752,
"s": 14728,
"text": "Gravitational parameter"
},
{
"code": null,
"e": 14935,
"s": 14752,
"text": "... so basically the output order of the function oscelt. Line 2 to 9 convert the orbital elements to a state vector and line 11 to 14 print the state vectors from conics and spkgeo."
},
{
"code": null,
"e": 15013,
"s": 14935,
"text": "The output is shown below and you can see that the state vectors are similar!"
},
{
"code": null,
"e": 15309,
"s": 15013,
"text": "State vector of Ceres from the kernel:[ 3.07867363e+08 -3.13068701e+08 -6.66012287e+07 1.19236526e+01 1.14721598e+01 -1.83537545e+00]State vector of Ceres based on the determined orbital elements:[ 3.07867363e+08 -3.13068701e+08 -6.66012287e+07 1.19236526e+01 1.14721598e+01 -1.83537545e+00]"
},
{
"code": null,
"e": 15824,
"s": 15309,
"text": "Have you seen a meteor? A falling star? Probably. One can observe so-called sporadics or stream meteors (like the Perseids in August). These are small dust particles entering the Earth’s atmosphere with high velocities. The atmospheric friction and ionisation cause a nice glowing effect. The source of these particles: comets, asteroids, collisions of minor bodies, etc. But there are also bigger particles that cross our Earth’s path around the Sun (or at least they come quite close): Near-Earth Objects (NEOs)."
},
{
"code": null,
"e": 16049,
"s": 15824,
"text": "On Spaceweather.com you can see a list (bottom of the webpage) where objects are listed that will have a close encounter with Earth. Today (beginning of May 2020) we can see several objects. So let’s pick a larger one, like:"
},
{
"code": null,
"e": 16213,
"s": 16049,
"text": "Asteroid | Date(UT) | Miss Distance | Diameter (m)---------|-------------|---------------|------------- 136795 | 2020-May-21 | 16.1 LD | 892"
},
{
"code": null,
"e": 16455,
"s": 16213,
"text": "That’s a huge asteroid! Almost 1 km in diameter. Such an impact would be devastating for our home planet. But luckily, the minimum distance between Earth and 136795, respectively 1997 BQ is around 16.1 Lunar Distances (LD; 1 LD = 384401 km)."
},
{
"code": null,
"e": 16619,
"s": 16455,
"text": "Before we compute the orbital elements of this object let’s take a quick look whether our planet’s gravitational pull would alter the orbit of the object severely."
},
{
"code": null,
"e": 17379,
"s": 16619,
"text": "One could now develop an N-body numerical simulator that considers all perturbation effects. Or, we could do a first simple approach before we apply any mathematical “overkill”. For this approach we use a simple astrodynamical idea: The Sphere of Influence (SOI). Each object in our Solar System has a SOI: The Earth, the Moon, each asteroid and planet. Within each body’s SOI, the body itself is the major gravitational factor. This means that for simple computations e.g., within Earth’s SOI, we can neglect the gravitational pull of larger objects like the Sun. The SOI is theoretically an ellipsoid, but can be approximated by a sphere. The SOI radius r of a mass m (e.g., the Earth) depends on its semi-major axis a and the larger mass M (e.g., the Sun):"
},
{
"code": null,
"e": 17750,
"s": 17379,
"text": "So first, we can compute the Earth’s SOI to determine whether our planet will alter the orbit or not. We set 1 AU as the semi-major axis. Line 10 converts 1 AU to km (SPICE function convrt). In line 13 and 14 we extract the G*M value of Earth using bodvcd. Finally, line 17 computes Earth’s SOI in km. We set 1 LD as 384401 km in line 20 and print the result in line 22."
},
{
"code": null,
"e": 17884,
"s": 17750,
"text": "Earth’s SOI is around 2.4 LD. Consequently, the orbit of 1997 BQ should not be altered to much by the encounter with our home planet."
},
{
"code": null,
"e": 17927,
"s": 17884,
"text": "SOI of the Earth in LD: 2.4054224328225597"
},
{
"code": null,
"e": 18296,
"s": 17927,
"text": "JPL’s Small Body Database provides the orbital elements at a certain epoch. However, we need to consider the provided errors (1 sigma deviation) of the values. In science, one has to round values, results or measurements based on the first 2 significant digits of the measurement error. E.g.,: x = 123.98765 with an error of xerr = 0.035 becomes x = 123.987 +/- 0.035."
},
{
"code": null,
"e": 18766,
"s": 18296,
"text": "The JPL database provides several digits for the error. So we build a small lambda function that rounds the values based on the position of the first 2 error digits. First, the log10 value of the error is taken. Example: 0.035 becomes -1.4559. Then the floor function is applied: -1.4559 becomes -2. We multiply the value with -1, and add +1 to the end. The result is 3. And that is what we need: we want to round 123.98765 at the 3rd position based on the error 0.035!"
},
{
"code": null,
"e": 19016,
"s": 18766,
"text": "Let’s define all orbital elements with the data from the database. Please note: The database provides the epoch 2459000.5 (Julian Date). Thanks to the mighty utc2et function, this can easily be converted to ET using the string format “2459000.5 JD”."
},
{
"code": null,
"e": 19272,
"s": 19016,
"text": "Now we can compute the state vector of the asteroid after we create an array with orbital elements (line 2 to 9). We use the function conics to determine the state vector for the current date-time (line 12). Finally, the results are printed in line 14+15."
},
{
"code": null,
"e": 19438,
"s": 19272,
"text": "Current state vector of 1997BQ in km and km/s (2020-05-08T15:29:48):[-1.01302335e+08 -9.80403762e+07 2.92324589e+06 2.10287249e+01 -2.97600309e+01 -6.83829911e+00]"
},
{
"code": null,
"e": 19866,
"s": 19438,
"text": "What is the current distance between 1997 BQ and the Earth? To find out, we compute Earth’s state vector, too (using spkgeo). The NAIF ID for our planet is 399 and the observer is the Sun (10). We use the same ET (DATETIME_ET) and set the reference frame ECLIPJ2000. The spatial components of both state vectors are then used to determine the length of the resulting vector between Earth and 1997 BQ (line 8+9, function vnorm)."
},
{
"code": null,
"e": 19917,
"s": 19866,
"text": "For our timestamp the distance is around 38.69 LD."
},
{
"code": null,
"e": 20009,
"s": 19917,
"text": "Current distance between the Earth and 1997BQ in LD (2020-05-08T15:29:48):38.69205689796575"
},
{
"code": null,
"e": 20546,
"s": 20009,
"text": "That was a lot of content to digest! Take your time and use the provided Jupyter Notebook and Python script from my GitHub repository to walk through this tutorial. Reference frames and orbital mechanics as shown in the last two tutorials are used in the future tutorials. Do not worry. The next tutorials will be smaller to give you some time to get familiar with everything. There are a lot of Python functions, concepts and technical terms that need to be understand. If you need support or have any questions do not hesitate to ask."
},
{
"code": null,
"e": 20553,
"s": 20546,
"text": "Thomas"
},
{
"code": null,
"e": 20682,
"s": 20553,
"text": "Albin, T. (2019). Machine learning and monte carlo based data analysis methods in cosmic dust research. University of Stuttgart."
},
{
"code": null,
"e": 20859,
"s": 20682,
"text": "Meech, K., Weryk, R., Micheli, M. et al. A brief visit from a red and extremely elongated interstellar asteroid. Nature 552, 378–381 (2017). https://doi.org/10.1038/nature25020"
},
{
"code": null,
"e": 21053,
"s": 20859,
"text": "Micheli, M., Farnocchia, D., Meech, K.J. et al. Non-gravitational acceleration in the trajectory of 1I/2017 U1 (‘Oumuamua). Nature 559, 223–226 (2018). https://doi.org/10.1038/s41586-018-0254-4"
}
] |
Extracting MAC address using Python | We know that the MAC address is a hardware address which means it is unique for the network card installed on our PC. It is always unique that means no two devices on a local network could have the same MAC addresses.
The main purpose of MAC address is to provide a unique hardware address or physical address for every node on a local area network (LAN) or other networks. A node means a point at which a computer or other device (e.g. a printer or router) will remain connected to the network.
Using uuid.getnode()
In this example getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module.
Live Demo
import uuid
print (hex(uuid.getnode()))
0x242ac110002L
Using getnode() + format() [ This is for better formatting ]
import uuid
# after each 2 digits, join elements of getnode().
print ("The formatted MAC address is : ", end="")
print (':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)
for elements in range(0,2*6,2)][::-1]))
The formatted MAC address is : 3e:f8:e2:8b:2c:b3
Using getnode() + findall() + re()[ This is for reducing complexity]
import re, uuid
# after each 2 digits, join elements of getnode().
# using regex expression
print ("The MAC address in expressed in formatted and less complex way : ", end="")
print (':'.join(re.findall('..', '%012x' % uuid.getnode())))
The MAC address in expressed in formatted and less complex way : 18:5e:0f:d4:f8:b3 | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "We know that the MAC address is a hardware address which means it is unique for the network card installed on our PC. It is always unique that means no two devices on a local network could have the same MAC addresses."
},
{
"code": null,
"e": 1558,
"s": 1280,
"text": "The main purpose of MAC address is to provide a unique hardware address or physical address for every node on a local area network (LAN) or other networks. A node means a point at which a computer or other device (e.g. a printer or router) will remain connected to the network."
},
{
"code": null,
"e": 1579,
"s": 1558,
"text": "Using uuid.getnode()"
},
{
"code": null,
"e": 1702,
"s": 1579,
"text": "In this example getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module."
},
{
"code": null,
"e": 1713,
"s": 1702,
"text": " Live Demo"
},
{
"code": null,
"e": 1753,
"s": 1713,
"text": "import uuid\nprint (hex(uuid.getnode()))"
},
{
"code": null,
"e": 1769,
"s": 1753,
"text": "0x242ac110002L\n"
},
{
"code": null,
"e": 1830,
"s": 1769,
"text": "Using getnode() + format() [ This is for better formatting ]"
},
{
"code": null,
"e": 2053,
"s": 1830,
"text": "import uuid\n# after each 2 digits, join elements of getnode().\nprint (\"The formatted MAC address is : \", end=\"\")\nprint (':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)\nfor elements in range(0,2*6,2)][::-1]))"
},
{
"code": null,
"e": 2103,
"s": 2053,
"text": "The formatted MAC address is : 3e:f8:e2:8b:2c:b3\n"
},
{
"code": null,
"e": 2172,
"s": 2103,
"text": "Using getnode() + findall() + re()[ This is for reducing complexity]"
},
{
"code": null,
"e": 2409,
"s": 2172,
"text": "import re, uuid\n# after each 2 digits, join elements of getnode().\n# using regex expression\nprint (\"The MAC address in expressed in formatted and less complex way : \", end=\"\")\nprint (':'.join(re.findall('..', '%012x' % uuid.getnode())))"
},
{
"code": null,
"e": 2493,
"s": 2409,
"text": "The MAC address in expressed in formatted and less complex way : 18:5e:0f:d4:f8:b3\n"
}
] |
A Graphic Guide to Implementing PPO for Atari Games | by DarylRodrigo | Towards Data Science | Written by Daryl and Daniel
Learning how Proximal Policy Optimisation (PPO) works and writing a functioning version is hard. There are many places where this can go wrong — from misunderstanding the maths and mismatching tensors to having a logical error in the implementation. It took a friend and me around a month of work to get to a fully running PPO, where we successfully implemented the algorithm and were confident that we understood how it operated. This guide summarises all the areas where we struggled building our final algorithm and intuitions we developed. This blog aims to cover the basic theory of PPO, how we decided to implement our version, working with tensor shapes, testing, and using the recorded metrics to debug what we built. I hope you enjoy it!
Because this blog post intends to cover PPO, it will assume some prior knowledge of basic reinforcement learning (RL). In particular the basic setup of an RL problem, some notion on how an actor-critic model works, concepts behind the Bellman equation and a vague understanding of what policy gradient methods are.
Github Repo — [link]
As a recap — PPO belongs to a class of algorithms called policy gradients (PG). The fundamental idea is to update the policy directly to make the probability of taking actions which provide a larger future reward more likely. This is done by running the algorithm in an environment and collecting the state change based on an agent’s actions — a collection of these interactions is called a trajectory. Once one or more trajectories have been collected, the algorithm will look at each step and check whether the chosen action led to a positive or negative reward and update the policy accordingly.
Trajectories are sampled by interacting with the environment step by step. To take a single step an agent selects an action and passes it into the environment.
PG algorithms decide on which action to take by accepting an input (the state or observation of an environment) and then, for a discrete action space, output a probability for each possible action. A neural network typically calculates this probability. The neural network’s output is dictated by its weights and is typically written as π_θ, where π denotes the policy and θ the weights of the network (important for the next part).
To select an action, the agent samples from the distribution of probabilities given by the neural network (called logits) — this action is then used to provide the environment with its next input. For example, in Figure 1.2, the action right has a 50% chance of being selected (left 12.5%, up 25% and down 12.5%). As a consequence of selecting an action from probabilities, exploration is inherently present in PG algorithms as the randomness in actions comes from the selection probabilities. As the agent becomes more sure of what the correct action is, exploration will decrease as the probabilities for incorrect actions decrease. Once the action has been taken, all metrics are stored for later use in training (observation, action, log action probabilities, value, reward, done).
Before diving into PPO, it is useful to breeze over the maths for PG algorithms from a high level to get a complete image of what the algorithm will be doing. However, since this blog post is about implementing PPO, we’ll have to skip over the details of how the derivation behind calculating the loss and updating the agent works (also, if you’re not interested in the maths behind PG, then feel free to skip the next 3 headings).
Updating the Policy: The building block of any PG algorithm is the formula on how a network is updated. The update formula in Figure 1.3 shows that the new weights of a network [1] are updated to the current weights [2] + the gradient of the current network given a specific state-action pair [4] times the learning rate [3]. This is the underpinning formula of how to update the network weights. Intuitively the gradient is the direction (+/-) of the weights in which the change of the policy will make taken actions more likely in a given state (reverse them to make them less likely).
A full explanation of how policy gradient updates work from a mathematical standpoint there is no better place than David Silvers lecture.
So how do we calculate this gradient? Thankfully, all the most common deep learning frameworks will keep a computational graph of information passing through a neural network and keep a record of the gradient part of the network.
Adjusting Weight Direction and Amount: With the update equation we know what direction the “gradient” of a specific state-action pair is — that is to say, to make that action (in a specific state) more likely by changing the neural networks weights in the direction of the gradient. Of course, we do not want to make every action more likely, if a bad result was obtained we want to reduce the probability of taking that action. This is what the advantage function [1] embodies — how much better or worse an action was than we expected. If a action led to a scenario where we are better off than before (positive advantage), the weights are change in the gradients direction, effectively making it more likely that that action is chosen again. If it’s worse, we decrease the weights in the direction of the gradient, making it less lightly
Another consideration is the amount weights are updated by, if just the advantage times the gradient were to be updated, there would be very aggressive updates (great explanation of why here). So in order to counteract this, we divide the update by the output of the policy [2], this is called importance sampling (how much weight to place on a particular update).
For example, if the action output was [2,3,5,1] and the action with value 5 (action 3) was chosen, the gradient would be divided by 5 to reduce the amount the gradient is updated. This is to stop action 3 quickly increasing in value, and hence and no other value getting the chance of being chosen (as it is done on a probability basis and if we have [2,3,100,1] the other actions are unlikely to be chosen), even if they might yield a higher return in the long run.
Chaining it up: This leaves the last step to the update rule, which comes from using the magic of the chain rule. Using this we can substitute out our partial derivative fraction with the gradient log of the action which was taken. This part is important because it’s what builds the foundation of PG and PPO algorithms.
Again, this is not intended to be a full explanation on the mathematical theory behind policy gradient algorithms but rather a quick review/recap on where the log values are coming from.
Visualising the update: When the theory is placed in practice it would look something as Figure 1.6 describes. First, the trajectory is run [step 1], and all relevant values are saved (log probabilities, value and reward — amongst other things). Once the trajectories have been completed, the discounted returns and advantages can be calculated [step 2] (great article here explaining what advantages are, but as a reminder, the advantages = discounted_return - expected_return where expected return is calculated by the critic as value). [step 3] Next the loss of each step is calculated by looking at the log probabilities and multiplying it by the advantage, just as shown in Figure 1.5. [step 4] Lastly we take the average of all these losses and do a backwards pass with gradient descent.
Original PPO paper — link
With policy gradient methods, once a few trajectories have been collected a model will be updated a number times using the same trajectories in order to learn from the new data that has been collected. Remember that the size of this update is determined by both the magnitude of the advantage as well as the importance sample (which is expressed as the log probability of the action).
PPO adds an additional factor which is the probability ratio to prevent large updates from occurring. This is defined as the difference between the original action log probability and the new model’s action log probability.
Problem: The problem with PG algorithms is that when an update is performed, its magnitude by which the policy change can happen (i.e. the weights change) can push the policy into a region that when another gradient descent is performed, all direction are essentially the same and the peak of the reward is missed. This is demonstrated in Figure 1.8 — a single update has missed the peak of the reward, and now when gradient descent is performed on a new trajectory it’s hard to say whether “left” of “right” movement will lead to a better policy loss. This causes the update to destroy the policy to an unrecoverable extent.
Solution: The PPO paper’s solution is to create a ratio between the original action log probability and the new model’s action log probability. If that ratio becomes too large or too small, it will be clipped to +/- a set amount (typically 0.2). This will prevent the policy from taking too large of an update step; this can be seen in Figure 1.9.
Mathematically this is expressed using a clipping function, also known as a surrogate function, in the PPO paper:
If you’d like to understand this in more detail, Arxiv Insights has an insanely good YouTube explanation of how PPO works from a theoretical standpoint.
Visual implementation of flow: From a practical standpoint following happens;
First, we collect a few trajectories using our initial model (model_1), making sure to save the action log probability for the actions taken. Using our trajectory, the initial model gets updated to model_2 and is now different from the original.
Then with the same states that we collected from the trajectories [3], the new log probabilities are calculated [2] (these will be different to the initial model as the model has changed).
The ratio between the new model and the old model’s action log probabilities is then used to calculate the scalar by which the new policy should be updated. Ratios are calculated on a per-step basis. If the ratio is too large or too small, it will be clipped according to the surrogate function.
Hopefully, the theory section was adequate to give some intuition about how an agent takes actions, the model is updated, why PPO works and why the clipping and probability ratio are required. The following section explains how we implemented PPO for ourselves — some of it might be obvious some not. However, it’s probably helpful to go through everything if you want to fully understand our implementation, as there will be differences. Throughout this section, there will be references made back to our code, so it might be helpful to split your screen in half, with one section having the blog post open and the other section the code, having said that, of course, read through this as works best for yourself!
As an overview there are three main classes and a file which runs the whole system:
Model.py [class] - This contains the logic for the agent to both, act on given inputs and learn from data collected from trajectories.
Memory.py [class] - This contains all the data from the trajectories and calculates the advantages. It also allows the agent to sample random sections of the trajectory to update the agent in batches.
Config.py [class] - This contains all the settings required in RL & PPO, such as learning rate, number of steps to take, and hyperparameters like epsilon for the clipping size.
Utils.py [File] - This is the main file which runs the sampling and training loop.
As you might be able to tell from the flow chart in Figure 2.1, the way an agent is trained is essentially an expansion of the overview in Figure 1.1. First, the program initialises all our variables, and then the algorithm runs in two distinct stages, collecting trajectories and updating the agent from the collected data.
Collecting Trajectories: Trajectories are collected by playing in a gym environment; the agent takes actions in the simulation based on its observations. Whilst this loop is active, the individual steps are saved in the agent’s memory.
Updating the Agent: Once enough steps are taken, the discounted returns and advantages are calculated — the agent then samples all the steps from the “memory” to calculate the losses and update the agent (all captured data is trained over). Once all the updates are performed, the loop starts at the beginning again.
To start with, all the components used in the experiment need to be initialised. The main pieces of this are:
The gym environment
The agent, which includes adding the model and the memory
Logging our experiments (we use weights and biases)
The environments which agents train in is typically created with OpenAI gym, a framework that creates a simulation environment for physics tasks and Atari games. Actions are entered which the environment reacts to — this change is then returned to the agent as a set of observations. With this also comes rewards and whether the game has finished letting the agent know whether or not their actions were “good” or “bad”.
When human players look at an Atari game, we see the RGB colours which make up the image and a steady change in frames as we play the game. We could feed every frame directly into our agent; this would be portrayed as a tensor of 160,192,3, representing the game's dimensions and RGB pixels. However, in typical Atari game implementations (and those done in the original paper) a few tricks are used to train more effectively, which we've included in the env.py file (this was heavily influenced and partly copied from Costa's CleanRL implementation).
Changing the game styles:
The first few tricks pertain to changing how the game fundamentally operates to help the agents along a little bit.
Episodic Life Env (envs.py:61) — This makes sure that the episode is only finished when all lives are lost, rather than when one. As a result, discounted rewards will get carried through the whole game rather than individual lives — this is important as it will allow the agent to get further into the game.
NoopResetEnv (envs.py:12) — As a technicality in the Atari engine, the game will always be the same if you start playing from the start. To get random behaviour in the game engine (rather than the same version every time), a random set of actions are taken to set the game in a pseudo-random state [paper]. This is critical to help the agent generalise its learnings.
FireResetEnv (envs.py:41) — If the game only starts when the fire command is pressed it will automatically hit fire when is initialised, this is so that the agent doesn’t have to learn how to start the game.
Max and Skip (envs.py:97) — Any action taken by the agent will be applied to four-time steps within the game. The max of each pixel for all the produced frames will be returned — similarly to max pooling. The reward for those frames will also be added up. The short of the long is that this is all to avoid flickering experienced when playing the game [Better explanation].
Clip Reward (envs.py:125) — Typically speaking in RL, agents train best if rewards are kept in a “reasonable range” (around +/- 1), this is to avoid too large updates when calculating the discounted returns. Clip rewards cut the rewards to +/- 1 for this reason.
Augmenting the Atari observation output:
Frame Stack (envs.py:187)- The agent is passed a stack of frames, representing four time steps in the actual game. This is so that the agent can have a sense of movement. For example, in Breakout, the ball might be in 4 different positions indicating movement in a particular direction.
WrapFrame (envs.py:134) — This is a custom method that reframes the Atari gym environment’s output. After all the augmentations have taken place, a tensor of (4, 84, 84) is produced - with WrapFrame, this is then converted to (84, 84, 4) for every frame. This is so that it is compatible with the CNN head from our agent.
What this ends up looking like, in terms of tensor sizes for a single environment, is the following:
All these techniques of augmenting the output and altering gameplay are designed for the agent to learn more effectively from the Atari game environment. It can be thought of as data augmentation in machine vision tasks.
Implementation: The augmentations are implemented in env.py, where they are grouped in a thunk function called make_env(env_id, seed). This function can be invoked at any point, specifying the seed and game type to return an environment; it is implemented this way to help when creating multiple environments.
Note: One might have noticed that there is an Augment input block in Figure 2.2, which adds a dimension to the input of the agent, this is present because the PyTorch 2D CNN block expects a batch to be entered. In our case, this is a batch of one.
We chose to implement multiple environments to take advantage of our home DL machines’ extra CPU and GPU. This sped up training and was a good learning exercise on how multiple environments worked.
When multiple environments are added, all outputs from the gym environment gain an extra dimension n, where n is the number of environments. Our agent’s input, however, is not any different. That is because we already augmented the input in the single environment to have 4 dimensions (as seen in Figure 2.2.).
Multiple environments are implemented is in our Config.py, here the environments are initialised by wrapping the make_env function in the Open Baseline's DummyVecEnv, as seen below.
envs = VecPyTorch( DummyVecEnv( [make_env(env_id, self.seed+i, i) for i in range(self.num_env)] ), self.device)
This function expects “a list of functions that will create the environments (each callable returns a Gym.Env instance when called)”, which is why make_env returns a thunk function that creates a gym-env rather than the gym-env itself. The VecPyTorch is essentially based on VecEnv, which "abstracts asynchronous vectorised environments". It's an easier way of interacting with the vectorised environments.
Multiple environments take what we did for single environments and vectorise them in an easy to handle manner. All other game augmentations and reshaping of the environments happen the same way as they did in single environments.
The Atari PPO agent is created from a base class which (Figure 2.4), with the hyperparameters, initialise two key sections:
The Model - This houses the CNN model, we’ve configured so that this is split into a “head” “actor”, and “critic. The head pre-processes incoming data, which the actor and critic then use to calculate their respective values.
The Memory - There is a deep dive on this topic later, but basically the memory stores state transitions collected during the acting phase. The initialisation determines the shape and size of the memory, and consequently, how long roll-outs will be.
With these two class instances the agent is able to perform 3 essential functions:
Act: This takes in the observations (of multiple environments), and provides the corresponding actions and log probabilities of those actions.
AddToMemory: Once an action has been taken, all the data for that step must be stored for later use. That is what the AddToMemory function does; it stores the information in PyTorch tensors.
Learn: This will be explored further in a later section — but essentially, this will take processed data from memory and update the model accordingly.
The Model
The model is a vanilla actor-critic network. A CNN head takes in the frames of the game as input, with the addition of all pixels being scaled down by 255, this is to ensure that the input range is between 0 and 1. The output from the CNN is then passed into two fully connected layers. The first layer outputs a single value acting as the critic, and then the second network outputs the number of actions available in the game environment acting as the actor.
The class is set up so that an act method (models.py:76) can be invoked to return the action, log probabilities and entropy produced by the actor, as well as the value predicted by the critic. To obtain the action, the logits from the actor are immediately sampled (models.py:79).
Initialising Network Weights
One last important factor is to ensure that that each layer has been initialised. A generic function called layer_init surrounds every layer in the network, this is to avoid vanishing or exploding gradients (great post by explaining how this works here).
The decision to make a memory class (rather than just storing the individual variables as PyTorch arrays) in part stemmed the Reinforcement Learning Discussion Discord (shout-out to the community who has been incredible in facilitating discussions), where we were discussing tests for core functionality. RL algorithms notoriously fail silently, meaning that they will either not throw an error but never learn, or even worse, learn but not to its maximum potential. This is a huge problem because it makes debugging incredibly hard and requires many, many experiments; and when using simple environments such as CartPole-v1 might never surface. This is why we decided to create a class that stored the saved trajectories, but whose responsibility it also is to calculate the advantages, discounted returns and sample the correct data from memory. This way, we could write tests for each individual function (the tests can be found in /tests/test_memory.py) to ensure that the output is exactly what was expected. It was also instrumental in validating our understanding of advantages and discounted returns.
The memory itself (as seen in Figure 2.6) has three key aspects:
Saved Variables — Trajectories are stored to memory here. The data is stored in predefined PyTorch tensors, as this avoids having to convert arrays to tensors etc.
Calculating Advantages — how this is done will be explained in the next section; the important part is that it calculates the advantages and discounted returns based on the trajectories sampled.
Sampling from Memory — Because all of our data is in order and still in the format of our n number of environments, this function essentially squashes all our trajectories into on long tensor and then samples random sections to train on (the implementation is explained in more detail in the Updating Model section).
The initialisation of the memory dictates it’s shape and size and requires various arguments. This includes the number of environments and the environment itself to get the observation and action space. To will determine how many “steps” are taken it also requires the size of the memory. Lastly, hyperparameters such as gamma are also needed.
Lastly, we initialise W&B — this has been a key tool for us to understand how our agents are performing. It has allowed Daniel and myself to analyse data and run experiments on our own machines and making the results available for both of us, all whilst working remotely.
Having some logging tool has been critical in understanding where mistakes were being made and what affect different hyperparameters have on the model. In a later section, we’ll dig into how various metrics helped us debug our work.
The first stage in training the PPO agent is to collect trajectories — this happens as seen in Figure 2.7 after the agent and environment have been initialised. The agent takes actions based on the observations from the environment, which is then used to take the next step. The sequence of states and actions are then finally saved to the memory for the training phase.
The action is taken by with act function on the agent [Models.py:109].
class ActorCritic(nn.Module): # ... def act(self, x, action=None): values = self.critic(self.forward(x)) logits = self.actor(self.forward(x)) probabilities = Categorical(logits=logits) if action is None: action = probabilities.sample() return action, probabilities.log_prob(action), values, probabilities.entropy()
To act, the model receives observations from the gym environment (x). The observations then pass through the critic network which returns the value (what the value of that state is) and then the actor-network, which returns the logits (the output of the neural network).
The value is returned as-is. However, we want to convert our logits into a probability distribution on which we can then sample an action. This is done with the Categorical function of PyTorch — this function turns our logits into a distribution proportional to the logits, summing up to one. The benefit of the categorical class is that the class can also sample an action from the distribution, calculate the log probability of action and the entropy (entropy will be further explained in a later section).
Saving trajectories is fairly intuitive, but is useful to have a visual representation of how the rewards, observations and done’s come out of the gym environment. For each step in an environment, 3 variables of different dimensions are returned (observation, reward and done — shown in Figure 2.8).
Every interaction the agent has with the environment (acting on multiple environments) returns an observation, reward, and done. In the example of Figure 2.8, the first step shows no reward, and the episode has not terminated yet, this is assumed to be the case for every step after that unless indicated otherwise. This illustrates that the data collected is appended into the memory as entire steps across multiple environments, indicated by the blue box. This means that what is being saved into the memory is:
Observations (n, 80, 80, 4)
Rewards (n, 1)
dones (n, 1)
And will then be saved in the memory in a tensor of dimensions:
Observations (x, n, 80, 80, 4)
Rewards (x, n, 1)
dones (x, n, 1)
Where x is the number of steps, this implies that the “global” number of steps which the agent trains on will, in reality, be x times n, as we have x steps for n number of environments.
The second stage in our PPO is to learn from our collected trajectories — this is initiated by the learn function in Models.py and invoked by the training loop in util.py:L113. When this starts, the advantages are calculated first, this is important to do as all trajectories are required to remain in sequence to calculate the correct discounted return. Once this is finished, we can sample from memory at random, calculate our losses and update the model. Updating over the trajectories happens a set number of times, dictated by a hyper-parameter. Once completed, the old model is replaced with the updated one and the process start over again, but this time with a (hopefully) better performance. This process can be seen in Figure 2.9.
The Advantage is defined as the expected return minus the actual return — this indicates how much better or worse the model performed than anticipated. Calculating these advantages occurs in two steps — first, the discounted returns need to be computed. The expected values (calculated by the critic) are then subtracted from the discounted returns to obtain the advantage.
In case you’re not familiar with discounted returns, this is a great video, but essentially it takes the current reward + the value of the next state times a discount factor (gamma) as per Figure 2.10 (G is the discounted returns).
In order to calculate the discounted returns, we cannot start at the beginning of the trajectory but rather have to start at the end. This is because we need to iteratively calculate what the value of the next state is. This presents a problem at the very last state as there is no next value, which is why the function also takes last_value and last_done, which are used in the very first calculation of the discounted returns (in the case of Figure 2.11 it's -0.5 as the last value and the episode not being done). In many books, you might see this as n-step bootstrapping. We do not (necessarily) wait for the whole episode to finish but rather estimate after n-steps what the value of that state would be if the episode were to finish.
As an example of what might happen, in Figure 2.11 assumes the trajectories have already been collected (step 1) and then iteratively calculates the discounted return backwards.
This logic is implemented in our Memory.pyclass:
def calculate_discounted_returns(self, last_value, next_done): with torch.no_grad(): # Create empty discounted returns array self.discounted_returns = torch.zeros((self.size, self.num_envs)).to(self.device) for t in reversed(range(self.size)): # If first loop if t == self.size - 1: next_non_terminal = 1.0 - torch.FloatTensor(next_done).reshape(-1).to(self.device) next_return = last_value.reshape(-1).to(self.device) else: next_non_terminal = 1.0 - self.dones[t+1] next_return = self.discounted_returns[t+1] self.discounted_returns[t] = self.rewards[t] + self.gamma * next_non_terminal * next_return
The reverse for loop iterates over the collected trajectories in reverse order to calculate the discounted returns. As in Figure 2.11, the first calculation uses the last predicted value, outputted by the critic, all other cases will have the previous discounted return available. The new discounted return is the reward + gamma * the previous discounted return. next_non_terminal is used to check if the discounting should be set to 0 because the episode ended. Finally to get the advantages the memory simply takes the discounted_returns and subtracts the collected values at the corresponding time steps.
Calculating the discounted returns can be a headache, and making sure that they are correctly calculated for the many different scenarios is even harder. It’s easy to make a mistake, in some cases meaning the algorithm will still train but doesn’t perform as well as it could. To really check all the edge cases it is suggested to write test cases and run the calculations against them. For our implementation, this can be found in /tests/test_memory.py.
Fetching the data
To update the model, the memory is sampled first — this is done by extracting mini-batches (random subsection) from the trajectory saved in memory. This is done with the get_mini_batch_idxs function. The function creates an index for every entry in the memory and randomly assigns them into the arrays for the mini-batch; for example, this could return
[ [1013,456, ... 147,328], ..., [295, 1937, ..., 49,846]]
The first element in the mini-batch array([1013,456, ... 147,328]) is then passed into the sample function, which expects an array of indexes to pull out of the memory. For every index in that array the following values are returned:
prev_states
prev_actions
prev_log_probs
discounted_returns
advantage
prev_values
Policy Loss
The loss function consists of the policy and value loss. As a reminder, it might be worth to check out Figure 1.11 to remember the method of updating the PPO model.
First, the two surrogate functions (clipping of the ratios) need to be calculated. The surrogate function requires the probability ratios — this uses the updated model’s log probabilities and the current model’s log probabilities (used to collect the trajectory). This is the primary reason the action and observations were saved — the observations can now be passed into the updated model and calculate what new log probabilities are outputted given the action taken during the trajectory.
Once the ratios are calculated the surrogate function is relatively straight forward, we simply multiply through by the advantage (calculated in the previous section) and use the clamp function to limit this by 1 + ε and 1- ε. The loss is then the minimum of the two.
# Grab sample from memoryprev_states, prev_actions, prev_log_probs, discounted_returns, advantage, prev_values = self.mem.sample(mini_batch_idx)# find ratiosactions, log_probs, _, entropy = self.model.act(prev_states, prev_actions)ratio = torch.exp(log_probs - prev_log_probs.detach())# calculate surrogatessurrogate_1 = advantages * ratiosurrogate_2 = advantages * torch.clamp(ratio, 1-self.epsilon, 1+self.epsilon)# Policy Gradient Losspg_loss = -torch.min(surrogate_1, surrogate_2).mean()
Value Loss
To calculate the value loss we take the mean squared error of what we thought the value of that observation was and what the discounted returns actually were.
# Grab sample from memoryprev_states, prev_actions, prev_log_probs, discounted_returns, advantage, prev_values = self.mem.sample(mini_batch_idx)# Calculate values from new modelnew_values = self.model.get_values(prev_states).view(-1)# Generate lossvalue_loss = F.MSE(new_values, discounted_returns)
Updating
Updating is also very standard, we simply backpropagate all the loss added together and include the entropy.
# Lossloss = pg_loss + value_loss - self.entropy_beta*entropy_loss# calculate gradientself.optimiser.zero_grad()loss.backward()# Clip grad to avoid massive updatesnn.utils.clip_grad_norm_(self.model.parameters(), 0.5)self.optimiser.step()
This process gets repeated will the model has been updated n times for the whole memory set. Then we repeat the whole process over again and hope the model converges!
To run our the environment navigate to the PPO folder and run:
python main_atari.py
To get weights and biases set up you will need to do your own configuration and register the project if you do not have this, tensorboard will still record all of the experiments data.
When running the experiment the key values which are measured are:
Episode Reward
This is the most obvious metric to record, it tells us how well an agent is performing at a given step.
Learning Rate
The learning rate is logged in case this is changed throughout the life cycle of the experiment. For this experiment, it will remain constant, however, annealing is required to get state of the art results. Another blog post will cover why and how this works.
Policy Loss
The policy loss is generally agreed to be a difficult metric to draw conclusions from, depending on whether the advantages are normalised, or if learning rate annealing is used this will look different.
Value Loss
This is defined as the mean squared error between what the discounted return was and what the critic thought, it shows how well the critic is predicting the value of a state. Typically this sits quite low, however, when an agent performs much better or worse than expected the value loss will shoot up indicated that the critic is updating how it thinks about this state.
Entropy
Entropy in RL is the predictability of whether an action is taken (so how certain we are that in a given state we might go left); because the actions are sampled from a distribution, if one those outputs are very high that means it’s fairly certain what action will be taken. Conversely, if all the probabilities sit at the same level, it’s going to be hard to predict which action is taken next (great article that goes more in-depth).
From an insight perspective, what this means is that if the entropy is very high, the agent doesn’t really know what the right action is and when it’s lower is start be more certain about its actions. This is why, in general, the entropy will be going down.
KL Divergence
When calculating which action to take in with policy gradient methods, the actions are going to be represented as a set of probabilities — the log of these probabilities is then used to calculate the loss of our model.
When you update the model using the log probabilities in the “learning” phase, typically you would clone your model and update that new model. Once your model has gone through all the updates, it will differ slightly from the original model.
The KL divergence is a measure of how different the log probabilities from the original model are to the new one. The higher the KL divergence is the more the model has changed. As a rule of thumb, a KL divergence which sits around +/- 0.03 from 0 means that the model is updating nicely, whereas a high KL divergence can indicate that the model is taking too big of an update step, this can cause the model to not converge. This is what makes KL divergence such a useful metric to observe.
It’s hard to pin down what the exact problems in an experiment are when looking at metrics, especially because it’s hard to work out whether or not something just isn’t converging or if there is something wrong with the algorithm. One thing that has helped us tremendously is looking for how “on average” performance looks on different metrics. For example from Figure 3.1 it might look like the agent is learning, and then just cannot converge — but when also looking at the value loss (so the MSE between the discounted returns and what the critic thought), it’s clear that the critic was behaving very suspiciously, the value loss is all over the place and it’s frequently far too high. On closer inspection, we found that the calculation for value loss had a wrong variable name in it.
When we were building our agent — Costa’s CleanRL metrics were of great help to us.
Our Metrics
After much work, we managed to get a reward of around 50. Clearly not ideal, there is still a lot to work at, but this will require adding some additional tricks to the algorithm, it’s also very possible that after more training it will reach ~400.
When creating your own PPO, it might be helpful to have these metrics as reference.
Visual display of agents performing at various stages of training.
Implementing PPO from scratch has been an interesting challenge which has certainly stretched my understanding of RL and patients to its limits. What has really helped is having somebody to work with, this was both a motivation as well as helpful to bounce ideas off when either of us got stuck.
From our experiments, it’s clear that running just a vanilla PPO algorithm will not achieve top-level performance. As such, we have also implemented PPO as per the baselines specifications which reach a reward of 400. I aim to post a blog post on the modifications required to obtain the result soon!
Daniel and I would like to thank Costa Huang for all his help in explaining how his PPO implementation worked. Without his help, it would surely have been a much longer road. | [
{
"code": null,
"e": 199,
"s": 171,
"text": "Written by Daryl and Daniel"
},
{
"code": null,
"e": 946,
"s": 199,
"text": "Learning how Proximal Policy Optimisation (PPO) works and writing a functioning version is hard. There are many places where this can go wrong — from misunderstanding the maths and mismatching tensors to having a logical error in the implementation. It took a friend and me around a month of work to get to a fully running PPO, where we successfully implemented the algorithm and were confident that we understood how it operated. This guide summarises all the areas where we struggled building our final algorithm and intuitions we developed. This blog aims to cover the basic theory of PPO, how we decided to implement our version, working with tensor shapes, testing, and using the recorded metrics to debug what we built. I hope you enjoy it!"
},
{
"code": null,
"e": 1261,
"s": 946,
"text": "Because this blog post intends to cover PPO, it will assume some prior knowledge of basic reinforcement learning (RL). In particular the basic setup of an RL problem, some notion on how an actor-critic model works, concepts behind the Bellman equation and a vague understanding of what policy gradient methods are."
},
{
"code": null,
"e": 1282,
"s": 1261,
"text": "Github Repo — [link]"
},
{
"code": null,
"e": 1881,
"s": 1282,
"text": "As a recap — PPO belongs to a class of algorithms called policy gradients (PG). The fundamental idea is to update the policy directly to make the probability of taking actions which provide a larger future reward more likely. This is done by running the algorithm in an environment and collecting the state change based on an agent’s actions — a collection of these interactions is called a trajectory. Once one or more trajectories have been collected, the algorithm will look at each step and check whether the chosen action led to a positive or negative reward and update the policy accordingly."
},
{
"code": null,
"e": 2041,
"s": 1881,
"text": "Trajectories are sampled by interacting with the environment step by step. To take a single step an agent selects an action and passes it into the environment."
},
{
"code": null,
"e": 2474,
"s": 2041,
"text": "PG algorithms decide on which action to take by accepting an input (the state or observation of an environment) and then, for a discrete action space, output a probability for each possible action. A neural network typically calculates this probability. The neural network’s output is dictated by its weights and is typically written as π_θ, where π denotes the policy and θ the weights of the network (important for the next part)."
},
{
"code": null,
"e": 3260,
"s": 2474,
"text": "To select an action, the agent samples from the distribution of probabilities given by the neural network (called logits) — this action is then used to provide the environment with its next input. For example, in Figure 1.2, the action right has a 50% chance of being selected (left 12.5%, up 25% and down 12.5%). As a consequence of selecting an action from probabilities, exploration is inherently present in PG algorithms as the randomness in actions comes from the selection probabilities. As the agent becomes more sure of what the correct action is, exploration will decrease as the probabilities for incorrect actions decrease. Once the action has been taken, all metrics are stored for later use in training (observation, action, log action probabilities, value, reward, done)."
},
{
"code": null,
"e": 3692,
"s": 3260,
"text": "Before diving into PPO, it is useful to breeze over the maths for PG algorithms from a high level to get a complete image of what the algorithm will be doing. However, since this blog post is about implementing PPO, we’ll have to skip over the details of how the derivation behind calculating the loss and updating the agent works (also, if you’re not interested in the maths behind PG, then feel free to skip the next 3 headings)."
},
{
"code": null,
"e": 4280,
"s": 3692,
"text": "Updating the Policy: The building block of any PG algorithm is the formula on how a network is updated. The update formula in Figure 1.3 shows that the new weights of a network [1] are updated to the current weights [2] + the gradient of the current network given a specific state-action pair [4] times the learning rate [3]. This is the underpinning formula of how to update the network weights. Intuitively the gradient is the direction (+/-) of the weights in which the change of the policy will make taken actions more likely in a given state (reverse them to make them less likely)."
},
{
"code": null,
"e": 4419,
"s": 4280,
"text": "A full explanation of how policy gradient updates work from a mathematical standpoint there is no better place than David Silvers lecture."
},
{
"code": null,
"e": 4649,
"s": 4419,
"text": "So how do we calculate this gradient? Thankfully, all the most common deep learning frameworks will keep a computational graph of information passing through a neural network and keep a record of the gradient part of the network."
},
{
"code": null,
"e": 5489,
"s": 4649,
"text": "Adjusting Weight Direction and Amount: With the update equation we know what direction the “gradient” of a specific state-action pair is — that is to say, to make that action (in a specific state) more likely by changing the neural networks weights in the direction of the gradient. Of course, we do not want to make every action more likely, if a bad result was obtained we want to reduce the probability of taking that action. This is what the advantage function [1] embodies — how much better or worse an action was than we expected. If a action led to a scenario where we are better off than before (positive advantage), the weights are change in the gradients direction, effectively making it more likely that that action is chosen again. If it’s worse, we decrease the weights in the direction of the gradient, making it less lightly"
},
{
"code": null,
"e": 5854,
"s": 5489,
"text": "Another consideration is the amount weights are updated by, if just the advantage times the gradient were to be updated, there would be very aggressive updates (great explanation of why here). So in order to counteract this, we divide the update by the output of the policy [2], this is called importance sampling (how much weight to place on a particular update)."
},
{
"code": null,
"e": 6321,
"s": 5854,
"text": "For example, if the action output was [2,3,5,1] and the action with value 5 (action 3) was chosen, the gradient would be divided by 5 to reduce the amount the gradient is updated. This is to stop action 3 quickly increasing in value, and hence and no other value getting the chance of being chosen (as it is done on a probability basis and if we have [2,3,100,1] the other actions are unlikely to be chosen), even if they might yield a higher return in the long run."
},
{
"code": null,
"e": 6642,
"s": 6321,
"text": "Chaining it up: This leaves the last step to the update rule, which comes from using the magic of the chain rule. Using this we can substitute out our partial derivative fraction with the gradient log of the action which was taken. This part is important because it’s what builds the foundation of PG and PPO algorithms."
},
{
"code": null,
"e": 6829,
"s": 6642,
"text": "Again, this is not intended to be a full explanation on the mathematical theory behind policy gradient algorithms but rather a quick review/recap on where the log values are coming from."
},
{
"code": null,
"e": 7623,
"s": 6829,
"text": "Visualising the update: When the theory is placed in practice it would look something as Figure 1.6 describes. First, the trajectory is run [step 1], and all relevant values are saved (log probabilities, value and reward — amongst other things). Once the trajectories have been completed, the discounted returns and advantages can be calculated [step 2] (great article here explaining what advantages are, but as a reminder, the advantages = discounted_return - expected_return where expected return is calculated by the critic as value). [step 3] Next the loss of each step is calculated by looking at the log probabilities and multiplying it by the advantage, just as shown in Figure 1.5. [step 4] Lastly we take the average of all these losses and do a backwards pass with gradient descent."
},
{
"code": null,
"e": 7649,
"s": 7623,
"text": "Original PPO paper — link"
},
{
"code": null,
"e": 8034,
"s": 7649,
"text": "With policy gradient methods, once a few trajectories have been collected a model will be updated a number times using the same trajectories in order to learn from the new data that has been collected. Remember that the size of this update is determined by both the magnitude of the advantage as well as the importance sample (which is expressed as the log probability of the action)."
},
{
"code": null,
"e": 8258,
"s": 8034,
"text": "PPO adds an additional factor which is the probability ratio to prevent large updates from occurring. This is defined as the difference between the original action log probability and the new model’s action log probability."
},
{
"code": null,
"e": 8884,
"s": 8258,
"text": "Problem: The problem with PG algorithms is that when an update is performed, its magnitude by which the policy change can happen (i.e. the weights change) can push the policy into a region that when another gradient descent is performed, all direction are essentially the same and the peak of the reward is missed. This is demonstrated in Figure 1.8 — a single update has missed the peak of the reward, and now when gradient descent is performed on a new trajectory it’s hard to say whether “left” of “right” movement will lead to a better policy loss. This causes the update to destroy the policy to an unrecoverable extent."
},
{
"code": null,
"e": 9232,
"s": 8884,
"text": "Solution: The PPO paper’s solution is to create a ratio between the original action log probability and the new model’s action log probability. If that ratio becomes too large or too small, it will be clipped to +/- a set amount (typically 0.2). This will prevent the policy from taking too large of an update step; this can be seen in Figure 1.9."
},
{
"code": null,
"e": 9346,
"s": 9232,
"text": "Mathematically this is expressed using a clipping function, also known as a surrogate function, in the PPO paper:"
},
{
"code": null,
"e": 9499,
"s": 9346,
"text": "If you’d like to understand this in more detail, Arxiv Insights has an insanely good YouTube explanation of how PPO works from a theoretical standpoint."
},
{
"code": null,
"e": 9577,
"s": 9499,
"text": "Visual implementation of flow: From a practical standpoint following happens;"
},
{
"code": null,
"e": 9823,
"s": 9577,
"text": "First, we collect a few trajectories using our initial model (model_1), making sure to save the action log probability for the actions taken. Using our trajectory, the initial model gets updated to model_2 and is now different from the original."
},
{
"code": null,
"e": 10012,
"s": 9823,
"text": "Then with the same states that we collected from the trajectories [3], the new log probabilities are calculated [2] (these will be different to the initial model as the model has changed)."
},
{
"code": null,
"e": 10308,
"s": 10012,
"text": "The ratio between the new model and the old model’s action log probabilities is then used to calculate the scalar by which the new policy should be updated. Ratios are calculated on a per-step basis. If the ratio is too large or too small, it will be clipped according to the surrogate function."
},
{
"code": null,
"e": 11023,
"s": 10308,
"text": "Hopefully, the theory section was adequate to give some intuition about how an agent takes actions, the model is updated, why PPO works and why the clipping and probability ratio are required. The following section explains how we implemented PPO for ourselves — some of it might be obvious some not. However, it’s probably helpful to go through everything if you want to fully understand our implementation, as there will be differences. Throughout this section, there will be references made back to our code, so it might be helpful to split your screen in half, with one section having the blog post open and the other section the code, having said that, of course, read through this as works best for yourself!"
},
{
"code": null,
"e": 11107,
"s": 11023,
"text": "As an overview there are three main classes and a file which runs the whole system:"
},
{
"code": null,
"e": 11242,
"s": 11107,
"text": "Model.py [class] - This contains the logic for the agent to both, act on given inputs and learn from data collected from trajectories."
},
{
"code": null,
"e": 11443,
"s": 11242,
"text": "Memory.py [class] - This contains all the data from the trajectories and calculates the advantages. It also allows the agent to sample random sections of the trajectory to update the agent in batches."
},
{
"code": null,
"e": 11620,
"s": 11443,
"text": "Config.py [class] - This contains all the settings required in RL & PPO, such as learning rate, number of steps to take, and hyperparameters like epsilon for the clipping size."
},
{
"code": null,
"e": 11703,
"s": 11620,
"text": "Utils.py [File] - This is the main file which runs the sampling and training loop."
},
{
"code": null,
"e": 12028,
"s": 11703,
"text": "As you might be able to tell from the flow chart in Figure 2.1, the way an agent is trained is essentially an expansion of the overview in Figure 1.1. First, the program initialises all our variables, and then the algorithm runs in two distinct stages, collecting trajectories and updating the agent from the collected data."
},
{
"code": null,
"e": 12264,
"s": 12028,
"text": "Collecting Trajectories: Trajectories are collected by playing in a gym environment; the agent takes actions in the simulation based on its observations. Whilst this loop is active, the individual steps are saved in the agent’s memory."
},
{
"code": null,
"e": 12581,
"s": 12264,
"text": "Updating the Agent: Once enough steps are taken, the discounted returns and advantages are calculated — the agent then samples all the steps from the “memory” to calculate the losses and update the agent (all captured data is trained over). Once all the updates are performed, the loop starts at the beginning again."
},
{
"code": null,
"e": 12691,
"s": 12581,
"text": "To start with, all the components used in the experiment need to be initialised. The main pieces of this are:"
},
{
"code": null,
"e": 12711,
"s": 12691,
"text": "The gym environment"
},
{
"code": null,
"e": 12769,
"s": 12711,
"text": "The agent, which includes adding the model and the memory"
},
{
"code": null,
"e": 12821,
"s": 12769,
"text": "Logging our experiments (we use weights and biases)"
},
{
"code": null,
"e": 13242,
"s": 12821,
"text": "The environments which agents train in is typically created with OpenAI gym, a framework that creates a simulation environment for physics tasks and Atari games. Actions are entered which the environment reacts to — this change is then returned to the agent as a set of observations. With this also comes rewards and whether the game has finished letting the agent know whether or not their actions were “good” or “bad”."
},
{
"code": null,
"e": 13794,
"s": 13242,
"text": "When human players look at an Atari game, we see the RGB colours which make up the image and a steady change in frames as we play the game. We could feed every frame directly into our agent; this would be portrayed as a tensor of 160,192,3, representing the game's dimensions and RGB pixels. However, in typical Atari game implementations (and those done in the original paper) a few tricks are used to train more effectively, which we've included in the env.py file (this was heavily influenced and partly copied from Costa's CleanRL implementation)."
},
{
"code": null,
"e": 13820,
"s": 13794,
"text": "Changing the game styles:"
},
{
"code": null,
"e": 13936,
"s": 13820,
"text": "The first few tricks pertain to changing how the game fundamentally operates to help the agents along a little bit."
},
{
"code": null,
"e": 14244,
"s": 13936,
"text": "Episodic Life Env (envs.py:61) — This makes sure that the episode is only finished when all lives are lost, rather than when one. As a result, discounted rewards will get carried through the whole game rather than individual lives — this is important as it will allow the agent to get further into the game."
},
{
"code": null,
"e": 14612,
"s": 14244,
"text": "NoopResetEnv (envs.py:12) — As a technicality in the Atari engine, the game will always be the same if you start playing from the start. To get random behaviour in the game engine (rather than the same version every time), a random set of actions are taken to set the game in a pseudo-random state [paper]. This is critical to help the agent generalise its learnings."
},
{
"code": null,
"e": 14820,
"s": 14612,
"text": "FireResetEnv (envs.py:41) — If the game only starts when the fire command is pressed it will automatically hit fire when is initialised, this is so that the agent doesn’t have to learn how to start the game."
},
{
"code": null,
"e": 15194,
"s": 14820,
"text": "Max and Skip (envs.py:97) — Any action taken by the agent will be applied to four-time steps within the game. The max of each pixel for all the produced frames will be returned — similarly to max pooling. The reward for those frames will also be added up. The short of the long is that this is all to avoid flickering experienced when playing the game [Better explanation]."
},
{
"code": null,
"e": 15457,
"s": 15194,
"text": "Clip Reward (envs.py:125) — Typically speaking in RL, agents train best if rewards are kept in a “reasonable range” (around +/- 1), this is to avoid too large updates when calculating the discounted returns. Clip rewards cut the rewards to +/- 1 for this reason."
},
{
"code": null,
"e": 15498,
"s": 15457,
"text": "Augmenting the Atari observation output:"
},
{
"code": null,
"e": 15785,
"s": 15498,
"text": "Frame Stack (envs.py:187)- The agent is passed a stack of frames, representing four time steps in the actual game. This is so that the agent can have a sense of movement. For example, in Breakout, the ball might be in 4 different positions indicating movement in a particular direction."
},
{
"code": null,
"e": 16107,
"s": 15785,
"text": "WrapFrame (envs.py:134) — This is a custom method that reframes the Atari gym environment’s output. After all the augmentations have taken place, a tensor of (4, 84, 84) is produced - with WrapFrame, this is then converted to (84, 84, 4) for every frame. This is so that it is compatible with the CNN head from our agent."
},
{
"code": null,
"e": 16208,
"s": 16107,
"text": "What this ends up looking like, in terms of tensor sizes for a single environment, is the following:"
},
{
"code": null,
"e": 16429,
"s": 16208,
"text": "All these techniques of augmenting the output and altering gameplay are designed for the agent to learn more effectively from the Atari game environment. It can be thought of as data augmentation in machine vision tasks."
},
{
"code": null,
"e": 16739,
"s": 16429,
"text": "Implementation: The augmentations are implemented in env.py, where they are grouped in a thunk function called make_env(env_id, seed). This function can be invoked at any point, specifying the seed and game type to return an environment; it is implemented this way to help when creating multiple environments."
},
{
"code": null,
"e": 16987,
"s": 16739,
"text": "Note: One might have noticed that there is an Augment input block in Figure 2.2, which adds a dimension to the input of the agent, this is present because the PyTorch 2D CNN block expects a batch to be entered. In our case, this is a batch of one."
},
{
"code": null,
"e": 17185,
"s": 16987,
"text": "We chose to implement multiple environments to take advantage of our home DL machines’ extra CPU and GPU. This sped up training and was a good learning exercise on how multiple environments worked."
},
{
"code": null,
"e": 17496,
"s": 17185,
"text": "When multiple environments are added, all outputs from the gym environment gain an extra dimension n, where n is the number of environments. Our agent’s input, however, is not any different. That is because we already augmented the input in the single environment to have 4 dimensions (as seen in Figure 2.2.)."
},
{
"code": null,
"e": 17678,
"s": 17496,
"text": "Multiple environments are implemented is in our Config.py, here the environments are initialised by wrapping the make_env function in the Open Baseline's DummyVecEnv, as seen below."
},
{
"code": null,
"e": 17791,
"s": 17678,
"text": "envs = VecPyTorch(\tDummyVecEnv(\t\t[make_env(env_id, self.seed+i, i) for i in range(self.num_env)]\t), self.device)"
},
{
"code": null,
"e": 18198,
"s": 17791,
"text": "This function expects “a list of functions that will create the environments (each callable returns a Gym.Env instance when called)”, which is why make_env returns a thunk function that creates a gym-env rather than the gym-env itself. The VecPyTorch is essentially based on VecEnv, which \"abstracts asynchronous vectorised environments\". It's an easier way of interacting with the vectorised environments."
},
{
"code": null,
"e": 18428,
"s": 18198,
"text": "Multiple environments take what we did for single environments and vectorise them in an easy to handle manner. All other game augmentations and reshaping of the environments happen the same way as they did in single environments."
},
{
"code": null,
"e": 18552,
"s": 18428,
"text": "The Atari PPO agent is created from a base class which (Figure 2.4), with the hyperparameters, initialise two key sections:"
},
{
"code": null,
"e": 18778,
"s": 18552,
"text": "The Model - This houses the CNN model, we’ve configured so that this is split into a “head” “actor”, and “critic. The head pre-processes incoming data, which the actor and critic then use to calculate their respective values."
},
{
"code": null,
"e": 19028,
"s": 18778,
"text": "The Memory - There is a deep dive on this topic later, but basically the memory stores state transitions collected during the acting phase. The initialisation determines the shape and size of the memory, and consequently, how long roll-outs will be."
},
{
"code": null,
"e": 19111,
"s": 19028,
"text": "With these two class instances the agent is able to perform 3 essential functions:"
},
{
"code": null,
"e": 19254,
"s": 19111,
"text": "Act: This takes in the observations (of multiple environments), and provides the corresponding actions and log probabilities of those actions."
},
{
"code": null,
"e": 19445,
"s": 19254,
"text": "AddToMemory: Once an action has been taken, all the data for that step must be stored for later use. That is what the AddToMemory function does; it stores the information in PyTorch tensors."
},
{
"code": null,
"e": 19596,
"s": 19445,
"text": "Learn: This will be explored further in a later section — but essentially, this will take processed data from memory and update the model accordingly."
},
{
"code": null,
"e": 19606,
"s": 19596,
"text": "The Model"
},
{
"code": null,
"e": 20067,
"s": 19606,
"text": "The model is a vanilla actor-critic network. A CNN head takes in the frames of the game as input, with the addition of all pixels being scaled down by 255, this is to ensure that the input range is between 0 and 1. The output from the CNN is then passed into two fully connected layers. The first layer outputs a single value acting as the critic, and then the second network outputs the number of actions available in the game environment acting as the actor."
},
{
"code": null,
"e": 20348,
"s": 20067,
"text": "The class is set up so that an act method (models.py:76) can be invoked to return the action, log probabilities and entropy produced by the actor, as well as the value predicted by the critic. To obtain the action, the logits from the actor are immediately sampled (models.py:79)."
},
{
"code": null,
"e": 20377,
"s": 20348,
"text": "Initialising Network Weights"
},
{
"code": null,
"e": 20632,
"s": 20377,
"text": "One last important factor is to ensure that that each layer has been initialised. A generic function called layer_init surrounds every layer in the network, this is to avoid vanishing or exploding gradients (great post by explaining how this works here)."
},
{
"code": null,
"e": 21741,
"s": 20632,
"text": "The decision to make a memory class (rather than just storing the individual variables as PyTorch arrays) in part stemmed the Reinforcement Learning Discussion Discord (shout-out to the community who has been incredible in facilitating discussions), where we were discussing tests for core functionality. RL algorithms notoriously fail silently, meaning that they will either not throw an error but never learn, or even worse, learn but not to its maximum potential. This is a huge problem because it makes debugging incredibly hard and requires many, many experiments; and when using simple environments such as CartPole-v1 might never surface. This is why we decided to create a class that stored the saved trajectories, but whose responsibility it also is to calculate the advantages, discounted returns and sample the correct data from memory. This way, we could write tests for each individual function (the tests can be found in /tests/test_memory.py) to ensure that the output is exactly what was expected. It was also instrumental in validating our understanding of advantages and discounted returns."
},
{
"code": null,
"e": 21806,
"s": 21741,
"text": "The memory itself (as seen in Figure 2.6) has three key aspects:"
},
{
"code": null,
"e": 21970,
"s": 21806,
"text": "Saved Variables — Trajectories are stored to memory here. The data is stored in predefined PyTorch tensors, as this avoids having to convert arrays to tensors etc."
},
{
"code": null,
"e": 22165,
"s": 21970,
"text": "Calculating Advantages — how this is done will be explained in the next section; the important part is that it calculates the advantages and discounted returns based on the trajectories sampled."
},
{
"code": null,
"e": 22482,
"s": 22165,
"text": "Sampling from Memory — Because all of our data is in order and still in the format of our n number of environments, this function essentially squashes all our trajectories into on long tensor and then samples random sections to train on (the implementation is explained in more detail in the Updating Model section)."
},
{
"code": null,
"e": 22826,
"s": 22482,
"text": "The initialisation of the memory dictates it’s shape and size and requires various arguments. This includes the number of environments and the environment itself to get the observation and action space. To will determine how many “steps” are taken it also requires the size of the memory. Lastly, hyperparameters such as gamma are also needed."
},
{
"code": null,
"e": 23098,
"s": 22826,
"text": "Lastly, we initialise W&B — this has been a key tool for us to understand how our agents are performing. It has allowed Daniel and myself to analyse data and run experiments on our own machines and making the results available for both of us, all whilst working remotely."
},
{
"code": null,
"e": 23331,
"s": 23098,
"text": "Having some logging tool has been critical in understanding where mistakes were being made and what affect different hyperparameters have on the model. In a later section, we’ll dig into how various metrics helped us debug our work."
},
{
"code": null,
"e": 23702,
"s": 23331,
"text": "The first stage in training the PPO agent is to collect trajectories — this happens as seen in Figure 2.7 after the agent and environment have been initialised. The agent takes actions based on the observations from the environment, which is then used to take the next step. The sequence of states and actions are then finally saved to the memory for the training phase."
},
{
"code": null,
"e": 23773,
"s": 23702,
"text": "The action is taken by with act function on the agent [Models.py:109]."
},
{
"code": null,
"e": 24098,
"s": 23773,
"text": "class ActorCritic(nn.Module):\t# ...\tdef act(self, x, action=None):\t\tvalues = self.critic(self.forward(x))\t\tlogits = self.actor(self.forward(x))\t\tprobabilities = Categorical(logits=logits)\t\tif action is None:\t\t action = probabilities.sample()\t\treturn action, probabilities.log_prob(action), values, probabilities.entropy()"
},
{
"code": null,
"e": 24369,
"s": 24098,
"text": "To act, the model receives observations from the gym environment (x). The observations then pass through the critic network which returns the value (what the value of that state is) and then the actor-network, which returns the logits (the output of the neural network)."
},
{
"code": null,
"e": 24878,
"s": 24369,
"text": "The value is returned as-is. However, we want to convert our logits into a probability distribution on which we can then sample an action. This is done with the Categorical function of PyTorch — this function turns our logits into a distribution proportional to the logits, summing up to one. The benefit of the categorical class is that the class can also sample an action from the distribution, calculate the log probability of action and the entropy (entropy will be further explained in a later section)."
},
{
"code": null,
"e": 25178,
"s": 24878,
"text": "Saving trajectories is fairly intuitive, but is useful to have a visual representation of how the rewards, observations and done’s come out of the gym environment. For each step in an environment, 3 variables of different dimensions are returned (observation, reward and done — shown in Figure 2.8)."
},
{
"code": null,
"e": 25692,
"s": 25178,
"text": "Every interaction the agent has with the environment (acting on multiple environments) returns an observation, reward, and done. In the example of Figure 2.8, the first step shows no reward, and the episode has not terminated yet, this is assumed to be the case for every step after that unless indicated otherwise. This illustrates that the data collected is appended into the memory as entire steps across multiple environments, indicated by the blue box. This means that what is being saved into the memory is:"
},
{
"code": null,
"e": 25720,
"s": 25692,
"text": "Observations (n, 80, 80, 4)"
},
{
"code": null,
"e": 25735,
"s": 25720,
"text": "Rewards (n, 1)"
},
{
"code": null,
"e": 25748,
"s": 25735,
"text": "dones (n, 1)"
},
{
"code": null,
"e": 25812,
"s": 25748,
"text": "And will then be saved in the memory in a tensor of dimensions:"
},
{
"code": null,
"e": 25843,
"s": 25812,
"text": "Observations (x, n, 80, 80, 4)"
},
{
"code": null,
"e": 25861,
"s": 25843,
"text": "Rewards (x, n, 1)"
},
{
"code": null,
"e": 25877,
"s": 25861,
"text": "dones (x, n, 1)"
},
{
"code": null,
"e": 26063,
"s": 25877,
"text": "Where x is the number of steps, this implies that the “global” number of steps which the agent trains on will, in reality, be x times n, as we have x steps for n number of environments."
},
{
"code": null,
"e": 26804,
"s": 26063,
"text": "The second stage in our PPO is to learn from our collected trajectories — this is initiated by the learn function in Models.py and invoked by the training loop in util.py:L113. When this starts, the advantages are calculated first, this is important to do as all trajectories are required to remain in sequence to calculate the correct discounted return. Once this is finished, we can sample from memory at random, calculate our losses and update the model. Updating over the trajectories happens a set number of times, dictated by a hyper-parameter. Once completed, the old model is replaced with the updated one and the process start over again, but this time with a (hopefully) better performance. This process can be seen in Figure 2.9."
},
{
"code": null,
"e": 27178,
"s": 26804,
"text": "The Advantage is defined as the expected return minus the actual return — this indicates how much better or worse the model performed than anticipated. Calculating these advantages occurs in two steps — first, the discounted returns need to be computed. The expected values (calculated by the critic) are then subtracted from the discounted returns to obtain the advantage."
},
{
"code": null,
"e": 27410,
"s": 27178,
"text": "In case you’re not familiar with discounted returns, this is a great video, but essentially it takes the current reward + the value of the next state times a discount factor (gamma) as per Figure 2.10 (G is the discounted returns)."
},
{
"code": null,
"e": 28150,
"s": 27410,
"text": "In order to calculate the discounted returns, we cannot start at the beginning of the trajectory but rather have to start at the end. This is because we need to iteratively calculate what the value of the next state is. This presents a problem at the very last state as there is no next value, which is why the function also takes last_value and last_done, which are used in the very first calculation of the discounted returns (in the case of Figure 2.11 it's -0.5 as the last value and the episode not being done). In many books, you might see this as n-step bootstrapping. We do not (necessarily) wait for the whole episode to finish but rather estimate after n-steps what the value of that state would be if the episode were to finish."
},
{
"code": null,
"e": 28328,
"s": 28150,
"text": "As an example of what might happen, in Figure 2.11 assumes the trajectories have already been collected (step 1) and then iteratively calculates the discounted return backwards."
},
{
"code": null,
"e": 28377,
"s": 28328,
"text": "This logic is implemented in our Memory.pyclass:"
},
{
"code": null,
"e": 29061,
"s": 28377,
"text": "def calculate_discounted_returns(self, last_value, next_done): with torch.no_grad(): # Create empty discounted returns array self.discounted_returns = torch.zeros((self.size, self.num_envs)).to(self.device) for t in reversed(range(self.size)): # If first loop if t == self.size - 1: next_non_terminal = 1.0 - torch.FloatTensor(next_done).reshape(-1).to(self.device) next_return = last_value.reshape(-1).to(self.device) else: next_non_terminal = 1.0 - self.dones[t+1] next_return = self.discounted_returns[t+1] self.discounted_returns[t] = self.rewards[t] + self.gamma * next_non_terminal * next_return"
},
{
"code": null,
"e": 29669,
"s": 29061,
"text": "The reverse for loop iterates over the collected trajectories in reverse order to calculate the discounted returns. As in Figure 2.11, the first calculation uses the last predicted value, outputted by the critic, all other cases will have the previous discounted return available. The new discounted return is the reward + gamma * the previous discounted return. next_non_terminal is used to check if the discounting should be set to 0 because the episode ended. Finally to get the advantages the memory simply takes the discounted_returns and subtracts the collected values at the corresponding time steps."
},
{
"code": null,
"e": 30124,
"s": 29669,
"text": "Calculating the discounted returns can be a headache, and making sure that they are correctly calculated for the many different scenarios is even harder. It’s easy to make a mistake, in some cases meaning the algorithm will still train but doesn’t perform as well as it could. To really check all the edge cases it is suggested to write test cases and run the calculations against them. For our implementation, this can be found in /tests/test_memory.py."
},
{
"code": null,
"e": 30142,
"s": 30124,
"text": "Fetching the data"
},
{
"code": null,
"e": 30495,
"s": 30142,
"text": "To update the model, the memory is sampled first — this is done by extracting mini-batches (random subsection) from the trajectory saved in memory. This is done with the get_mini_batch_idxs function. The function creates an index for every entry in the memory and randomly assigns them into the arrays for the mini-batch; for example, this could return"
},
{
"code": null,
"e": 30556,
"s": 30495,
"text": "[ \t[1013,456, ... 147,328], \t..., \t[295, 1937, ..., 49,846]]"
},
{
"code": null,
"e": 30790,
"s": 30556,
"text": "The first element in the mini-batch array([1013,456, ... 147,328]) is then passed into the sample function, which expects an array of indexes to pull out of the memory. For every index in that array the following values are returned:"
},
{
"code": null,
"e": 30802,
"s": 30790,
"text": "prev_states"
},
{
"code": null,
"e": 30815,
"s": 30802,
"text": "prev_actions"
},
{
"code": null,
"e": 30830,
"s": 30815,
"text": "prev_log_probs"
},
{
"code": null,
"e": 30849,
"s": 30830,
"text": "discounted_returns"
},
{
"code": null,
"e": 30859,
"s": 30849,
"text": "advantage"
},
{
"code": null,
"e": 30871,
"s": 30859,
"text": "prev_values"
},
{
"code": null,
"e": 30883,
"s": 30871,
"text": "Policy Loss"
},
{
"code": null,
"e": 31048,
"s": 30883,
"text": "The loss function consists of the policy and value loss. As a reminder, it might be worth to check out Figure 1.11 to remember the method of updating the PPO model."
},
{
"code": null,
"e": 31539,
"s": 31048,
"text": "First, the two surrogate functions (clipping of the ratios) need to be calculated. The surrogate function requires the probability ratios — this uses the updated model’s log probabilities and the current model’s log probabilities (used to collect the trajectory). This is the primary reason the action and observations were saved — the observations can now be passed into the updated model and calculate what new log probabilities are outputted given the action taken during the trajectory."
},
{
"code": null,
"e": 31807,
"s": 31539,
"text": "Once the ratios are calculated the surrogate function is relatively straight forward, we simply multiply through by the advantage (calculated in the previous section) and use the clamp function to limit this by 1 + ε and 1- ε. The loss is then the minimum of the two."
},
{
"code": null,
"e": 32299,
"s": 31807,
"text": "# Grab sample from memoryprev_states, prev_actions, prev_log_probs, discounted_returns, advantage, prev_values = self.mem.sample(mini_batch_idx)# find ratiosactions, log_probs, _, entropy = self.model.act(prev_states, prev_actions)ratio = torch.exp(log_probs - prev_log_probs.detach())# calculate surrogatessurrogate_1 = advantages * ratiosurrogate_2 = advantages * torch.clamp(ratio, 1-self.epsilon, 1+self.epsilon)# Policy Gradient Losspg_loss = -torch.min(surrogate_1, surrogate_2).mean()"
},
{
"code": null,
"e": 32310,
"s": 32299,
"text": "Value Loss"
},
{
"code": null,
"e": 32469,
"s": 32310,
"text": "To calculate the value loss we take the mean squared error of what we thought the value of that observation was and what the discounted returns actually were."
},
{
"code": null,
"e": 32768,
"s": 32469,
"text": "# Grab sample from memoryprev_states, prev_actions, prev_log_probs, discounted_returns, advantage, prev_values = self.mem.sample(mini_batch_idx)# Calculate values from new modelnew_values = self.model.get_values(prev_states).view(-1)# Generate lossvalue_loss = F.MSE(new_values, discounted_returns)"
},
{
"code": null,
"e": 32777,
"s": 32768,
"text": "Updating"
},
{
"code": null,
"e": 32886,
"s": 32777,
"text": "Updating is also very standard, we simply backpropagate all the loss added together and include the entropy."
},
{
"code": null,
"e": 33125,
"s": 32886,
"text": "# Lossloss = pg_loss + value_loss - self.entropy_beta*entropy_loss# calculate gradientself.optimiser.zero_grad()loss.backward()# Clip grad to avoid massive updatesnn.utils.clip_grad_norm_(self.model.parameters(), 0.5)self.optimiser.step()"
},
{
"code": null,
"e": 33292,
"s": 33125,
"text": "This process gets repeated will the model has been updated n times for the whole memory set. Then we repeat the whole process over again and hope the model converges!"
},
{
"code": null,
"e": 33355,
"s": 33292,
"text": "To run our the environment navigate to the PPO folder and run:"
},
{
"code": null,
"e": 33376,
"s": 33355,
"text": "python main_atari.py"
},
{
"code": null,
"e": 33561,
"s": 33376,
"text": "To get weights and biases set up you will need to do your own configuration and register the project if you do not have this, tensorboard will still record all of the experiments data."
},
{
"code": null,
"e": 33628,
"s": 33561,
"text": "When running the experiment the key values which are measured are:"
},
{
"code": null,
"e": 33643,
"s": 33628,
"text": "Episode Reward"
},
{
"code": null,
"e": 33747,
"s": 33643,
"text": "This is the most obvious metric to record, it tells us how well an agent is performing at a given step."
},
{
"code": null,
"e": 33761,
"s": 33747,
"text": "Learning Rate"
},
{
"code": null,
"e": 34021,
"s": 33761,
"text": "The learning rate is logged in case this is changed throughout the life cycle of the experiment. For this experiment, it will remain constant, however, annealing is required to get state of the art results. Another blog post will cover why and how this works."
},
{
"code": null,
"e": 34033,
"s": 34021,
"text": "Policy Loss"
},
{
"code": null,
"e": 34236,
"s": 34033,
"text": "The policy loss is generally agreed to be a difficult metric to draw conclusions from, depending on whether the advantages are normalised, or if learning rate annealing is used this will look different."
},
{
"code": null,
"e": 34247,
"s": 34236,
"text": "Value Loss"
},
{
"code": null,
"e": 34619,
"s": 34247,
"text": "This is defined as the mean squared error between what the discounted return was and what the critic thought, it shows how well the critic is predicting the value of a state. Typically this sits quite low, however, when an agent performs much better or worse than expected the value loss will shoot up indicated that the critic is updating how it thinks about this state."
},
{
"code": null,
"e": 34627,
"s": 34619,
"text": "Entropy"
},
{
"code": null,
"e": 35064,
"s": 34627,
"text": "Entropy in RL is the predictability of whether an action is taken (so how certain we are that in a given state we might go left); because the actions are sampled from a distribution, if one those outputs are very high that means it’s fairly certain what action will be taken. Conversely, if all the probabilities sit at the same level, it’s going to be hard to predict which action is taken next (great article that goes more in-depth)."
},
{
"code": null,
"e": 35322,
"s": 35064,
"text": "From an insight perspective, what this means is that if the entropy is very high, the agent doesn’t really know what the right action is and when it’s lower is start be more certain about its actions. This is why, in general, the entropy will be going down."
},
{
"code": null,
"e": 35336,
"s": 35322,
"text": "KL Divergence"
},
{
"code": null,
"e": 35555,
"s": 35336,
"text": "When calculating which action to take in with policy gradient methods, the actions are going to be represented as a set of probabilities — the log of these probabilities is then used to calculate the loss of our model."
},
{
"code": null,
"e": 35797,
"s": 35555,
"text": "When you update the model using the log probabilities in the “learning” phase, typically you would clone your model and update that new model. Once your model has gone through all the updates, it will differ slightly from the original model."
},
{
"code": null,
"e": 36288,
"s": 35797,
"text": "The KL divergence is a measure of how different the log probabilities from the original model are to the new one. The higher the KL divergence is the more the model has changed. As a rule of thumb, a KL divergence which sits around +/- 0.03 from 0 means that the model is updating nicely, whereas a high KL divergence can indicate that the model is taking too big of an update step, this can cause the model to not converge. This is what makes KL divergence such a useful metric to observe."
},
{
"code": null,
"e": 37078,
"s": 36288,
"text": "It’s hard to pin down what the exact problems in an experiment are when looking at metrics, especially because it’s hard to work out whether or not something just isn’t converging or if there is something wrong with the algorithm. One thing that has helped us tremendously is looking for how “on average” performance looks on different metrics. For example from Figure 3.1 it might look like the agent is learning, and then just cannot converge — but when also looking at the value loss (so the MSE between the discounted returns and what the critic thought), it’s clear that the critic was behaving very suspiciously, the value loss is all over the place and it’s frequently far too high. On closer inspection, we found that the calculation for value loss had a wrong variable name in it."
},
{
"code": null,
"e": 37162,
"s": 37078,
"text": "When we were building our agent — Costa’s CleanRL metrics were of great help to us."
},
{
"code": null,
"e": 37174,
"s": 37162,
"text": "Our Metrics"
},
{
"code": null,
"e": 37423,
"s": 37174,
"text": "After much work, we managed to get a reward of around 50. Clearly not ideal, there is still a lot to work at, but this will require adding some additional tricks to the algorithm, it’s also very possible that after more training it will reach ~400."
},
{
"code": null,
"e": 37507,
"s": 37423,
"text": "When creating your own PPO, it might be helpful to have these metrics as reference."
},
{
"code": null,
"e": 37574,
"s": 37507,
"text": "Visual display of agents performing at various stages of training."
},
{
"code": null,
"e": 37870,
"s": 37574,
"text": "Implementing PPO from scratch has been an interesting challenge which has certainly stretched my understanding of RL and patients to its limits. What has really helped is having somebody to work with, this was both a motivation as well as helpful to bounce ideas off when either of us got stuck."
},
{
"code": null,
"e": 38171,
"s": 37870,
"text": "From our experiments, it’s clear that running just a vanilla PPO algorithm will not achieve top-level performance. As such, we have also implemented PPO as per the baselines specifications which reach a reward of 400. I aim to post a blog post on the modifications required to obtain the result soon!"
}
] |
Display flex items horizontally on a specific screen size in Bootstrap | To set flex item horizontally in different screen size, use the flex-*-row class.
The varied screen sizes is set for small, medium, large and extra large screen size. Let us see how to align flex items horizontally for small screen size −
<h2>Flex Row (Small Screen)</h2>
<div class="d-sm-flex flex-sm-row bg-primary mb-3">
<div class="p-2 bg-primary">Audi</div>
<div class="p-2 bg-warning">BMW</div>
<div class="p-2 bg-secondary">Benz</div>
</div>
The following is an example to display flex items horizontally on different screen size −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h2>Flex</h2>
<p>Resize the browser window to check the effect.</p>
<h2>Flex Row</h2>
<div class="d-flex flex-row bg-primary mb-3">
<div class="p-2 bg-secondary">Audi</div>
<div class="p-2 bg-warning">BMW</div>
<div class="p-2 bg-info">Benz</div>
</div>
<h2>Flex Row (Small Screen)</h2>
<div class="d-sm-flex flex-sm-row bg-primary mb-3">
<div class="p-2 bg-primary">Audi</div>
<div class="p-2 bg-warning">BMW</div>
<div class="p-2 bg-secondary">Benz</div>
</div>
<h2>Flex Row (Medium Screen)</h2>
<div class="d-md-flex flex-md-row bg-primary mb-3">
<div class="p-2 bg-warning">Audi</div>
<div class="p-2 bg-danger">BMW</div>
<div class="p-2 bg-primary">Benz</div>
</div>
<h2>Flex Row (Large Screen)</h2>
<div class="d-lg-flex flex-lg-row bg-primary mb-3">
<div class="p-2 bg-primary">Audi</div>
<div class="p-2 bg-danger">BMW</div>
<div class="p-2 bg-info">Benz</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To set flex item horizontally in different screen size, use the flex-*-row class."
},
{
"code": null,
"e": 1301,
"s": 1144,
"text": "The varied screen sizes is set for small, medium, large and extra large screen size. Let us see how to align flex items horizontally for small screen size −"
},
{
"code": null,
"e": 1517,
"s": 1301,
"text": "<h2>Flex Row (Small Screen)</h2>\n<div class=\"d-sm-flex flex-sm-row bg-primary mb-3\">\n <div class=\"p-2 bg-primary\">Audi</div>\n <div class=\"p-2 bg-warning\">BMW</div>\n <div class=\"p-2 bg-secondary\">Benz</div>\n</div>"
},
{
"code": null,
"e": 1607,
"s": 1517,
"text": "The following is an example to display flex items horizontally on different screen size −"
},
{
"code": null,
"e": 1617,
"s": 1607,
"text": "Live Demo"
},
{
"code": null,
"e": 3171,
"s": 1617,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n <div class=\"container mt-3\">\n <h2>Flex</h2>\n <p>Resize the browser window to check the effect.</p>\n <h2>Flex Row</h2>\n <div class=\"d-flex flex-row bg-primary mb-3\">\n <div class=\"p-2 bg-secondary\">Audi</div>\n <div class=\"p-2 bg-warning\">BMW</div>\n <div class=\"p-2 bg-info\">Benz</div>\n </div>\n <h2>Flex Row (Small Screen)</h2>\n <div class=\"d-sm-flex flex-sm-row bg-primary mb-3\">\n <div class=\"p-2 bg-primary\">Audi</div>\n <div class=\"p-2 bg-warning\">BMW</div>\n <div class=\"p-2 bg-secondary\">Benz</div>\n </div>\n <h2>Flex Row (Medium Screen)</h2>\n <div class=\"d-md-flex flex-md-row bg-primary mb-3\">\n <div class=\"p-2 bg-warning\">Audi</div>\n <div class=\"p-2 bg-danger\">BMW</div>\n <div class=\"p-2 bg-primary\">Benz</div>\n </div>\n <h2>Flex Row (Large Screen)</h2>\n <div class=\"d-lg-flex flex-lg-row bg-primary mb-3\">\n <div class=\"p-2 bg-primary\">Audi</div>\n <div class=\"p-2 bg-danger\">BMW</div>\n <div class=\"p-2 bg-info\">Benz</div>\n </div>\n </div>\n\n </body>\n</html>"
}
] |
Build and deploy your first machine learning web app | by Moez Ali | Towards Data Science | In our last post we demonstrated how to train and deploy machine learning models in Power BI using PyCaret. If you haven’t heard about PyCaret before, please read our announcement to get a quick start.
In this tutorial we will use PyCaret to develop a machine learning pipeline, that will include preprocessing transformations and a regression model to predict patient hospitalization charges based on demographic and basic patient health risk metrics such as age, BMI, smoking status etc.
What is a deployment and why do we deploy machine learning models.
Develop a machine learning pipeline and train models using PyCaret.
Build a simple web app using a Python framework called ‘Flask’.
Deploy a web app on ‘Heroku’ and see your model in action.
PyCaret is an open source, low-code machine learning library in Python to train and deploy machine learning pipelines and models in production. PyCaret can be installed easily using pip.
# for Jupyter notebook on your local computerpip install pycaret# for azure notebooks and google colab!pip install pycaret
Flask is a framework that allows you to build web applications. A web application can be a commercial website, a blog, e-commerce system, or an application that generates predictions from data provided in real-time using trained models. If you don’t have Flask installed, you can use pip to install it.
# install flaskpip install Flask
GitHub is a cloud-based service that is used to host, manage and control code. Imagine you are working in a large team where multiple people (sometime hundreds of them) are making changes. PyCaret is itself an example of an open-source project where hundreds of community developers are continuously contributing to source code. If you haven’t used GitHub before, you can sign up for a free account.
Heroku is a platform as a service (PaaS) that enables the deployment of web apps based on a managed container system, with integrated data services and a powerful ecosystem. In simple words, this will allow you to take the application from your local machine to the cloud so that anybody can access it using a Web URL. In this tutorial we have chosen Heroku for deployment as it provides free resource hours when you sign up for new account.
The deployment of machine learning models is the process of making models available in production where web applications, enterprise software and APIs can consume the trained model by providing new data points and generating predictions.
Normally machine learning models are built so that they can be used to predict an outcome (binary value i.e. 1 or 0 for Classification, continuous values for Regression, labels for Clustering etc. There are two broad ways of generating predictions (i) predict by batch; and (ii) predict in real-time. In our last tutorial we demonstrated how to deploy machine learning model in Power BI and predict by batch. In this tutorial we will see how to deploy a machine learning model to predict in real-time.
An insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization.
(data source)
To build a web application where demographic and health information of a patient is entered in a web form to predict charges.
Train and validate models and develop a machine learning pipeline for deployment.
Build a basic HTML front-end with an input form for independent variables (age, sex, bmi, children, smoker, region).
Build a back-end of the web application using a Flask Framework.
Deploy the web app on Heroku. Once deployed, it will become publicly available and can be accessed via Web URL.
Training and model validation are performed in Integrated Development Environment (IDE) or Notebook either on your local machine or on cloud. In this tutorial we will use PyCaret in Jupyter Notebook to develop machine learning pipeline and train regression models. If you haven’t used PyCaret before, click here to learn more about PyCaret or see Getting Started Tutorials on our website.
In this tutorial, we have performed two experiments. The first experiment is performed with default preprocessing settings in PyCaret (missing value imputation, categorical encoding etc). The second experiment has some additional preprocessing tasks such as scaling and normalization, automatic feature engineering and binning continuous data into intervals. See the setup example for the second experiment:
# Experiment No. 2from pycaret.regression import *r2 = setup(data, target = 'charges', session_id = 123, normalize = True, polynomial_features = True, trigonometry_features = True, feature_interaction=True, bin_numeric_features= ['age', 'bmi'])
The magic happens with only a few lines of code. Notice that in Experiment 2 the transformed dataset has 62 features for training derived from only 7 features in the original dataset. All of the new features are the result of transformations and automatic feature engineering in PyCaret.
Sample code for model training and validation in PyCaret:
# Model Training and Validation lr = create_model('lr')
Notice the impact of transformations and automatic feature engineering. The R2 has increased by 10% with very little effort. We can compare the residual plot of linear regression model for both experiments and observe the impact of transformations and feature engineering on the heteroskedasticity of model.
# plot residuals of trained modelplot_model(lr, plot = 'residuals')
Machine learning is an iterative process. Number of iterations and techniques used within are dependent on how critical the task is and what the impact will be if predictions are wrong. The severity and impact of a machine learning model to predict a patient outcome in real-time in the ICU of a hospital is far more than a model built to predict customer churn.
In this tutorial, we have performed only two iterations and the linear regression model from the second experiment will be used for deployment. At this stage, however, the model is still only an object within notebook. To save it as a file that can be transferred to and consumed by other applications, run the following code:
# save transformation pipeline and model save_model(lr, model_name = 'c:/username/ins/deployment_28042020')
When you save a model in PyCaret, the entire transformation pipeline based on the configuration defined in the setup() function is created . All inter-dependencies are orchestrated automatically. See the pipeline and model stored in the ‘deployment_28042020’ variable:
We have finished our first task of training and selecting a model for deployment. The final machine learning pipeline and linear regression model is now saved as a file in the local drive under the location defined in the save_model() function. (In this example: c:/username/ins/deployment_28042020.pkl).
Now that our machine learning pipeline and model are ready we will start building a web application that can connect to them and generate predictions on new data in real-time. There are two parts of this application:
Front-end (designed using HTML)
Back-end (developed using Flask in Python)
Generally, the front-end of web applications are built using HTML which is not the focus of this article. We have used a simple HTML template and a CSS style sheet to design an input form. Here’s the HTML snippet of the front-end page of our web application.
You don’t need to be an expert in HTML to build simple applications. There are numerous free platforms that provide HTML and CSS templates as well as enable building beautiful HTML pages quickly by using a drag and drop interface.
CSS Style SheetCSS (also known as Cascading Style Sheets) describes how HTML elements are displayed on a screen. It is an efficient way of controlling the layout of your application. Style sheets contain information such as background color, font size and color, margins etc. They are saved externally as a .css file and is linked to HTML but including 1 line of code.
The back-end of a web application is developed using a Flask framework. For beginner’s it is intuitive to consider Flask as a library that you can import just like any other library in Python. See the sample code snippet of our back-end written using a Flask framework in Python.
If you remember from the Step 1 above we have finalized linear regression model that was trained on 62 features that were automatically engineered by PyCaret. However, the front-end of our web application has an input form that collects only the six features i.e. age, sex, bmi, children, smoker, region.
How do we transform 6 features of a new data point in real-time into 62 features on which model was trained? With a sequence of transformations applied during model training, coding becomes increasingly complex and time-taking task.
In PyCaret all transformations such as categorical encoding, scaling, missing value imputation, feature engineering and even feature selection are automatically executed in real-time before generating predictions.
Imagine the amount of code you would have had to write to apply all the transformations in strict sequence before you could even use your model for predictions. In practice, when you think of machine learning, you should think about the entire ML pipeline and not just the model.
Testing AppOne final step before we publish the application on Heroku is to test the web app locally. Open Anaconda Prompt and navigate to folder where ‘app.py’ is saved on your computer. Run the python file with below code:
python app.py
Once executed, copy the URL into a browser and it should open a web application hosted on your local machine (127.0.0.1). Try entering test values to see if the predict function is working. In the example below, the expected bill for a 19 year old female smoker with no children in the southwest is $20,900.
Congratulations! you have now built your first machine learning app. Now it’s time to take this application from your local machine into the cloud so other people can use it with a Web URL.
Now that the model is trained, the machine learning pipeline is ready, and the application is tested on our local machine, we are ready to start our deployment on Heroku. There are couple of ways to upload your application source code onto Heroku. The simplest way is to link a GitHub repository to your Heroku account.
If you would like to follow along you can fork this repository from GitHub. If you don’t know how to fork a repo, please read this official GitHub tutorial.
By now you are familiar with all the files in repository shown above except for two files i.e. ‘requirements.txt’ and ‘Procfile’.
requirements.txt file is a text file containing the names of the python packages required to execute the application. If these packages are not installed in the environment application is running, it will fail.
Procfile is simply one line of code that provides startup instructions to web server that indicate which file should be executed first when somebody logs into the application. In this example the name of our application file is ‘app.py’ and the name of the application is also ‘app’. (hence app:app)
Once all the files are uploaded onto the GitHub repository, we are now ready to start deployment on Heroku. Follow the steps below:
Step 1 — Sign up on heroku.com and click on ‘Create new app’
Step 2 — Enter App name and region
Step 3 — Connect to your GitHub repository where code is hosted
Step 4 — Deploy branch
Step 5 — Wait 5–10 minutes and BOOM
App is published to URL: https://pycaret-insurance.herokuapp.com/
There is one last thing to see before we end the tutorial.
So far we have built and deployed a web application that works with our machine learning pipeline. Now imagine that you already have an enterprise application in which you want to integrate predictions from your model. What you need is a web service where you can make an API call with input data points and get the predictions back. To achieve this we have created the predict_api function in our ‘app.py’ file. See the code snippet:
Here’s how you can use this web service in Python using the requests library:
import requestsurl = 'https://pycaret-insurance.herokuapp.com/predict_api'pred = requests.post(url,json={'age':55, 'sex':'male', 'bmi':59, 'children':1, 'smoker':'male', 'region':'northwest'})print(pred.json())
In the next tutorial for deploying machine learning pipelines, we will dive deeper into deploying machine learning pipelines using docker containers. We will demonstrate how to easily deploy and run containerized machine learning applications on Linux.
Follow our LinkedIn and subscribe to our Youtube channel to learn more about PyCaret.
User Guide / DocumentationGitHub RepositoryInstall PyCaretNotebook TutorialsContribute in PyCaret
As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
PyCaret getting started tutorials in Notebook:
ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification
We are actively working on improving PyCaret. Our future development pipeline includes a new Time Series Forecasting module, integration with TensorFlow, and major improvements on the scalability of PyCaret. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page.
PyCaret is an open source project. Everybody is welcome to contribute. If you would like contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch.
Please give us ⭐️ on our GitHub repo if you like PyCaret.
Medium : https://medium.com/@moez_62905/
LinkedIn : https://www.linkedin.com/in/profile-moez/
Twitter : https://twitter.com/moezpycaretorg1 | [
{
"code": null,
"e": 374,
"s": 172,
"text": "In our last post we demonstrated how to train and deploy machine learning models in Power BI using PyCaret. If you haven’t heard about PyCaret before, please read our announcement to get a quick start."
},
{
"code": null,
"e": 662,
"s": 374,
"text": "In this tutorial we will use PyCaret to develop a machine learning pipeline, that will include preprocessing transformations and a regression model to predict patient hospitalization charges based on demographic and basic patient health risk metrics such as age, BMI, smoking status etc."
},
{
"code": null,
"e": 729,
"s": 662,
"text": "What is a deployment and why do we deploy machine learning models."
},
{
"code": null,
"e": 797,
"s": 729,
"text": "Develop a machine learning pipeline and train models using PyCaret."
},
{
"code": null,
"e": 861,
"s": 797,
"text": "Build a simple web app using a Python framework called ‘Flask’."
},
{
"code": null,
"e": 920,
"s": 861,
"text": "Deploy a web app on ‘Heroku’ and see your model in action."
},
{
"code": null,
"e": 1107,
"s": 920,
"text": "PyCaret is an open source, low-code machine learning library in Python to train and deploy machine learning pipelines and models in production. PyCaret can be installed easily using pip."
},
{
"code": null,
"e": 1230,
"s": 1107,
"text": "# for Jupyter notebook on your local computerpip install pycaret# for azure notebooks and google colab!pip install pycaret"
},
{
"code": null,
"e": 1533,
"s": 1230,
"text": "Flask is a framework that allows you to build web applications. A web application can be a commercial website, a blog, e-commerce system, or an application that generates predictions from data provided in real-time using trained models. If you don’t have Flask installed, you can use pip to install it."
},
{
"code": null,
"e": 1566,
"s": 1533,
"text": "# install flaskpip install Flask"
},
{
"code": null,
"e": 1966,
"s": 1566,
"text": "GitHub is a cloud-based service that is used to host, manage and control code. Imagine you are working in a large team where multiple people (sometime hundreds of them) are making changes. PyCaret is itself an example of an open-source project where hundreds of community developers are continuously contributing to source code. If you haven’t used GitHub before, you can sign up for a free account."
},
{
"code": null,
"e": 2408,
"s": 1966,
"text": "Heroku is a platform as a service (PaaS) that enables the deployment of web apps based on a managed container system, with integrated data services and a powerful ecosystem. In simple words, this will allow you to take the application from your local machine to the cloud so that anybody can access it using a Web URL. In this tutorial we have chosen Heroku for deployment as it provides free resource hours when you sign up for new account."
},
{
"code": null,
"e": 2646,
"s": 2408,
"text": "The deployment of machine learning models is the process of making models available in production where web applications, enterprise software and APIs can consume the trained model by providing new data points and generating predictions."
},
{
"code": null,
"e": 3148,
"s": 2646,
"text": "Normally machine learning models are built so that they can be used to predict an outcome (binary value i.e. 1 or 0 for Classification, continuous values for Regression, labels for Clustering etc. There are two broad ways of generating predictions (i) predict by batch; and (ii) predict in real-time. In our last tutorial we demonstrated how to deploy machine learning model in Power BI and predict by batch. In this tutorial we will see how to deploy a machine learning model to predict in real-time."
},
{
"code": null,
"e": 3337,
"s": 3148,
"text": "An insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization."
},
{
"code": null,
"e": 3351,
"s": 3337,
"text": "(data source)"
},
{
"code": null,
"e": 3477,
"s": 3351,
"text": "To build a web application where demographic and health information of a patient is entered in a web form to predict charges."
},
{
"code": null,
"e": 3559,
"s": 3477,
"text": "Train and validate models and develop a machine learning pipeline for deployment."
},
{
"code": null,
"e": 3676,
"s": 3559,
"text": "Build a basic HTML front-end with an input form for independent variables (age, sex, bmi, children, smoker, region)."
},
{
"code": null,
"e": 3741,
"s": 3676,
"text": "Build a back-end of the web application using a Flask Framework."
},
{
"code": null,
"e": 3853,
"s": 3741,
"text": "Deploy the web app on Heroku. Once deployed, it will become publicly available and can be accessed via Web URL."
},
{
"code": null,
"e": 4242,
"s": 3853,
"text": "Training and model validation are performed in Integrated Development Environment (IDE) or Notebook either on your local machine or on cloud. In this tutorial we will use PyCaret in Jupyter Notebook to develop machine learning pipeline and train regression models. If you haven’t used PyCaret before, click here to learn more about PyCaret or see Getting Started Tutorials on our website."
},
{
"code": null,
"e": 4650,
"s": 4242,
"text": "In this tutorial, we have performed two experiments. The first experiment is performed with default preprocessing settings in PyCaret (missing value imputation, categorical encoding etc). The second experiment has some additional preprocessing tasks such as scaling and normalization, automatic feature engineering and binning continuous data into intervals. See the setup example for the second experiment:"
},
{
"code": null,
"e": 4936,
"s": 4650,
"text": "# Experiment No. 2from pycaret.regression import *r2 = setup(data, target = 'charges', session_id = 123, normalize = True, polynomial_features = True, trigonometry_features = True, feature_interaction=True, bin_numeric_features= ['age', 'bmi'])"
},
{
"code": null,
"e": 5224,
"s": 4936,
"text": "The magic happens with only a few lines of code. Notice that in Experiment 2 the transformed dataset has 62 features for training derived from only 7 features in the original dataset. All of the new features are the result of transformations and automatic feature engineering in PyCaret."
},
{
"code": null,
"e": 5282,
"s": 5224,
"text": "Sample code for model training and validation in PyCaret:"
},
{
"code": null,
"e": 5338,
"s": 5282,
"text": "# Model Training and Validation lr = create_model('lr')"
},
{
"code": null,
"e": 5646,
"s": 5338,
"text": "Notice the impact of transformations and automatic feature engineering. The R2 has increased by 10% with very little effort. We can compare the residual plot of linear regression model for both experiments and observe the impact of transformations and feature engineering on the heteroskedasticity of model."
},
{
"code": null,
"e": 5714,
"s": 5646,
"text": "# plot residuals of trained modelplot_model(lr, plot = 'residuals')"
},
{
"code": null,
"e": 6077,
"s": 5714,
"text": "Machine learning is an iterative process. Number of iterations and techniques used within are dependent on how critical the task is and what the impact will be if predictions are wrong. The severity and impact of a machine learning model to predict a patient outcome in real-time in the ICU of a hospital is far more than a model built to predict customer churn."
},
{
"code": null,
"e": 6404,
"s": 6077,
"text": "In this tutorial, we have performed only two iterations and the linear regression model from the second experiment will be used for deployment. At this stage, however, the model is still only an object within notebook. To save it as a file that can be transferred to and consumed by other applications, run the following code:"
},
{
"code": null,
"e": 6512,
"s": 6404,
"text": "# save transformation pipeline and model save_model(lr, model_name = 'c:/username/ins/deployment_28042020')"
},
{
"code": null,
"e": 6781,
"s": 6512,
"text": "When you save a model in PyCaret, the entire transformation pipeline based on the configuration defined in the setup() function is created . All inter-dependencies are orchestrated automatically. See the pipeline and model stored in the ‘deployment_28042020’ variable:"
},
{
"code": null,
"e": 7086,
"s": 6781,
"text": "We have finished our first task of training and selecting a model for deployment. The final machine learning pipeline and linear regression model is now saved as a file in the local drive under the location defined in the save_model() function. (In this example: c:/username/ins/deployment_28042020.pkl)."
},
{
"code": null,
"e": 7303,
"s": 7086,
"text": "Now that our machine learning pipeline and model are ready we will start building a web application that can connect to them and generate predictions on new data in real-time. There are two parts of this application:"
},
{
"code": null,
"e": 7335,
"s": 7303,
"text": "Front-end (designed using HTML)"
},
{
"code": null,
"e": 7378,
"s": 7335,
"text": "Back-end (developed using Flask in Python)"
},
{
"code": null,
"e": 7637,
"s": 7378,
"text": "Generally, the front-end of web applications are built using HTML which is not the focus of this article. We have used a simple HTML template and a CSS style sheet to design an input form. Here’s the HTML snippet of the front-end page of our web application."
},
{
"code": null,
"e": 7868,
"s": 7637,
"text": "You don’t need to be an expert in HTML to build simple applications. There are numerous free platforms that provide HTML and CSS templates as well as enable building beautiful HTML pages quickly by using a drag and drop interface."
},
{
"code": null,
"e": 8237,
"s": 7868,
"text": "CSS Style SheetCSS (also known as Cascading Style Sheets) describes how HTML elements are displayed on a screen. It is an efficient way of controlling the layout of your application. Style sheets contain information such as background color, font size and color, margins etc. They are saved externally as a .css file and is linked to HTML but including 1 line of code."
},
{
"code": null,
"e": 8517,
"s": 8237,
"text": "The back-end of a web application is developed using a Flask framework. For beginner’s it is intuitive to consider Flask as a library that you can import just like any other library in Python. See the sample code snippet of our back-end written using a Flask framework in Python."
},
{
"code": null,
"e": 8822,
"s": 8517,
"text": "If you remember from the Step 1 above we have finalized linear regression model that was trained on 62 features that were automatically engineered by PyCaret. However, the front-end of our web application has an input form that collects only the six features i.e. age, sex, bmi, children, smoker, region."
},
{
"code": null,
"e": 9055,
"s": 8822,
"text": "How do we transform 6 features of a new data point in real-time into 62 features on which model was trained? With a sequence of transformations applied during model training, coding becomes increasingly complex and time-taking task."
},
{
"code": null,
"e": 9269,
"s": 9055,
"text": "In PyCaret all transformations such as categorical encoding, scaling, missing value imputation, feature engineering and even feature selection are automatically executed in real-time before generating predictions."
},
{
"code": null,
"e": 9549,
"s": 9269,
"text": "Imagine the amount of code you would have had to write to apply all the transformations in strict sequence before you could even use your model for predictions. In practice, when you think of machine learning, you should think about the entire ML pipeline and not just the model."
},
{
"code": null,
"e": 9774,
"s": 9549,
"text": "Testing AppOne final step before we publish the application on Heroku is to test the web app locally. Open Anaconda Prompt and navigate to folder where ‘app.py’ is saved on your computer. Run the python file with below code:"
},
{
"code": null,
"e": 9788,
"s": 9774,
"text": "python app.py"
},
{
"code": null,
"e": 10096,
"s": 9788,
"text": "Once executed, copy the URL into a browser and it should open a web application hosted on your local machine (127.0.0.1). Try entering test values to see if the predict function is working. In the example below, the expected bill for a 19 year old female smoker with no children in the southwest is $20,900."
},
{
"code": null,
"e": 10286,
"s": 10096,
"text": "Congratulations! you have now built your first machine learning app. Now it’s time to take this application from your local machine into the cloud so other people can use it with a Web URL."
},
{
"code": null,
"e": 10606,
"s": 10286,
"text": "Now that the model is trained, the machine learning pipeline is ready, and the application is tested on our local machine, we are ready to start our deployment on Heroku. There are couple of ways to upload your application source code onto Heroku. The simplest way is to link a GitHub repository to your Heroku account."
},
{
"code": null,
"e": 10763,
"s": 10606,
"text": "If you would like to follow along you can fork this repository from GitHub. If you don’t know how to fork a repo, please read this official GitHub tutorial."
},
{
"code": null,
"e": 10893,
"s": 10763,
"text": "By now you are familiar with all the files in repository shown above except for two files i.e. ‘requirements.txt’ and ‘Procfile’."
},
{
"code": null,
"e": 11104,
"s": 10893,
"text": "requirements.txt file is a text file containing the names of the python packages required to execute the application. If these packages are not installed in the environment application is running, it will fail."
},
{
"code": null,
"e": 11404,
"s": 11104,
"text": "Procfile is simply one line of code that provides startup instructions to web server that indicate which file should be executed first when somebody logs into the application. In this example the name of our application file is ‘app.py’ and the name of the application is also ‘app’. (hence app:app)"
},
{
"code": null,
"e": 11536,
"s": 11404,
"text": "Once all the files are uploaded onto the GitHub repository, we are now ready to start deployment on Heroku. Follow the steps below:"
},
{
"code": null,
"e": 11597,
"s": 11536,
"text": "Step 1 — Sign up on heroku.com and click on ‘Create new app’"
},
{
"code": null,
"e": 11632,
"s": 11597,
"text": "Step 2 — Enter App name and region"
},
{
"code": null,
"e": 11696,
"s": 11632,
"text": "Step 3 — Connect to your GitHub repository where code is hosted"
},
{
"code": null,
"e": 11719,
"s": 11696,
"text": "Step 4 — Deploy branch"
},
{
"code": null,
"e": 11755,
"s": 11719,
"text": "Step 5 — Wait 5–10 minutes and BOOM"
},
{
"code": null,
"e": 11821,
"s": 11755,
"text": "App is published to URL: https://pycaret-insurance.herokuapp.com/"
},
{
"code": null,
"e": 11880,
"s": 11821,
"text": "There is one last thing to see before we end the tutorial."
},
{
"code": null,
"e": 12315,
"s": 11880,
"text": "So far we have built and deployed a web application that works with our machine learning pipeline. Now imagine that you already have an enterprise application in which you want to integrate predictions from your model. What you need is a web service where you can make an API call with input data points and get the predictions back. To achieve this we have created the predict_api function in our ‘app.py’ file. See the code snippet:"
},
{
"code": null,
"e": 12393,
"s": 12315,
"text": "Here’s how you can use this web service in Python using the requests library:"
},
{
"code": null,
"e": 12604,
"s": 12393,
"text": "import requestsurl = 'https://pycaret-insurance.herokuapp.com/predict_api'pred = requests.post(url,json={'age':55, 'sex':'male', 'bmi':59, 'children':1, 'smoker':'male', 'region':'northwest'})print(pred.json())"
},
{
"code": null,
"e": 12857,
"s": 12604,
"text": "In the next tutorial for deploying machine learning pipelines, we will dive deeper into deploying machine learning pipelines using docker containers. We will demonstrate how to easily deploy and run containerized machine learning applications on Linux."
},
{
"code": null,
"e": 12943,
"s": 12857,
"text": "Follow our LinkedIn and subscribe to our Youtube channel to learn more about PyCaret."
},
{
"code": null,
"e": 13041,
"s": 12943,
"text": "User Guide / DocumentationGitHub RepositoryInstall PyCaretNotebook TutorialsContribute in PyCaret"
},
{
"code": null,
"e": 13207,
"s": 13041,
"text": "As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python."
},
{
"code": null,
"e": 13309,
"s": 13207,
"text": "ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining"
},
{
"code": null,
"e": 13356,
"s": 13309,
"text": "PyCaret getting started tutorials in Notebook:"
},
{
"code": null,
"e": 13458,
"s": 13356,
"text": "ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification"
},
{
"code": null,
"e": 13825,
"s": 13458,
"text": "We are actively working on improving PyCaret. Our future development pipeline includes a new Time Series Forecasting module, integration with TensorFlow, and major improvements on the scalability of PyCaret. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page."
},
{
"code": null,
"e": 14031,
"s": 13825,
"text": "PyCaret is an open source project. Everybody is welcome to contribute. If you would like contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch."
},
{
"code": null,
"e": 14089,
"s": 14031,
"text": "Please give us ⭐️ on our GitHub repo if you like PyCaret."
},
{
"code": null,
"e": 14130,
"s": 14089,
"text": "Medium : https://medium.com/@moez_62905/"
},
{
"code": null,
"e": 14183,
"s": 14130,
"text": "LinkedIn : https://www.linkedin.com/in/profile-moez/"
}
] |
Drag and Drop a File feature in React JS | Drag and Drop interfaces enable web applications to allow users to drag and drop files on a web page. In this article, we will see how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page. Here, we will be using the react-dropzone package. Let's get started.
First of all, create a React project −
npx create-react-app newproject
Go to the project directory −
cd newproject
Now download and install the react-dropzone package −
npm i --save react-dropzone
We will use this library to add a droppable area inside our React
element's area. This is used to add a file selection area too.
In this example, we will add the name of a file in a list using drag-and-drag feature. Insert the following lines of code in App.js −
import React from "react";
import { useDropzone } from "react-dropzone";
function Basic(props) {
const { acceptedFiles, getRootProps, getInputProps } =
useDropzone();
const files = acceptedFiles.map((file) => (
<li key={file.path}>
{file.path} - {file.size} bytes
</li>
));
return (
<section className="container">
<div {...getRootProps({ className: "dropzone" })}>
<input
{...getInputProps()}
style={{ backgroundColor: "black", color: "white" }}
/>
<br />
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
<aside>
<h4>Files</h4>
<ul>{files}</ul>
</aside>
</section>
);
}
export default App
function App() {
return <Basic />;
}
We have created three variables −
The first variable stores all the file details,
The first variable stores all the file details,
The second variable defines the area where this drag-and-drop feature will work, and
The second variable defines the area where this drag-and-drop feature will work, and
The third variable makes the input field droppable.
The third variable makes the input field droppable.
On execution, it will produce the following output −
You can drag-and-drop files onto this page from any folder. It will
display the file name along with its size. Also, you can use the "Choose
files" button to open a folder location and select a file. | [
{
"code": null,
"e": 1399,
"s": 1062,
"text": "Drag and Drop interfaces enable web applications to allow users to drag and drop files on a web page. In this article, we will see how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page. Here, we will be using the react-dropzone package. Let's get started."
},
{
"code": null,
"e": 1438,
"s": 1399,
"text": "First of all, create a React project −"
},
{
"code": null,
"e": 1470,
"s": 1438,
"text": "npx create-react-app newproject"
},
{
"code": null,
"e": 1500,
"s": 1470,
"text": "Go to the project directory −"
},
{
"code": null,
"e": 1514,
"s": 1500,
"text": "cd newproject"
},
{
"code": null,
"e": 1568,
"s": 1514,
"text": "Now download and install the react-dropzone package −"
},
{
"code": null,
"e": 1596,
"s": 1568,
"text": "npm i --save react-dropzone"
},
{
"code": null,
"e": 1725,
"s": 1596,
"text": "We will use this library to add a droppable area inside our React\nelement's area. This is used to add a file selection area too."
},
{
"code": null,
"e": 1859,
"s": 1725,
"text": "In this example, we will add the name of a file in a list using drag-and-drag feature. Insert the following lines of code in App.js −"
},
{
"code": null,
"e": 2659,
"s": 1859,
"text": "import React from \"react\";\nimport { useDropzone } from \"react-dropzone\";\nfunction Basic(props) {\n const { acceptedFiles, getRootProps, getInputProps } =\nuseDropzone();\n\n const files = acceptedFiles.map((file) => (\n <li key={file.path}>\n {file.path} - {file.size} bytes\n </li>\n ));\n return (\n <section className=\"container\">\n <div {...getRootProps({ className: \"dropzone\" })}>\n <input\n {...getInputProps()}\n style={{ backgroundColor: \"black\", color: \"white\" }}\n />\n <br />\n <p>Drag 'n' drop some files here, or click to select files</p>\n </div>\n <aside>\n <h4>Files</h4>\n <ul>{files}</ul>\n </aside>\n </section>\n );\n}\nexport default App\n\nfunction App() {\n return <Basic />;\n}"
},
{
"code": null,
"e": 2693,
"s": 2659,
"text": "We have created three variables −"
},
{
"code": null,
"e": 2741,
"s": 2693,
"text": "The first variable stores all the file details,"
},
{
"code": null,
"e": 2789,
"s": 2741,
"text": "The first variable stores all the file details,"
},
{
"code": null,
"e": 2874,
"s": 2789,
"text": "The second variable defines the area where this drag-and-drop feature will work, and"
},
{
"code": null,
"e": 2959,
"s": 2874,
"text": "The second variable defines the area where this drag-and-drop feature will work, and"
},
{
"code": null,
"e": 3011,
"s": 2959,
"text": "The third variable makes the input field droppable."
},
{
"code": null,
"e": 3063,
"s": 3011,
"text": "The third variable makes the input field droppable."
},
{
"code": null,
"e": 3116,
"s": 3063,
"text": "On execution, it will produce the following output −"
},
{
"code": null,
"e": 3316,
"s": 3116,
"text": "You can drag-and-drop files onto this page from any folder. It will\ndisplay the file name along with its size. Also, you can use the \"Choose\nfiles\" button to open a folder location and select a file."
}
] |
Program to calculate the value of nPr - GeeksforGeeks | 07 May, 2021
Given two numbers n and r, the task is to find the value of nPr. nPr represents n permutation r which is calculated as n!/(n-k)!. Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! where “!” represents factorial.
nPr = n! / (n - r)!
Program:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to calculate nPr#include<bits/stdc++.h>using namespace std; int fact(int n){ if (n <= 1) return 1; return n * fact(n - 1);} int nPr(int n, int r){ return fact(n) / fact(n - r);} // Driver codeint main(){ int n = 5; int r = 2; cout << n << "P" << r << " = " << nPr(n, r);} // This code is contributed by// Surendra_Gangwar
// Java program to calculate nPr import java.util.*; public class GFG { static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } static int nPr(int n, int r) { return fact(n) / fact(n - r); } public static void main(String args[]) { int n = 5; int r = 2; System.out.println(n + "P" + r + " = " + nPr(n, r)); }}
# Python3 program to calculate nPrimport mathdef fact(n): if (n <= 1): return 1 return n * fact(n - 1) def nPr(n, r): return math.floor(fact(n) / fact(n - r)) # Driver coden = 5r = 2 print(n, "P", r, "=", nPr(n, r)) # This code contributed by Rajput-Ji
// C# program to calculate nPrusing System; class GFG{ static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } static int nPr(int n, int r) { return fact(n) / fact(n - r); } public static void Main() { int n = 5; int r = 2; Console.WriteLine(n + "P" + r + " = " + nPr(n, r)); }} /* This code contributed by PrinciRaj1992 */
<?php// PHP program to calculate nPrfunction fact($n){ if ($n <= 1) return 1; return $n * fact($n - 1);} function nPr($n, $r){ return floor(fact($n) / fact($n - $r));} // Driver code$n = 5;$r = 2; echo $n, "P", $r, " = ", nPr($n, $r); // This code is contributed by Ryuga?>
// Javascript program to calculate nPrfunction fact(n){ if (n <= 1) return 1; return n * fact(n - 1);} function nPr(n, r){ return Math.floor(fact(n) / fact(n - r));} // Driver codelet n = 5;let r = 2; document.write(n, "P", r, " = ", nPr(n, r)); // This code is contributed by gfgking
5P2 = 20
Optimization for multiple queries of nPr If there are multiple queries for nPr, we may precompute factorial values and use the same for every call. This would avoid the computation of the same factorial values again and again.
princiraj1992
ankthon
Rajput-Ji
SURENDRA_GANGWAR
gfgking
factorial
Combinatorial
Java Programs
Combinatorial
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Print all distinct permutations of a given string with duplicates
Heap's Algorithm for generating permutations
Find all distinct subsets of a given set using BitMasking Approach
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 26179,
"s": 26151,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 26505,
"s": 26179,
"text": "Given two numbers n and r, the task is to find the value of nPr. nPr represents n permutation r which is calculated as n!/(n-k)!. Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! where “!” represents factorial. "
},
{
"code": null,
"e": 26526,
"s": 26505,
"text": "nPr = n! / (n - r)! "
},
{
"code": null,
"e": 26537,
"s": 26526,
"text": "Program: "
},
{
"code": null,
"e": 26541,
"s": 26537,
"text": "C++"
},
{
"code": null,
"e": 26546,
"s": 26541,
"text": "Java"
},
{
"code": null,
"e": 26554,
"s": 26546,
"text": "Python3"
},
{
"code": null,
"e": 26557,
"s": 26554,
"text": "C#"
},
{
"code": null,
"e": 26561,
"s": 26557,
"text": "PHP"
},
{
"code": null,
"e": 26572,
"s": 26561,
"text": "Javascript"
},
{
"code": "// CPP program to calculate nPr#include<bits/stdc++.h>using namespace std; int fact(int n){ if (n <= 1) return 1; return n * fact(n - 1);} int nPr(int n, int r){ return fact(n) / fact(n - r);} // Driver codeint main(){ int n = 5; int r = 2; cout << n << \"P\" << r << \" = \" << nPr(n, r);} // This code is contributed by// Surendra_Gangwar",
"e": 26935,
"s": 26572,
"text": null
},
{
"code": "// Java program to calculate nPr import java.util.*; public class GFG { static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } static int nPr(int n, int r) { return fact(n) / fact(n - r); } public static void main(String args[]) { int n = 5; int r = 2; System.out.println(n + \"P\" + r + \" = \" + nPr(n, r)); }}",
"e": 27372,
"s": 26935,
"text": null
},
{
"code": "# Python3 program to calculate nPrimport mathdef fact(n): if (n <= 1): return 1 return n * fact(n - 1) def nPr(n, r): return math.floor(fact(n) / fact(n - r)) # Driver coden = 5r = 2 print(n, \"P\", r, \"=\", nPr(n, r)) # This code contributed by Rajput-Ji",
"e": 27674,
"s": 27372,
"text": null
},
{
"code": "// C# program to calculate nPrusing System; class GFG{ static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } static int nPr(int n, int r) { return fact(n) / fact(n - r); } public static void Main() { int n = 5; int r = 2; Console.WriteLine(n + \"P\" + r + \" = \" + nPr(n, r)); }} /* This code contributed by PrinciRaj1992 */",
"e": 28122,
"s": 27674,
"text": null
},
{
"code": "<?php// PHP program to calculate nPrfunction fact($n){ if ($n <= 1) return 1; return $n * fact($n - 1);} function nPr($n, $r){ return floor(fact($n) / fact($n - $r));} // Driver code$n = 5;$r = 2; echo $n, \"P\", $r, \" = \", nPr($n, $r); // This code is contributed by Ryuga?>",
"e": 28441,
"s": 28122,
"text": null
},
{
"code": "// Javascript program to calculate nPrfunction fact(n){ if (n <= 1) return 1; return n * fact(n - 1);} function nPr(n, r){ return Math.floor(fact(n) / fact(n - r));} // Driver codelet n = 5;let r = 2; document.write(n, \"P\", r, \" = \", nPr(n, r)); // This code is contributed by gfgking",
"e": 28770,
"s": 28441,
"text": null
},
{
"code": null,
"e": 28779,
"s": 28770,
"text": "5P2 = 20"
},
{
"code": null,
"e": 29009,
"s": 28781,
"text": "Optimization for multiple queries of nPr If there are multiple queries for nPr, we may precompute factorial values and use the same for every call. This would avoid the computation of the same factorial values again and again. "
},
{
"code": null,
"e": 29023,
"s": 29009,
"text": "princiraj1992"
},
{
"code": null,
"e": 29031,
"s": 29023,
"text": "ankthon"
},
{
"code": null,
"e": 29041,
"s": 29031,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29058,
"s": 29041,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 29066,
"s": 29058,
"text": "gfgking"
},
{
"code": null,
"e": 29076,
"s": 29066,
"text": "factorial"
},
{
"code": null,
"e": 29090,
"s": 29076,
"text": "Combinatorial"
},
{
"code": null,
"e": 29104,
"s": 29090,
"text": "Java Programs"
},
{
"code": null,
"e": 29118,
"s": 29104,
"text": "Combinatorial"
},
{
"code": null,
"e": 29128,
"s": 29118,
"text": "factorial"
},
{
"code": null,
"e": 29226,
"s": 29128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29263,
"s": 29226,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 29320,
"s": 29263,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 29386,
"s": 29320,
"text": "Print all distinct permutations of a given string with duplicates"
},
{
"code": null,
"e": 29431,
"s": 29386,
"text": "Heap's Algorithm for generating permutations"
},
{
"code": null,
"e": 29498,
"s": 29431,
"text": "Find all distinct subsets of a given set using BitMasking Approach"
},
{
"code": null,
"e": 29526,
"s": 29498,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 29570,
"s": 29526,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 29596,
"s": 29570,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29630,
"s": 29596,
"text": "Convert Double to Integer in Java"
}
] |
Python2 vs Python3 | Syntax and performance Comparison - GeeksforGeeks | 28 Oct, 2019
Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards.
Still in dilemma?Ever wondered what separates both of them? Let’s find this thing out below.
First of all, let us go through this quick comparison through this image, which will give you a fair idea on what to expect.
Print Statement
Python 2.7: Extra pair of parenthesis is not mandatory in this.
print 'Hello and welcome to GeeksForGeeks'
Python 3.x: Extra pair of parenthesis is mandatory.
print ('Hello and welcome to GeeksForGeeks')
Integer Division
Python 2.7:The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, a classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are.
print 5 / 2print -5//2 # Output:# 2# -3
Python 3.x:Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you need to use // operator.
print (-5 / 2)print (5//2) # Output:# -2.5# 2
Input Function
Python 2.7:When you use input() function, Python automatically converts the data type based on your input.
val1 = input("Enter any number: ")val2 = input("Enter any string: ") type(val1)type(val2)
raw_input gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string.
val1 = raw_input("Enter any number: ")val2 = raw_input("Enter any string: ") type(val1)type(val2)
Python 3.xIn Python3, the input function acts like raw_input from Python 2.7 and it always returns string type.
val1 = input("Enter any number: ")val2 = input("Enter any string: ") type(val1)type(val2)# In order to fix this you need to apply # float() function when user is prompted for input.
Round Function
Python 2.7: The output always results in a floating point number.
print(round(69.9)) print(round(69.4)) # Output: # 70.0# 69.0
Python 3.x: The return results in n digit precision.
print(round(69.9)) print(round(69.4)) # Output:# 70# 69
List Comprehensions
Python 2.7: Refer to the example below, how global variable changes.
num = 7print (num) mylist = [num for num in range(100)]print (num) # Output:# 7# 99
Python 3.x: There is no namespace leak now. This is quite fixed now.
num = 7print (num) mylist = [num for num in range(100)]print (num) # Output: # 7# 7
Range Function
Python 2.7 :It has both range and xrange function. When you need to iterate one object at a time, use xrange and when you need an actual list, use range function. xrange is generally faster & saves memory.
% timeit [i for i in range(1000)] % timeit [i for i in xrange(1000)]
Python 3.x :Here range does what xrange does in Python 2.7. xrange doesn’t work in Python 3.x.
% timeit [i for i in range(1000)] % timeit [i for i in xrange(1000)]
Exception Handling
Python 2.7 : This has a different syntax than Python 3.x.
try: YoYoexcept NameError, error: print error, "YOU HAVE REACHED FOR AN ERROR" try: YoYoexcept NameError as error: print error, "YOU HAVE REACHED AN ERROR, YET AGAIN !"
Python 3.x: ‘As’ keyword is needed to be included in this.
try: YoYoexcept NameError as error: print (error, "THE ERROR HAS ARRIVED !")
List Comprehensions
Python 2.7: Lesser parenthesis than Python 3.x.
[item for item in 1, 2, 3, 4, 5][1, 2, 3, 4, 5]
Python 3.x: Extra pair of parenthesis is needed here.
[item for item in (1, 2, 3, 4, 5)][1, 2, 3, 4, 5]
next() function and .next() method
Python 2.7: Both next() and .next() are used here.
generator = (letter for letter in 'abcdefg')next(generator)generator.next()
Python 3.x: Only next() is used here. Using .next() shows an AttributeError.
generator = (letter for letter in 'abcdefg')next(generator)
ASCII, Unicode and Byte types
Python 2.7: It has ASCII string type, a separate unicode type, but there is no byte type.
type(unicode('a'))type(u'a')type(b'a')
Python 3.x: We have unicode strings, and byte type.
type(unicode('a'))# This returns an error
Note: List of Methods & Functions that don’t return list anymore in Python 3.x.
In Python2.x -
zip()
map()
filter()
dictionary’s .keys() method
dictionary’s .values() method
dictionary’s .items() method
Code_r
nidhi_biet
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25687,
"s": 25659,
"text": "\n28 Oct, 2019"
},
{
"code": null,
"e": 26017,
"s": 25687,
"text": "Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards."
},
{
"code": null,
"e": 26110,
"s": 26017,
"text": "Still in dilemma?Ever wondered what separates both of them? Let’s find this thing out below."
},
{
"code": null,
"e": 26235,
"s": 26110,
"text": "First of all, let us go through this quick comparison through this image, which will give you a fair idea on what to expect."
},
{
"code": null,
"e": 26251,
"s": 26235,
"text": "Print Statement"
},
{
"code": null,
"e": 26315,
"s": 26251,
"text": "Python 2.7: Extra pair of parenthesis is not mandatory in this."
},
{
"code": "print 'Hello and welcome to GeeksForGeeks'",
"e": 26358,
"s": 26315,
"text": null
},
{
"code": null,
"e": 26410,
"s": 26358,
"text": "Python 3.x: Extra pair of parenthesis is mandatory."
},
{
"code": "print ('Hello and welcome to GeeksForGeeks')",
"e": 26455,
"s": 26410,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26455,
"text": "Integer Division"
},
{
"code": null,
"e": 26816,
"s": 26472,
"text": "Python 2.7:The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, a classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are."
},
{
"code": "print 5 / 2print -5//2 # Output:# 2# -3",
"e": 26857,
"s": 26816,
"text": null
},
{
"code": null,
"e": 27016,
"s": 26857,
"text": "Python 3.x:Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you need to use // operator."
},
{
"code": "print (-5 / 2)print (5//2) # Output:# -2.5# 2",
"e": 27063,
"s": 27016,
"text": null
},
{
"code": null,
"e": 27078,
"s": 27063,
"text": "Input Function"
},
{
"code": null,
"e": 27185,
"s": 27078,
"text": "Python 2.7:When you use input() function, Python automatically converts the data type based on your input."
},
{
"code": "val1 = input(\"Enter any number: \")val2 = input(\"Enter any string: \") type(val1)type(val2)",
"e": 27276,
"s": 27185,
"text": null
},
{
"code": null,
"e": 27440,
"s": 27276,
"text": "raw_input gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string."
},
{
"code": " val1 = raw_input(\"Enter any number: \")val2 = raw_input(\"Enter any string: \") type(val1)type(val2)",
"e": 27542,
"s": 27440,
"text": null
},
{
"code": null,
"e": 27654,
"s": 27542,
"text": "Python 3.xIn Python3, the input function acts like raw_input from Python 2.7 and it always returns string type."
},
{
"code": "val1 = input(\"Enter any number: \")val2 = input(\"Enter any string: \") type(val1)type(val2)# In order to fix this you need to apply # float() function when user is prompted for input.",
"e": 27837,
"s": 27654,
"text": null
},
{
"code": null,
"e": 27852,
"s": 27837,
"text": "Round Function"
},
{
"code": null,
"e": 27918,
"s": 27852,
"text": "Python 2.7: The output always results in a floating point number."
},
{
"code": "print(round(69.9)) print(round(69.4)) # Output: # 70.0# 69.0",
"e": 27981,
"s": 27918,
"text": null
},
{
"code": null,
"e": 28034,
"s": 27981,
"text": "Python 3.x: The return results in n digit precision."
},
{
"code": "print(round(69.9)) print(round(69.4)) # Output:# 70# 69",
"e": 28092,
"s": 28034,
"text": null
},
{
"code": null,
"e": 28112,
"s": 28092,
"text": "List Comprehensions"
},
{
"code": null,
"e": 28181,
"s": 28112,
"text": "Python 2.7: Refer to the example below, how global variable changes."
},
{
"code": "num = 7print (num) mylist = [num for num in range(100)]print (num) # Output:# 7# 99",
"e": 28267,
"s": 28181,
"text": null
},
{
"code": null,
"e": 28336,
"s": 28267,
"text": "Python 3.x: There is no namespace leak now. This is quite fixed now."
},
{
"code": "num = 7print (num) mylist = [num for num in range(100)]print (num) # Output: # 7# 7",
"e": 28422,
"s": 28336,
"text": null
},
{
"code": null,
"e": 28437,
"s": 28422,
"text": "Range Function"
},
{
"code": null,
"e": 28643,
"s": 28437,
"text": "Python 2.7 :It has both range and xrange function. When you need to iterate one object at a time, use xrange and when you need an actual list, use range function. xrange is generally faster & saves memory."
},
{
"code": "% timeit [i for i in range(1000)] % timeit [i for i in xrange(1000)]",
"e": 28713,
"s": 28643,
"text": null
},
{
"code": null,
"e": 28808,
"s": 28713,
"text": "Python 3.x :Here range does what xrange does in Python 2.7. xrange doesn’t work in Python 3.x."
},
{
"code": "% timeit [i for i in range(1000)] % timeit [i for i in xrange(1000)]",
"e": 28878,
"s": 28808,
"text": null
},
{
"code": null,
"e": 28897,
"s": 28878,
"text": "Exception Handling"
},
{
"code": null,
"e": 28955,
"s": 28897,
"text": "Python 2.7 : This has a different syntax than Python 3.x."
},
{
"code": "try: YoYoexcept NameError, error: print error, \"YOU HAVE REACHED FOR AN ERROR\" try: YoYoexcept NameError as error: print error, \"YOU HAVE REACHED AN ERROR, YET AGAIN !\"",
"e": 29137,
"s": 28955,
"text": null
},
{
"code": null,
"e": 29196,
"s": 29137,
"text": "Python 3.x: ‘As’ keyword is needed to be included in this."
},
{
"code": "try: YoYoexcept NameError as error: print (error, \"THE ERROR HAS ARRIVED !\")",
"e": 29279,
"s": 29196,
"text": null
},
{
"code": null,
"e": 29299,
"s": 29279,
"text": "List Comprehensions"
},
{
"code": null,
"e": 29347,
"s": 29299,
"text": "Python 2.7: Lesser parenthesis than Python 3.x."
},
{
"code": "[item for item in 1, 2, 3, 4, 5][1, 2, 3, 4, 5]",
"e": 29395,
"s": 29347,
"text": null
},
{
"code": null,
"e": 29449,
"s": 29395,
"text": "Python 3.x: Extra pair of parenthesis is needed here."
},
{
"code": "[item for item in (1, 2, 3, 4, 5)][1, 2, 3, 4, 5]",
"e": 29499,
"s": 29449,
"text": null
},
{
"code": null,
"e": 29534,
"s": 29499,
"text": "next() function and .next() method"
},
{
"code": null,
"e": 29585,
"s": 29534,
"text": "Python 2.7: Both next() and .next() are used here."
},
{
"code": "generator = (letter for letter in 'abcdefg')next(generator)generator.next()",
"e": 29661,
"s": 29585,
"text": null
},
{
"code": null,
"e": 29738,
"s": 29661,
"text": "Python 3.x: Only next() is used here. Using .next() shows an AttributeError."
},
{
"code": "generator = (letter for letter in 'abcdefg')next(generator)",
"e": 29798,
"s": 29738,
"text": null
},
{
"code": null,
"e": 29828,
"s": 29798,
"text": "ASCII, Unicode and Byte types"
},
{
"code": null,
"e": 29918,
"s": 29828,
"text": "Python 2.7: It has ASCII string type, a separate unicode type, but there is no byte type."
},
{
"code": "type(unicode('a'))type(u'a')type(b'a')",
"e": 29957,
"s": 29918,
"text": null
},
{
"code": null,
"e": 30009,
"s": 29957,
"text": "Python 3.x: We have unicode strings, and byte type."
},
{
"code": "type(unicode('a'))# This returns an error",
"e": 30051,
"s": 30009,
"text": null
},
{
"code": null,
"e": 30131,
"s": 30051,
"text": "Note: List of Methods & Functions that don’t return list anymore in Python 3.x."
},
{
"code": null,
"e": 30257,
"s": 30131,
"text": "In Python2.x - \n\nzip()\nmap()\nfilter()\ndictionary’s .keys() method\ndictionary’s .values() method\ndictionary’s .items() method\n"
},
{
"code": null,
"e": 30264,
"s": 30257,
"text": "Code_r"
},
{
"code": null,
"e": 30275,
"s": 30264,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30289,
"s": 30275,
"text": "python-basics"
},
{
"code": null,
"e": 30296,
"s": 30289,
"text": "Python"
},
{
"code": null,
"e": 30394,
"s": 30296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30412,
"s": 30394,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30447,
"s": 30412,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30479,
"s": 30447,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30501,
"s": 30479,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30543,
"s": 30501,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30573,
"s": 30543,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30599,
"s": 30573,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30628,
"s": 30599,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30672,
"s": 30628,
"text": "Reading and Writing to text files in Python"
}
] |
Weird Number - GeeksforGeeks | 08 Sep, 2021
In number theory, a weird number is a natural number that is abundant but not semiperfect. In other words, the sum of the proper divisors (divisors including 1 but not itself) of the number is greater than the number, but no subset of those divisors sums to the number itself. Given a number N, the task is to check if the number is weird or not.
Examples:
Input: 40 Output: The number is not weird 1+4+5+10+20=40, hence it is not weird.
Input: 70 Output: The number is Weird The smallest weird number is 70. Its proper divisors are 1, 2, 5, 7, 10, 14, and 35; these sum to 74, but no subset of these sums to 70. The number 12, for example, is abundant but not weird, because the proper divisors of 12 are 1, 2, 3, 4, and 6, which sum to 16; but 2+4+6 = 12. The first few weird numbers are 70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, ...
Approach: Check if the number is abundant or not. The approach has been discussed here. Once the checking has been done, check if the number is semiperfect or not. The approach for checking semiperfect numbers has been discussed here. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if the// number is weird or not#include <bits/stdc++.h>using namespace std; // code to find all the factors of// the number excluding the number itselfvector<int> factors(int n){ // vector to store the factors vector<int> v; v.push_back(1); // note that this loop runs till sqrt(n) for (int i = 2; i <= sqrt(n); i++) { // if the value of i is a factor if (n % i == 0) { v.push_back(i); // condition to check the // divisor is not the number itself if (n / i != i) { v.push_back(n / i); } } } // return the vector return v;} // Function to check if the number// is abundant or notbool checkAbundant(int n){ vector<int> v; int sum = 0; // find the divisors using function v = factors(n); // sum all the factors for (int i = 0; i < v.size(); i++) { sum += v[i]; } // check for abundant or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notbool checkSemiPerfect(int n){ vector<int> v; // find the divisors v = factors(n); // sorting the vector sort(v.begin(), v.end()); int r = v.size(); // subset to check if no is semiperfect bool subset[r + 1][n + 1]; // initialising 1st column to true for (int i = 0; i <= r; i++) subset[i][0] = true; // initialing 1st row except zero position to 0 for (int i = 1; i <= n; i++) subset[0][i] = false; // loop to find whether the number is semiperfect for (int i = 1; i <= r; i++) { for (int j = 1; j <= n; j++) { // calculation to check if the // number can be made by summation of divisors if (j < v[i - 1]) subset[i][j] = subset[i - 1][j]; else { subset[i][j] = subset[i - 1][j] || subset[i - 1][j - v[i - 1]]; } } } // if not possible to make the // number by any combination of divisors if ((subset[r][n]) == 0) return false; else return true;} // Function to check for// weird or notbool checkweird(int n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codeint main(){ int n = 70; if (checkweird(n)) cout << "Weird Number"; else cout << "Not Weird Number"; return 0;}
// Java program to check if // the number is weird or notimport java.util.*;class GFG{// code to find all the// factors of the number// excluding the number itselfstatic ArrayList<Integer> factors(int n){ // ArrayList to store // the factors ArrayList<Integer> v = new ArrayList<Integer>(); v.add(1); // note that this loop // runs till sqrt(n) for (int i = 2; i <= Math.sqrt(n); i++) { // if the value of // i is a factor if (n % i == 0) { v.add(i); // condition to check // the divisor is not // the number itself if (n / i != i) { v.add(n / i); } } } // return the ArrayList return v;} // Function to check if the// number is abundant or notstatic boolean checkAbundant(int n){ ArrayList<Integer> v; int sum = 0; // find the divisors // using function v = factors(n); // sum all the factors for (int i = 0; i < v.size(); i++) { sum += v.get(i); } // check for abundant // or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notstatic boolean checkSemiPerfect(int n){ ArrayList<Integer> v; // find the divisors v = factors(n); // sorting the ArrayList Collections.sort(v); int r = v.size(); // subset to check if // no is semiperfect boolean subset[][] = new boolean[r + 1][n + 1]; // initialising 1st // column to true for (int i = 0; i <= r; i++) subset[i][0] = true; // initialing 1st row except // zero position to 0 for (int i = 1; i <= n; i++) subset[0][i] = false; // loop to find whether // the number is semiperfect for (int i = 1; i <= r; i++) { for (int j = 1; j <= n; j++) { // calculation to check // if the number can be // made by summation of // divisors if (j < v.get(i - 1)) subset[i][j] = subset[i - 1][j]; else { subset[i][j] = subset[i - 1][j] || subset[i - 1][j - v.get(i - 1)]; } } } // if not possible to make // the number by any // combination of divisors if ((subset[r][n]) == false) return false; else return true;} // Function to check// for weird or notstatic boolean checkweird(int n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codepublic static void main(String args[]){ int n = 70; if (checkweird(n)) System.out.println("Weird Number"); else System.out.println("Not Weird Number");}} // This code is contributed// by Arnab Kundu
# Python 3 program to check if the# number is weird or notfrom math import sqrt # code to find all the factors of# the number excluding the number itselfdef factors(n): # vector to store the factors v = [] v.append(1) # note that this loop runs till sqrt(n) for i in range(2, int(sqrt(n)) + 1, 1): # if the value of i is a factor if (n % i == 0): v.append(i); # condition to check the # divisor is not the number itself if (int(n / i) != i): v.append(int(n / i)) # return the vector return v # Function to check if the number# is abundant or notdef checkAbundant(n): sum = 0 # find the divisors using function v = factors(n) # sum all the factors for i in range(len(v)): sum += v[i] # check for abundant or not if (sum > n): return True else: return False # Function to check if the# number is semi-perfect or notdef checkSemiPerfect(n): # find the divisors v = factors(n) # sorting the vector v.sort(reverse = False) r = len(v) # subset to check if no is semiperfect subset = [[0 for i in range(n + 1)] for j in range(r + 1)] # initialising 1st column to true for i in range(r + 1): subset[i][0] = True # initialing 1st row except zero position to 0 for i in range(1, n + 1): subset[0][i] = False # loop to find whether the number is semiperfect for i in range(1, r + 1): for j in range(1, n + 1): # calculation to check if the # number can be made by summation of divisors if (j < v[i - 1]): subset[i][j] = subset[i - 1][j] else: subset[i][j] = (subset[i - 1][j] or subset[i - 1][j - v[i - 1]]) # if not possible to make the # number by any combination of divisors if ((subset[r][n]) == 0): return False else: return True # Function to check for# weird or notdef checkweird(n): if (checkAbundant(n) == True and checkSemiPerfect(n) == False): return True else: return False # Driver Codeif __name__ == '__main__': n = 70 if (checkweird(n)): print("Weird Number") else: print("Not Weird Number") # This code is contributed by# Surendra_Gangwar
// C# program to check if// the number is weird or notusing System;using System.Collections.Generic; class GFG{ // code to find all the// factors of the number// excluding the number itselfstatic List<int> factors(int n){ // List to store // the factors List<int> v = new List<int>(); v.Add(1); // note that this loop // runs till sqrt(n) for (int i = 2; i <= Math.Sqrt(n); i++) { // if the value of // i is a factor if (n % i == 0) { v.Add(i); // condition to check // the divisor is not // the number itself if (n / i != i) { v.Add(n / i); } } } // return the List return v;} // Function to check if the// number is abundant or notstatic Boolean checkAbundant(int n){ List<int> v; int sum = 0; // find the divisors // using function v = factors(n); // sum all the factors for (int i = 0; i < v.Count; i++) { sum += v[i]; } // check for abundant // or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notstatic Boolean checkSemiPerfect(int n){ List<int> v; // find the divisors v = factors(n); // sorting the List v.Sort(); int r = v.Count; // subset to check if // no is semiperfect Boolean [,]subset = new Boolean[r + 1,n + 1]; // initialising 1st // column to true for (int i = 0; i <= r; i++) subset[i,0] = true; // initialing 1st row except // zero position to 0 for (int i = 1; i <= n; i++) subset[0,i] = false; // loop to find whether // the number is semiperfect for (int i = 1; i <= r; i++) { for (int j = 1; j <= n; j++) { // calculation to check // if the number can be // made by summation of // divisors if (j < v[i-1]) subset[i,j] = subset[i - 1,j]; else { subset[i,j] = subset[i - 1,j] || subset[i - 1,j - v[i-1]]; } } } // if not possible to make // the number by any // combination of divisors if ((subset[r,n]) == false) return false; else return true;} // Function to check// for weird or notstatic Boolean checkweird(int n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codepublic static void Main(String []args){ int n = 70; if (checkweird(n)) Console.WriteLine("Weird Number"); else Console.WriteLine("Not Weird Number");}} // This code is contributed by Princi Singh
<script> // Javascript program to check if the// number is weird or not // code to find all the factors of// the number excluding the number itselffunction factors(n){ // vector to store the factors var v = []; v.push(1); // note that this loop runs till sqrt(n) for (var i = 2; i <= Math.sqrt(n); i++) { // if the value of i is a factor if (n % i == 0) { v.push(i); // condition to check the // divisor is not the number itself if (n / i != i) { v.push(n / i); } } } // return the vector return v;} // Function to check if the number// is abundant or notfunction checkAbundant(n){ var v = []; var sum = 0; // find the divisors using function v = factors(n); // sum all the factors for (var i = 0; i < v.length; i++) { sum += v[i]; } // check for abundant or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notfunction checkSemiPerfect(n){ var v = []; // find the divisors v = factors(n); // sorting the vector v.sort() var r = v.length; // subset to check if no is semiperfect var subset = Array.from(Array(r+1), ()=>Array(n+1)); // initialising 1st column to true for (var i = 0; i <= r; i++) subset[i][0] = true; // initialing 1st row except zero position to 0 for (var i = 1; i <= n; i++) subset[0][i] = false; // loop to find whether the number is semiperfect for (var i = 1; i <= r; i++) { for (var j = 1; j <= n; j++) { // calculation to check if the // number can be made by summation of divisors if (j < v[i - 1]) subset[i][j] = subset[i - 1][j]; else { subset[i][j] = subset[i - 1][j] || subset[i - 1][j - v[i - 1]]; } } } // if not possible to make the // number by any combination of divisors if ((subset[r][n]) == 0) return false; else return true;} // Function to check for// weird or notfunction checkweird(n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codevar n = 70;if (checkweird(n)) document.write( "Weird Number");else document.write( "Not Weird Number"); </script>
Weird Number
Time Complexity: O(N * number of factors) Auxiliary Space: O(N * number of factors)
andrew1234
SURENDRA_GANGWAR
princi singh
rutvik_56
gulshankumarar231
surindertarika1234
simmytarika5
Algorithms-Dynamic Programming
factor
Numbers
subset
Dynamic Programming
Dynamic Programming
subset
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1
Maximum size square sub-matrix with all 1s | [
{
"code": null,
"e": 25979,
"s": 25951,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 26327,
"s": 25979,
"text": "In number theory, a weird number is a natural number that is abundant but not semiperfect. In other words, the sum of the proper divisors (divisors including 1 but not itself) of the number is greater than the number, but no subset of those divisors sums to the number itself. Given a number N, the task is to check if the number is weird or not. "
},
{
"code": null,
"e": 26338,
"s": 26327,
"text": "Examples: "
},
{
"code": null,
"e": 26420,
"s": 26338,
"text": "Input: 40 Output: The number is not weird 1+4+5+10+20=40, hence it is not weird. "
},
{
"code": null,
"e": 26892,
"s": 26420,
"text": "Input: 70 Output: The number is Weird The smallest weird number is 70. Its proper divisors are 1, 2, 5, 7, 10, 14, and 35; these sum to 74, but no subset of these sums to 70. The number 12, for example, is abundant but not weird, because the proper divisors of 12 are 1, 2, 3, 4, and 6, which sum to 16; but 2+4+6 = 12. The first few weird numbers are 70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, ..."
},
{
"code": null,
"e": 27179,
"s": 26892,
"text": "Approach: Check if the number is abundant or not. The approach has been discussed here. Once the checking has been done, check if the number is semiperfect or not. The approach for checking semiperfect numbers has been discussed here. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27183,
"s": 27179,
"text": "C++"
},
{
"code": null,
"e": 27188,
"s": 27183,
"text": "Java"
},
{
"code": null,
"e": 27196,
"s": 27188,
"text": "Python3"
},
{
"code": null,
"e": 27199,
"s": 27196,
"text": "C#"
},
{
"code": null,
"e": 27210,
"s": 27199,
"text": "Javascript"
},
{
"code": "// C++ program to check if the// number is weird or not#include <bits/stdc++.h>using namespace std; // code to find all the factors of// the number excluding the number itselfvector<int> factors(int n){ // vector to store the factors vector<int> v; v.push_back(1); // note that this loop runs till sqrt(n) for (int i = 2; i <= sqrt(n); i++) { // if the value of i is a factor if (n % i == 0) { v.push_back(i); // condition to check the // divisor is not the number itself if (n / i != i) { v.push_back(n / i); } } } // return the vector return v;} // Function to check if the number// is abundant or notbool checkAbundant(int n){ vector<int> v; int sum = 0; // find the divisors using function v = factors(n); // sum all the factors for (int i = 0; i < v.size(); i++) { sum += v[i]; } // check for abundant or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notbool checkSemiPerfect(int n){ vector<int> v; // find the divisors v = factors(n); // sorting the vector sort(v.begin(), v.end()); int r = v.size(); // subset to check if no is semiperfect bool subset[r + 1][n + 1]; // initialising 1st column to true for (int i = 0; i <= r; i++) subset[i][0] = true; // initialing 1st row except zero position to 0 for (int i = 1; i <= n; i++) subset[0][i] = false; // loop to find whether the number is semiperfect for (int i = 1; i <= r; i++) { for (int j = 1; j <= n; j++) { // calculation to check if the // number can be made by summation of divisors if (j < v[i - 1]) subset[i][j] = subset[i - 1][j]; else { subset[i][j] = subset[i - 1][j] || subset[i - 1][j - v[i - 1]]; } } } // if not possible to make the // number by any combination of divisors if ((subset[r][n]) == 0) return false; else return true;} // Function to check for// weird or notbool checkweird(int n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codeint main(){ int n = 70; if (checkweird(n)) cout << \"Weird Number\"; else cout << \"Not Weird Number\"; return 0;}",
"e": 29709,
"s": 27210,
"text": null
},
{
"code": "// Java program to check if // the number is weird or notimport java.util.*;class GFG{// code to find all the// factors of the number// excluding the number itselfstatic ArrayList<Integer> factors(int n){ // ArrayList to store // the factors ArrayList<Integer> v = new ArrayList<Integer>(); v.add(1); // note that this loop // runs till sqrt(n) for (int i = 2; i <= Math.sqrt(n); i++) { // if the value of // i is a factor if (n % i == 0) { v.add(i); // condition to check // the divisor is not // the number itself if (n / i != i) { v.add(n / i); } } } // return the ArrayList return v;} // Function to check if the// number is abundant or notstatic boolean checkAbundant(int n){ ArrayList<Integer> v; int sum = 0; // find the divisors // using function v = factors(n); // sum all the factors for (int i = 0; i < v.size(); i++) { sum += v.get(i); } // check for abundant // or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notstatic boolean checkSemiPerfect(int n){ ArrayList<Integer> v; // find the divisors v = factors(n); // sorting the ArrayList Collections.sort(v); int r = v.size(); // subset to check if // no is semiperfect boolean subset[][] = new boolean[r + 1][n + 1]; // initialising 1st // column to true for (int i = 0; i <= r; i++) subset[i][0] = true; // initialing 1st row except // zero position to 0 for (int i = 1; i <= n; i++) subset[0][i] = false; // loop to find whether // the number is semiperfect for (int i = 1; i <= r; i++) { for (int j = 1; j <= n; j++) { // calculation to check // if the number can be // made by summation of // divisors if (j < v.get(i - 1)) subset[i][j] = subset[i - 1][j]; else { subset[i][j] = subset[i - 1][j] || subset[i - 1][j - v.get(i - 1)]; } } } // if not possible to make // the number by any // combination of divisors if ((subset[r][n]) == false) return false; else return true;} // Function to check// for weird or notstatic boolean checkweird(int n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codepublic static void main(String args[]){ int n = 70; if (checkweird(n)) System.out.println(\"Weird Number\"); else System.out.println(\"Not Weird Number\");}} // This code is contributed// by Arnab Kundu",
"e": 32589,
"s": 29709,
"text": null
},
{
"code": "# Python 3 program to check if the# number is weird or notfrom math import sqrt # code to find all the factors of# the number excluding the number itselfdef factors(n): # vector to store the factors v = [] v.append(1) # note that this loop runs till sqrt(n) for i in range(2, int(sqrt(n)) + 1, 1): # if the value of i is a factor if (n % i == 0): v.append(i); # condition to check the # divisor is not the number itself if (int(n / i) != i): v.append(int(n / i)) # return the vector return v # Function to check if the number# is abundant or notdef checkAbundant(n): sum = 0 # find the divisors using function v = factors(n) # sum all the factors for i in range(len(v)): sum += v[i] # check for abundant or not if (sum > n): return True else: return False # Function to check if the# number is semi-perfect or notdef checkSemiPerfect(n): # find the divisors v = factors(n) # sorting the vector v.sort(reverse = False) r = len(v) # subset to check if no is semiperfect subset = [[0 for i in range(n + 1)] for j in range(r + 1)] # initialising 1st column to true for i in range(r + 1): subset[i][0] = True # initialing 1st row except zero position to 0 for i in range(1, n + 1): subset[0][i] = False # loop to find whether the number is semiperfect for i in range(1, r + 1): for j in range(1, n + 1): # calculation to check if the # number can be made by summation of divisors if (j < v[i - 1]): subset[i][j] = subset[i - 1][j] else: subset[i][j] = (subset[i - 1][j] or subset[i - 1][j - v[i - 1]]) # if not possible to make the # number by any combination of divisors if ((subset[r][n]) == 0): return False else: return True # Function to check for# weird or notdef checkweird(n): if (checkAbundant(n) == True and checkSemiPerfect(n) == False): return True else: return False # Driver Codeif __name__ == '__main__': n = 70 if (checkweird(n)): print(\"Weird Number\") else: print(\"Not Weird Number\") # This code is contributed by# Surendra_Gangwar",
"e": 34982,
"s": 32589,
"text": null
},
{
"code": "// C# program to check if// the number is weird or notusing System;using System.Collections.Generic; class GFG{ // code to find all the// factors of the number// excluding the number itselfstatic List<int> factors(int n){ // List to store // the factors List<int> v = new List<int>(); v.Add(1); // note that this loop // runs till sqrt(n) for (int i = 2; i <= Math.Sqrt(n); i++) { // if the value of // i is a factor if (n % i == 0) { v.Add(i); // condition to check // the divisor is not // the number itself if (n / i != i) { v.Add(n / i); } } } // return the List return v;} // Function to check if the// number is abundant or notstatic Boolean checkAbundant(int n){ List<int> v; int sum = 0; // find the divisors // using function v = factors(n); // sum all the factors for (int i = 0; i < v.Count; i++) { sum += v[i]; } // check for abundant // or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notstatic Boolean checkSemiPerfect(int n){ List<int> v; // find the divisors v = factors(n); // sorting the List v.Sort(); int r = v.Count; // subset to check if // no is semiperfect Boolean [,]subset = new Boolean[r + 1,n + 1]; // initialising 1st // column to true for (int i = 0; i <= r; i++) subset[i,0] = true; // initialing 1st row except // zero position to 0 for (int i = 1; i <= n; i++) subset[0,i] = false; // loop to find whether // the number is semiperfect for (int i = 1; i <= r; i++) { for (int j = 1; j <= n; j++) { // calculation to check // if the number can be // made by summation of // divisors if (j < v[i-1]) subset[i,j] = subset[i - 1,j]; else { subset[i,j] = subset[i - 1,j] || subset[i - 1,j - v[i-1]]; } } } // if not possible to make // the number by any // combination of divisors if ((subset[r,n]) == false) return false; else return true;} // Function to check// for weird or notstatic Boolean checkweird(int n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codepublic static void Main(String []args){ int n = 70; if (checkweird(n)) Console.WriteLine(\"Weird Number\"); else Console.WriteLine(\"Not Weird Number\");}} // This code is contributed by Princi Singh",
"e": 37786,
"s": 34982,
"text": null
},
{
"code": "<script> // Javascript program to check if the// number is weird or not // code to find all the factors of// the number excluding the number itselffunction factors(n){ // vector to store the factors var v = []; v.push(1); // note that this loop runs till sqrt(n) for (var i = 2; i <= Math.sqrt(n); i++) { // if the value of i is a factor if (n % i == 0) { v.push(i); // condition to check the // divisor is not the number itself if (n / i != i) { v.push(n / i); } } } // return the vector return v;} // Function to check if the number// is abundant or notfunction checkAbundant(n){ var v = []; var sum = 0; // find the divisors using function v = factors(n); // sum all the factors for (var i = 0; i < v.length; i++) { sum += v[i]; } // check for abundant or not if (sum > n) return true; else return false;} // Function to check if the// number is semi-perfect or notfunction checkSemiPerfect(n){ var v = []; // find the divisors v = factors(n); // sorting the vector v.sort() var r = v.length; // subset to check if no is semiperfect var subset = Array.from(Array(r+1), ()=>Array(n+1)); // initialising 1st column to true for (var i = 0; i <= r; i++) subset[i][0] = true; // initialing 1st row except zero position to 0 for (var i = 1; i <= n; i++) subset[0][i] = false; // loop to find whether the number is semiperfect for (var i = 1; i <= r; i++) { for (var j = 1; j <= n; j++) { // calculation to check if the // number can be made by summation of divisors if (j < v[i - 1]) subset[i][j] = subset[i - 1][j]; else { subset[i][j] = subset[i - 1][j] || subset[i - 1][j - v[i - 1]]; } } } // if not possible to make the // number by any combination of divisors if ((subset[r][n]) == 0) return false; else return true;} // Function to check for// weird or notfunction checkweird(n){ if (checkAbundant(n) == true && checkSemiPerfect(n) == false) return true; else return false;} // Driver Codevar n = 70;if (checkweird(n)) document.write( \"Weird Number\");else document.write( \"Not Weird Number\"); </script>",
"e": 40223,
"s": 37786,
"text": null
},
{
"code": null,
"e": 40236,
"s": 40223,
"text": "Weird Number"
},
{
"code": null,
"e": 40323,
"s": 40238,
"text": "Time Complexity: O(N * number of factors) Auxiliary Space: O(N * number of factors) "
},
{
"code": null,
"e": 40334,
"s": 40323,
"text": "andrew1234"
},
{
"code": null,
"e": 40351,
"s": 40334,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 40364,
"s": 40351,
"text": "princi singh"
},
{
"code": null,
"e": 40374,
"s": 40364,
"text": "rutvik_56"
},
{
"code": null,
"e": 40392,
"s": 40374,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 40411,
"s": 40392,
"text": "surindertarika1234"
},
{
"code": null,
"e": 40424,
"s": 40411,
"text": "simmytarika5"
},
{
"code": null,
"e": 40455,
"s": 40424,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 40462,
"s": 40455,
"text": "factor"
},
{
"code": null,
"e": 40470,
"s": 40462,
"text": "Numbers"
},
{
"code": null,
"e": 40477,
"s": 40470,
"text": "subset"
},
{
"code": null,
"e": 40497,
"s": 40477,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 40517,
"s": 40497,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 40524,
"s": 40517,
"text": "subset"
},
{
"code": null,
"e": 40532,
"s": 40524,
"text": "Numbers"
},
{
"code": null,
"e": 40630,
"s": 40532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40661,
"s": 40630,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 40694,
"s": 40661,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 40713,
"s": 40694,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 40748,
"s": 40713,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 40786,
"s": 40748,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 40854,
"s": 40786,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 40875,
"s": 40854,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 40897,
"s": 40875,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 40960,
"s": 40897,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
}
] |
Python | Sorting URL on basis of Top Level Domain - GeeksforGeeks | 11 May, 2020
Given a list of URL, the task is to sort the URL in the list based on the top-level domain.A top-level domain (TLD) is one of the domains at the highest level in the hierarchical Domain Name System of the Internet. Example – org, com, edu.This is mostly used in a case where we have to scrap the pages and sort URL according to top-level domain. It is widely used in open-source projects and serves as handy snippet for use.
Input :
url = ["https://www.isb.edu", "www.google.com",
"http://cyware.com", "https://www.gst.in",
"https://www.coursera.org", "https://www.create.net",
"https://www.ontariocolleges.ca"]
Output :
['https://www.ontariocolleges.ca', 'www.google.com',
'http://cyware.com', 'https://www.isb.edu',
'https://www.gst.in', 'https://www.create.net',
'https://www.coursera.org']
Explanation:
The Tld for the above list is in sorted order
['.ca','.com','.com','.edu','.in','.net','.org']
Below are some ways to do the above task.
Method 1: Using sortedYou can split the input and then use sorting to sort according to TLD.
#Python code to sort the URL in the list based on the top-level domain. #Url list initializationInput = ["https://www.isb.edu", "www.google.com", "http://cyware.com", "https://www.gst.in", "https://www.coursera.org", "https://www.create.net", "https://www.ontariocolleges.ca"] #Function to sort in tld orderdef tld(Input): return Input.split('.')[-1] #Using sorted and calling functionOutput = sorted(Input,key=tld) #Printing outputprint("Initial list is :")print(Input)print("sorted list according to TLD is")print(Output)
Initial list is :
['https://www.isb.edu', 'www.google.com', 'http://cyware.com',
'https://www.gst.in', 'https://www.coursera.org',
'https://www.create.net', 'https://www.ontariocolleges.ca']
Sorted list according to TLD is :
['https://www.ontariocolleges.ca', 'www.google.com',
'http://cyware.com', 'https://www.isb.edu',
'https://www.gst.in', 'https://www.create.net', 'https://www.coursera.org']
Method 2: Using LambdaThe most concise and readable way to sort the URL in the list based on the top-level domain is using lambda.
#Python code to sort the URL in the list based on the top-level domain. #Url list initializationInput = ["https://www.isb.edu", "www.google.com", "http://cyware.com","https://www.gst.in", "https://www.coursera.org","https://www.create.net", "https://www.ontariocolleges.ca"] #Using lambda and sorted Output = sorted(Input,key=lambda x: x.split('.')[-1]) #Printing outputprint("Initial list is :")print(Input)print("sorted list according to TLD is")print(Output)
Initial list is :
['https://www.isb.edu', 'www.google.com', 'http://cyware.com',
'https://www.gst.in', 'https://www.coursera.org',
'https://www.create.net', 'https://www.ontariocolleges.ca']
Sorted list according to TLD is :
['https://www.ontariocolleges.ca', 'www.google.com',
'http://cyware.com', 'https://www.isb.edu',
'https://www.gst.in', 'https://www.create.net', 'https://www.coursera.org']
Method 3: Using reversedReversing the input and splitting it and then applying a sort to sort URL according to TLD
#Python code to sort the URL in the list based on the top-level domain. #Url list initializationInput = ["https://www.isb.edu", "www.google.com", "http://cyware.com","https://www.gst.in", "https://www.coursera.org","https://www.create.net", "https://www.ontariocolleges.ca"] #Internal function for reverseddef internal(string): return list(reversed(string.split('.'))) #Using sorted and calling internal for reversedOutput = sorted(Input, key=internal) #Printing outputprint("Initial list is :")print(Input)print("sorted list according to TLD is")print(Output)
Initial list is :
['https://www.isb.edu', 'www.google.com', 'http://cyware.com',
'https://www.gst.in', 'https://www.coursera.org',
'https://www.create.net', 'https://www.ontariocolleges.ca']
Sorted list according to TLD is :
['https://www.ontariocolleges.ca', 'www.google.com',
'http://cyware.com', 'https://www.isb.edu',
'https://www.gst.in', 'https://www.create.net', 'https://www.coursera.org']
Python-sort
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python | [
{
"code": null,
"e": 26471,
"s": 26443,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 26896,
"s": 26471,
"text": "Given a list of URL, the task is to sort the URL in the list based on the top-level domain.A top-level domain (TLD) is one of the domains at the highest level in the hierarchical Domain Name System of the Internet. Example – org, com, edu.This is mostly used in a case where we have to scrap the pages and sort URL according to top-level domain. It is widely used in open-source projects and serves as handy snippet for use."
},
{
"code": null,
"e": 27383,
"s": 26896,
"text": "Input :\nurl = [\"https://www.isb.edu\", \"www.google.com\", \n\"http://cyware.com\", \"https://www.gst.in\", \n\"https://www.coursera.org\", \"https://www.create.net\", \n\"https://www.ontariocolleges.ca\"]\n\nOutput :\n['https://www.ontariocolleges.ca', 'www.google.com', \n'http://cyware.com', 'https://www.isb.edu', \n'https://www.gst.in', 'https://www.create.net',\n 'https://www.coursera.org']\n\nExplanation:\nThe Tld for the above list is in sorted order\n['.ca','.com','.com','.edu','.in','.net','.org']\n\n"
},
{
"code": null,
"e": 27425,
"s": 27383,
"text": "Below are some ways to do the above task."
},
{
"code": null,
"e": 27518,
"s": 27425,
"text": "Method 1: Using sortedYou can split the input and then use sorting to sort according to TLD."
},
{
"code": "#Python code to sort the URL in the list based on the top-level domain. #Url list initializationInput = [\"https://www.isb.edu\", \"www.google.com\", \"http://cyware.com\", \"https://www.gst.in\", \"https://www.coursera.org\", \"https://www.create.net\", \"https://www.ontariocolleges.ca\"] #Function to sort in tld orderdef tld(Input): return Input.split('.')[-1] #Using sorted and calling functionOutput = sorted(Input,key=tld) #Printing outputprint(\"Initial list is :\")print(Input)print(\"sorted list according to TLD is\")print(Output)",
"e": 28049,
"s": 27518,
"text": null
},
{
"code": null,
"e": 28455,
"s": 28049,
"text": "Initial list is :\n\n['https://www.isb.edu', 'www.google.com', 'http://cyware.com',\n 'https://www.gst.in', 'https://www.coursera.org', \n'https://www.create.net', 'https://www.ontariocolleges.ca']\n\nSorted list according to TLD is :\n\n['https://www.ontariocolleges.ca', 'www.google.com', \n'http://cyware.com', 'https://www.isb.edu',\n 'https://www.gst.in', 'https://www.create.net', 'https://www.coursera.org']\n"
},
{
"code": null,
"e": 28586,
"s": 28455,
"text": "Method 2: Using LambdaThe most concise and readable way to sort the URL in the list based on the top-level domain is using lambda."
},
{
"code": "#Python code to sort the URL in the list based on the top-level domain. #Url list initializationInput = [\"https://www.isb.edu\", \"www.google.com\", \"http://cyware.com\",\"https://www.gst.in\", \"https://www.coursera.org\",\"https://www.create.net\", \"https://www.ontariocolleges.ca\"] #Using lambda and sorted Output = sorted(Input,key=lambda x: x.split('.')[-1]) #Printing outputprint(\"Initial list is :\")print(Input)print(\"sorted list according to TLD is\")print(Output)",
"e": 29051,
"s": 28586,
"text": null
},
{
"code": null,
"e": 29457,
"s": 29051,
"text": "Initial list is :\n\n['https://www.isb.edu', 'www.google.com', 'http://cyware.com',\n 'https://www.gst.in', 'https://www.coursera.org', \n'https://www.create.net', 'https://www.ontariocolleges.ca']\n\nSorted list according to TLD is :\n\n['https://www.ontariocolleges.ca', 'www.google.com', \n'http://cyware.com', 'https://www.isb.edu',\n 'https://www.gst.in', 'https://www.create.net', 'https://www.coursera.org']\n"
},
{
"code": null,
"e": 29572,
"s": 29457,
"text": "Method 3: Using reversedReversing the input and splitting it and then applying a sort to sort URL according to TLD"
},
{
"code": "#Python code to sort the URL in the list based on the top-level domain. #Url list initializationInput = [\"https://www.isb.edu\", \"www.google.com\", \"http://cyware.com\",\"https://www.gst.in\", \"https://www.coursera.org\",\"https://www.create.net\", \"https://www.ontariocolleges.ca\"] #Internal function for reverseddef internal(string): return list(reversed(string.split('.'))) #Using sorted and calling internal for reversedOutput = sorted(Input, key=internal) #Printing outputprint(\"Initial list is :\")print(Input)print(\"sorted list according to TLD is\")print(Output)",
"e": 30140,
"s": 29572,
"text": null
},
{
"code": null,
"e": 30547,
"s": 30140,
"text": "Initial list is :\n\n['https://www.isb.edu', 'www.google.com', 'http://cyware.com',\n 'https://www.gst.in', 'https://www.coursera.org', \n'https://www.create.net', 'https://www.ontariocolleges.ca']\n\nSorted list according to TLD is :\n\n['https://www.ontariocolleges.ca', 'www.google.com', \n'http://cyware.com', 'https://www.isb.edu',\n 'https://www.gst.in', 'https://www.create.net', 'https://www.coursera.org']\n\n"
},
{
"code": null,
"e": 30559,
"s": 30547,
"text": "Python-sort"
},
{
"code": null,
"e": 30566,
"s": 30559,
"text": "Python"
},
{
"code": null,
"e": 30664,
"s": 30566,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30682,
"s": 30664,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30714,
"s": 30682,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30749,
"s": 30714,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30771,
"s": 30749,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30813,
"s": 30771,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30843,
"s": 30813,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30869,
"s": 30843,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30913,
"s": 30869,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 30942,
"s": 30913,
"text": "*args and **kwargs in Python"
}
] |
Chain Multiple Decorators in Python - GeeksforGeeks | 08 Jun, 2020
Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality.
So, here in this post we are going to learn about Decorator Chaining. Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for resuabale building blocks as it accumulates the several effects together. It is also knows as nested decorators in Python.
Syntax:
@decor1
@decor
def num():
statement(s)
Example: For num() function we are applying 2 decorator functions. Firstly the inner decorator will work and then the outer decorator.
Python3
# code for testing decorator chainingdef decor1(func): def inner(): x = func() return x * x return inner def decor(func): def inner(): x = func() return 2 * x return inner @decor1@decordef num(): return 10 print(num())
Output:
400
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 25823,
"s": 25673,
"text": "Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality."
},
{
"code": null,
"e": 26194,
"s": 25823,
"text": "So, here in this post we are going to learn about Decorator Chaining. Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for resuabale building blocks as it accumulates the several effects together. It is also knows as nested decorators in Python."
},
{
"code": null,
"e": 26203,
"s": 26194,
"text": "Syntax: "
},
{
"code": null,
"e": 26250,
"s": 26203,
"text": "@decor1\n@decor\ndef num():\n statement(s) "
},
{
"code": null,
"e": 26385,
"s": 26250,
"text": "Example: For num() function we are applying 2 decorator functions. Firstly the inner decorator will work and then the outer decorator."
},
{
"code": null,
"e": 26393,
"s": 26385,
"text": "Python3"
},
{
"code": "# code for testing decorator chainingdef decor1(func): def inner(): x = func() return x * x return inner def decor(func): def inner(): x = func() return 2 * x return inner @decor1@decordef num(): return 10 print(num())",
"e": 26658,
"s": 26393,
"text": null
},
{
"code": null,
"e": 26666,
"s": 26658,
"text": "Output:"
},
{
"code": null,
"e": 26670,
"s": 26666,
"text": "400"
},
{
"code": null,
"e": 26688,
"s": 26670,
"text": "Python Decorators"
},
{
"code": null,
"e": 26695,
"s": 26688,
"text": "Python"
},
{
"code": null,
"e": 26793,
"s": 26695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26811,
"s": 26793,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26846,
"s": 26811,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26878,
"s": 26846,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26900,
"s": 26878,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26942,
"s": 26900,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26972,
"s": 26942,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26998,
"s": 26972,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27027,
"s": 26998,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27071,
"s": 27027,
"text": "Reading and Writing to text files in Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.