title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How do I pass options to the Selenium Chrome driver using Python?
|
We can pass options to the Selenium Chrome driver using Python. This can be with the help of the ChromeOptions and the DesiredCapabilities class. For the ChromeOptions, we have to create an object for that class.
Then we shall take the help of the add_argument method and pass the option we want to send to the browser as a parameter to the method. Finally, this information must be given to the web driver.
Code Implementation.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
#object of ChromeOptions
op = webdriver.ChromeOptions()
#add option
op.add_argument('--enable-extensions')
#pass option to webdriver object
driver = webdriver.Chrome(chrome_options=op)
We can also add capabilities with the help of DesiredCapabilities class.
Code Implementation.
#object of DesiredCapabilities
c = webdriver.DesiredCapabilities.Chrome.copy()
#set capability to True
c['acceptInsecureCerts'] = True
#pass capability to webdriver object
driver = webdriver.Chrome(desired_capabilities=c)
In this way, we can pass the Chrome options.
|
[
{
"code": null,
"e": 1275,
"s": 1062,
"text": "We can pass options to the Selenium Chrome driver using Python. This can be with the help of the ChromeOptions and the DesiredCapabilities class. For the ChromeOptions, we have to create an object for that class."
},
{
"code": null,
"e": 1470,
"s": 1275,
"text": "Then we shall take the help of the add_argument method and pass the option we want to send to the browser as a parameter to the method. Finally, this information must be given to the web driver."
},
{
"code": null,
"e": 1491,
"s": 1470,
"text": "Code Implementation."
},
{
"code": null,
"e": 1778,
"s": 1491,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options as ChromeOptions\n#object of ChromeOptions\nop = webdriver.ChromeOptions()\n#add option\nop.add_argument('--enable-extensions')\n#pass option to webdriver object\ndriver = webdriver.Chrome(chrome_options=op)"
},
{
"code": null,
"e": 1851,
"s": 1778,
"text": "We can also add capabilities with the help of DesiredCapabilities class."
},
{
"code": null,
"e": 1872,
"s": 1851,
"text": "Code Implementation."
},
{
"code": null,
"e": 2095,
"s": 1872,
"text": "#object of DesiredCapabilities\nc = webdriver.DesiredCapabilities.Chrome.copy()\n\n#set capability to True\nc['acceptInsecureCerts'] = True\n#pass capability to webdriver object\ndriver = webdriver.Chrome(desired_capabilities=c)"
},
{
"code": null,
"e": 2140,
"s": 2095,
"text": "In this way, we can pass the Chrome options."
}
] |
Anomaly detection with Local Outlier Factor (LOF) | by Mahbubul Alam | Towards Data Science
|
Today’s article is my 5th in a series of “bite-size” article I am writing on different techniques used for anomaly detection. If you are interested, the following are the previous four articles:
Z-score for anomaly detection
Boxplot for anomaly detection
Statistical techniques for anomaly detection
Time series anomaly detection with “anomalize” library
Today I am going beyond statistical techniques and stepping into machine learning algorithms for anomaly detection.
LOF is an unsupervised (well, semi-supervised) machine learning algorithm that uses the density of data points in the distribution as a key factor to detect outliers.
LOF compares the density of any given data point to the density of its neighbors. Since outliers come from low-density areas, the ratio will be higher for anomalous data points. As a rule of thumb, a normal data point has a LOF between 1 and 1.5 whereas anomalous observations will have much higher LOF. The higher the LOF the more likely it is an outlier. If the LOF of point X is 5, it means the average density of X’s neighbors is 5 times higher than its local density.
In mathematical terms,
LOF(X)=[(LRD(1st neighbor) + LRD(2nd neighbor ) + .................+ LRD(kth neighbor))/LRD(X)]/k
where LRD is Local Reachability Distance and is computed as follows.
LRD(X) = 1/(sum of Reachability Distance (X, n))/k)where n is neighbors upto k
The algorithm has four different components:
Hyperparameter k: determines the number of neighbors
Reachability distance: distances measured using 3 methods — Euclid, Minkowski, Manhattan
Local reachability distance: (LRD) (X) = 1/(sum of Reachability Distance (X, n))/k), where n is neighbors upto k
Local Outlier Factor (LOF)
Enough of theory and mathematics. If you didn’t understand much of it, no hard feelings. As I use to say, to drive a car we don’t need to know about its mechanics, but we do need to know how to drive! So jump right into the next section on the implementation of LOF in Python.
We are going to implement LOF for anomaly detection in Python environment using Scikit-Learn library. Let’s first import the required libraries:
# data preparationimport pandas as pdimport numpy as np# data visualzationimport matplotlib.pyplot as pltimport seaborn as sns# outlier/anomaly detectionfrom sklearn.neighbors import LocalOutlierFactor
Now let’s create a hypothetical dataset containing 5 data points.
# datadf = pd.DataFrame(np.array([[0,1], [1,1], [1,2], [2,2], [5,6]]), columns = ["x", "y"], index = [0,1,2,3,4])
If you plot the data points, finding out the outlier with visual inspection is not so difficult.
# plot data pointsplt.scatter(df["x"], df["y"], color = "b", s = 65)plt.grid()
So indeed, we don’t need a machine learning algorithm to find out that the 5th data point is an outlier. But let’s see if the algorithm can detect it.
# model specificationmodel1 = LocalOutlierFactor(n_neighbors = 2, metric = "manhattan", contamination = 0.02)# model fittingy_pred = model1.fit_predict(df)# filter outlier indexoutlier_index = where(y_pred == -1) # negative values are outliers and positives inliers# filter outlier valuesoutlier_values = df.iloc[outlier_index]# plot dataplt.scatter(df["x"], df["y"], color = "b", s = 65)# plot outlier valuesplt.scatter(outlier_values["x"], outlier_values["y"], color = "r")
There you go! The algorithm correctly detected the outlier.
The purpose of this article was to introduce a density-based anomaly detection technique — Local Outlier Factor. LOF compares the density of a given data point to its neighbors and determines whether that data is normal or anomalous. The implementation of this algorithm is not too difficult thanks to the sklearn library. The interpretation of the results is also pretty straight forward.
To focus on just one thing I left out another important use case of LocalOutlierFactor() algorithm — Novelty Detection. This is the subject of another article but briefly, LOF is a semi-supervised ML algorithm where the algorithm is trained only on normal data. After training the algorithm, new data is shown to identify whether it is novel or not.
Hope you liked this article, feel free to follow me on Medium or Twitter.
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "Today’s article is my 5th in a series of “bite-size” article I am writing on different techniques used for anomaly detection. If you are interested, the following are the previous four articles:"
},
{
"code": null,
"e": 397,
"s": 367,
"text": "Z-score for anomaly detection"
},
{
"code": null,
"e": 427,
"s": 397,
"text": "Boxplot for anomaly detection"
},
{
"code": null,
"e": 472,
"s": 427,
"text": "Statistical techniques for anomaly detection"
},
{
"code": null,
"e": 527,
"s": 472,
"text": "Time series anomaly detection with “anomalize” library"
},
{
"code": null,
"e": 643,
"s": 527,
"text": "Today I am going beyond statistical techniques and stepping into machine learning algorithms for anomaly detection."
},
{
"code": null,
"e": 810,
"s": 643,
"text": "LOF is an unsupervised (well, semi-supervised) machine learning algorithm that uses the density of data points in the distribution as a key factor to detect outliers."
},
{
"code": null,
"e": 1283,
"s": 810,
"text": "LOF compares the density of any given data point to the density of its neighbors. Since outliers come from low-density areas, the ratio will be higher for anomalous data points. As a rule of thumb, a normal data point has a LOF between 1 and 1.5 whereas anomalous observations will have much higher LOF. The higher the LOF the more likely it is an outlier. If the LOF of point X is 5, it means the average density of X’s neighbors is 5 times higher than its local density."
},
{
"code": null,
"e": 1306,
"s": 1283,
"text": "In mathematical terms,"
},
{
"code": null,
"e": 1404,
"s": 1306,
"text": "LOF(X)=[(LRD(1st neighbor) + LRD(2nd neighbor ) + .................+ LRD(kth neighbor))/LRD(X)]/k"
},
{
"code": null,
"e": 1473,
"s": 1404,
"text": "where LRD is Local Reachability Distance and is computed as follows."
},
{
"code": null,
"e": 1552,
"s": 1473,
"text": "LRD(X) = 1/(sum of Reachability Distance (X, n))/k)where n is neighbors upto k"
},
{
"code": null,
"e": 1597,
"s": 1552,
"text": "The algorithm has four different components:"
},
{
"code": null,
"e": 1650,
"s": 1597,
"text": "Hyperparameter k: determines the number of neighbors"
},
{
"code": null,
"e": 1739,
"s": 1650,
"text": "Reachability distance: distances measured using 3 methods — Euclid, Minkowski, Manhattan"
},
{
"code": null,
"e": 1852,
"s": 1739,
"text": "Local reachability distance: (LRD) (X) = 1/(sum of Reachability Distance (X, n))/k), where n is neighbors upto k"
},
{
"code": null,
"e": 1879,
"s": 1852,
"text": "Local Outlier Factor (LOF)"
},
{
"code": null,
"e": 2156,
"s": 1879,
"text": "Enough of theory and mathematics. If you didn’t understand much of it, no hard feelings. As I use to say, to drive a car we don’t need to know about its mechanics, but we do need to know how to drive! So jump right into the next section on the implementation of LOF in Python."
},
{
"code": null,
"e": 2301,
"s": 2156,
"text": "We are going to implement LOF for anomaly detection in Python environment using Scikit-Learn library. Let’s first import the required libraries:"
},
{
"code": null,
"e": 2503,
"s": 2301,
"text": "# data preparationimport pandas as pdimport numpy as np# data visualzationimport matplotlib.pyplot as pltimport seaborn as sns# outlier/anomaly detectionfrom sklearn.neighbors import LocalOutlierFactor"
},
{
"code": null,
"e": 2569,
"s": 2503,
"text": "Now let’s create a hypothetical dataset containing 5 data points."
},
{
"code": null,
"e": 2683,
"s": 2569,
"text": "# datadf = pd.DataFrame(np.array([[0,1], [1,1], [1,2], [2,2], [5,6]]), columns = [\"x\", \"y\"], index = [0,1,2,3,4])"
},
{
"code": null,
"e": 2780,
"s": 2683,
"text": "If you plot the data points, finding out the outlier with visual inspection is not so difficult."
},
{
"code": null,
"e": 2859,
"s": 2780,
"text": "# plot data pointsplt.scatter(df[\"x\"], df[\"y\"], color = \"b\", s = 65)plt.grid()"
},
{
"code": null,
"e": 3010,
"s": 2859,
"text": "So indeed, we don’t need a machine learning algorithm to find out that the 5th data point is an outlier. But let’s see if the algorithm can detect it."
},
{
"code": null,
"e": 3486,
"s": 3010,
"text": "# model specificationmodel1 = LocalOutlierFactor(n_neighbors = 2, metric = \"manhattan\", contamination = 0.02)# model fittingy_pred = model1.fit_predict(df)# filter outlier indexoutlier_index = where(y_pred == -1) # negative values are outliers and positives inliers# filter outlier valuesoutlier_values = df.iloc[outlier_index]# plot dataplt.scatter(df[\"x\"], df[\"y\"], color = \"b\", s = 65)# plot outlier valuesplt.scatter(outlier_values[\"x\"], outlier_values[\"y\"], color = \"r\")"
},
{
"code": null,
"e": 3546,
"s": 3486,
"text": "There you go! The algorithm correctly detected the outlier."
},
{
"code": null,
"e": 3936,
"s": 3546,
"text": "The purpose of this article was to introduce a density-based anomaly detection technique — Local Outlier Factor. LOF compares the density of a given data point to its neighbors and determines whether that data is normal or anomalous. The implementation of this algorithm is not too difficult thanks to the sklearn library. The interpretation of the results is also pretty straight forward."
},
{
"code": null,
"e": 4286,
"s": 3936,
"text": "To focus on just one thing I left out another important use case of LocalOutlierFactor() algorithm — Novelty Detection. This is the subject of another article but briefly, LOF is a semi-supervised ML algorithm where the algorithm is trained only on normal data. After training the algorithm, new data is shown to identify whether it is novel or not."
}
] |
Ajax Introduction - GeeksforGeeks
|
08 Oct, 2021
Introduction:The following tutorial will provide a short introduction to Ajax and its uses. Before understanding these terms see few practical examples to demonstrate the power of Ajax. Facebook, Instagram, Twitter etc are considered the situation when check news feed and if like someone post simply click the like button and the like count is added without refreshing the page. Now imagine the situation if there would be the case, click the like button and the complete page would be loaded again which will make such processes. Now the question whether clicking the button again for such a small task which require complete loading of a web page. Absolutely not, because no one will do such an absurd thing (in the latter case). So it means that this feature of like is very helpful as it prevents the reloading of the complete page. It communicates only necessary information with the server and shows to the end user(in this case being the increase of like count).Consider another case when visit google to search for anything. Usually, observe that when start typing the desired keywords to search, observe that many suggestions are presented in the search bar. Now, where do they come from? Of course not from the client side. The results are again the power of communication with the server without reloading the page again.Like this, there are dozens of examples which can be considered. The whole power working behind is nothing but Ajax. Let’s discuss briefly Ajax and its implementation.
What is Ajax?Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance.
Prerequisites:There are no such pre-requisites required to understand the latter portion of the article. Only the basic knowledge of HTML, CSS, and Javascript are good to go.
How does it work?First, let us understand what does asynchronous actually mean. There are two types of requests synchronous as well as asynchronous. Synchronous requests are the one which follows sequentially i.e if one process is going on and in the same time another process wants to be executed, it will not be allowed that means the only one process at a time will be executed. This is not good because in this type most of the time CPU remains idle such as during I/O operation in the process which are the order of magnitude slower than the CPU processing the instructions. Thus to make the full utilization of the CPU and other resources use asynchronous calls. For more information visit this link. Why the word javascript is present here. Actually, the requests are made through the use of javascript functions. Now the term XML which is used to create XMLHttpRequest object.Thus the summary of the above explanation is that Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. Now discuss the important part and its implementation. For implementing Ajax, only be aware of XMLHttpRequest object. Now, what actually it is. It is an object used to exchange data with the server behind the scenes. Try to remember the paradigm of OOP which says that object communicates through calling methods (or in general sense message passing). The same case applied here as well. Usually, create this object and use it to call the methods which result in effective communication. All modern browsers support the XMLHttpRequest object.
Basic Syntax: The syntax of creating the object is given below
req = new XMLHttpRequest();
There are two types of methods open() and send(). Uses of these methods explained below.
req.open("GET", "abc.php", true);req.send();
The above two lines described the two methods. req stands for the request, it is basically a reference variable. The GET parameter is as usual one of two types of methods to send the request. Use POST as well depending upon whether send the data through POST or GET method. The second parameter being the name of the file which actually handles the requests and processes them. The third parameter is true, it tells that whether the requests are processed asynchronously or synchronously. It is by default true which means that requests are asynchronous. The open() method prepares the request before sending it to the server. The send method is used to send the request to the server.Sending the parameter through getting or POST request. The syntax is given below
req.open("GET", "abc.php?x=25", true);req.send();
In the above lines of code, the specified query in the form of URL followed by ? which is further followed by the name of the variable then = and then the corresponding value. If sending two or more variables use ampersand(&) sign between the two variables. The above method as shown applies for GET request. Sending the data through the POST, then send it in the send method as shown below.
req.send("name=johndoe&marks=99");
.
Use of setRequestHeader() method as shown below.
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Events and handling mechanism:Any action performs on the clicking button, hovering over elements, page loading etc all are termed as events. Also aware of fact that javascript can detect events. So bind the code of specific event with its action which can be implemented by javascript. These are basically event handlers.Implementing event handlers which actually hold the events. Events handlers are basically functions written in javascript which act on or set into action when an event is fired by the user. When sending the request through send method usually get the response from the server later. But getting of response time is not known. So track it.Therefore to keep a track of the response onreadystatechange event which is binding with the event handler(function) which will get executed when a response comes.When a request to the server is sending perform actions based on the response. The onreadystatechange event is triggered every time the readyState changes. So what actually a ready state is and when will the onreadystate event actually occur and how many times it will occur between the request and response?The XMLHttpRequest object has a property called as readyState whose value changes in the complete request-response journey i.e when a request is prepared, sent, resolves, processed and when the response comes. That’s why it is called os onreadystatechange.The onreadystatechange stores a function (or the name of the function)to be called automatically each time the readyState property changes.The readyState holds different values ranging from 0 to 4.
request not initializedserver connection establishedrequest receivedprocessing requestrequest finished and response is ready
request not initialized
server connection established
request received
processing request
request finished and response is ready
XMLHttpRequest also has a property named as status. The status has following values
200: “OK”
404: “Page not found”
Now remember it always that when readyState is 4 and status is 200, the response is ready.The whole thing described above is implemented in coding as given below
<p id = "dis">< /p>req.onreadystatechange = function(){ if(req.readyState == 4 && req.status == 200){ document.getElementById("dis").innerHTML = req.responseText; }}
(Note: This is only a section of code and moreover describing the communication between client and server so the code described above will not show any effect if run on IDE)In the above code if the condition is true (i.e the response is ready) then the result is displayed.Advantages:
Speed is enhanced as there is no need to reload the page again.AJAX make asynchronous calls to a web server, this means client browsers avoid waiting for all the data to arrive before starting of rendering.Form validation can be done successfully through it.Bandwidth utilization – It saves memory when the data is fetched from the same page.More interactive.
Speed is enhanced as there is no need to reload the page again.
AJAX make asynchronous calls to a web server, this means client browsers avoid waiting for all the data to arrive before starting of rendering.
Form validation can be done successfully through it.
Bandwidth utilization – It saves memory when the data is fetched from the same page.
More interactive.
Disadvantages:
Ajax is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support.Ajax can be problematic in Search engines as it uses Javascript for most of its parts.Source code written in AJAX is easily human readable. There will be some security issues in Ajax.Debugging is difficult.Problem with browser back button when using AJAX enabled pages.
Ajax is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support.
Ajax can be problematic in Search engines as it uses Javascript for most of its parts.
Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
Debugging is difficult.
Problem with browser back button when using AJAX enabled pages.
JavaScript-Misc
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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": 25050,
"s": 25022,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 26551,
"s": 25050,
"text": "Introduction:The following tutorial will provide a short introduction to Ajax and its uses. Before understanding these terms see few practical examples to demonstrate the power of Ajax. Facebook, Instagram, Twitter etc are considered the situation when check news feed and if like someone post simply click the like button and the like count is added without refreshing the page. Now imagine the situation if there would be the case, click the like button and the complete page would be loaded again which will make such processes. Now the question whether clicking the button again for such a small task which require complete loading of a web page. Absolutely not, because no one will do such an absurd thing (in the latter case). So it means that this feature of like is very helpful as it prevents the reloading of the complete page. It communicates only necessary information with the server and shows to the end user(in this case being the increase of like count).Consider another case when visit google to search for anything. Usually, observe that when start typing the desired keywords to search, observe that many suggestions are presented in the search bar. Now, where do they come from? Of course not from the client side. The results are again the power of communication with the server without reloading the page again.Like this, there are dozens of examples which can be considered. The whole power working behind is nothing but Ajax. Let’s discuss briefly Ajax and its implementation."
},
{
"code": null,
"e": 26758,
"s": 26551,
"text": "What is Ajax?Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance."
},
{
"code": null,
"e": 26933,
"s": 26758,
"text": "Prerequisites:There are no such pre-requisites required to understand the latter portion of the article. Only the basic knowledge of HTML, CSS, and Javascript are good to go."
},
{
"code": null,
"e": 28532,
"s": 26933,
"text": "How does it work?First, let us understand what does asynchronous actually mean. There are two types of requests synchronous as well as asynchronous. Synchronous requests are the one which follows sequentially i.e if one process is going on and in the same time another process wants to be executed, it will not be allowed that means the only one process at a time will be executed. This is not good because in this type most of the time CPU remains idle such as during I/O operation in the process which are the order of magnitude slower than the CPU processing the instructions. Thus to make the full utilization of the CPU and other resources use asynchronous calls. For more information visit this link. Why the word javascript is present here. Actually, the requests are made through the use of javascript functions. Now the term XML which is used to create XMLHttpRequest object.Thus the summary of the above explanation is that Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. Now discuss the important part and its implementation. For implementing Ajax, only be aware of XMLHttpRequest object. Now, what actually it is. It is an object used to exchange data with the server behind the scenes. Try to remember the paradigm of OOP which says that object communicates through calling methods (or in general sense message passing). The same case applied here as well. Usually, create this object and use it to call the methods which result in effective communication. All modern browsers support the XMLHttpRequest object."
},
{
"code": null,
"e": 28595,
"s": 28532,
"text": "Basic Syntax: The syntax of creating the object is given below"
},
{
"code": "req = new XMLHttpRequest();",
"e": 28623,
"s": 28595,
"text": null
},
{
"code": null,
"e": 28712,
"s": 28623,
"text": "There are two types of methods open() and send(). Uses of these methods explained below."
},
{
"code": "req.open(\"GET\", \"abc.php\", true);req.send();",
"e": 28757,
"s": 28712,
"text": null
},
{
"code": null,
"e": 29523,
"s": 28757,
"text": "The above two lines described the two methods. req stands for the request, it is basically a reference variable. The GET parameter is as usual one of two types of methods to send the request. Use POST as well depending upon whether send the data through POST or GET method. The second parameter being the name of the file which actually handles the requests and processes them. The third parameter is true, it tells that whether the requests are processed asynchronously or synchronously. It is by default true which means that requests are asynchronous. The open() method prepares the request before sending it to the server. The send method is used to send the request to the server.Sending the parameter through getting or POST request. The syntax is given below"
},
{
"code": "req.open(\"GET\", \"abc.php?x=25\", true);req.send();",
"e": 29573,
"s": 29523,
"text": null
},
{
"code": null,
"e": 29965,
"s": 29573,
"text": "In the above lines of code, the specified query in the form of URL followed by ? which is further followed by the name of the variable then = and then the corresponding value. If sending two or more variables use ampersand(&) sign between the two variables. The above method as shown applies for GET request. Sending the data through the POST, then send it in the send method as shown below."
},
{
"code": "req.send(\"name=johndoe&marks=99\");",
"e": 30000,
"s": 29965,
"text": null
},
{
"code": null,
"e": 30002,
"s": 30000,
"text": "."
},
{
"code": null,
"e": 30051,
"s": 30002,
"text": "Use of setRequestHeader() method as shown below."
},
{
"code": "req.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");",
"e": 30126,
"s": 30051,
"text": null
},
{
"code": null,
"e": 31710,
"s": 30126,
"text": "Events and handling mechanism:Any action performs on the clicking button, hovering over elements, page loading etc all are termed as events. Also aware of fact that javascript can detect events. So bind the code of specific event with its action which can be implemented by javascript. These are basically event handlers.Implementing event handlers which actually hold the events. Events handlers are basically functions written in javascript which act on or set into action when an event is fired by the user. When sending the request through send method usually get the response from the server later. But getting of response time is not known. So track it.Therefore to keep a track of the response onreadystatechange event which is binding with the event handler(function) which will get executed when a response comes.When a request to the server is sending perform actions based on the response. The onreadystatechange event is triggered every time the readyState changes. So what actually a ready state is and when will the onreadystate event actually occur and how many times it will occur between the request and response?The XMLHttpRequest object has a property called as readyState whose value changes in the complete request-response journey i.e when a request is prepared, sent, resolves, processed and when the response comes. That’s why it is called os onreadystatechange.The onreadystatechange stores a function (or the name of the function)to be called automatically each time the readyState property changes.The readyState holds different values ranging from 0 to 4."
},
{
"code": null,
"e": 31835,
"s": 31710,
"text": "request not initializedserver connection establishedrequest receivedprocessing requestrequest finished and response is ready"
},
{
"code": null,
"e": 31859,
"s": 31835,
"text": "request not initialized"
},
{
"code": null,
"e": 31889,
"s": 31859,
"text": "server connection established"
},
{
"code": null,
"e": 31906,
"s": 31889,
"text": "request received"
},
{
"code": null,
"e": 31925,
"s": 31906,
"text": "processing request"
},
{
"code": null,
"e": 31964,
"s": 31925,
"text": "request finished and response is ready"
},
{
"code": null,
"e": 32048,
"s": 31964,
"text": "XMLHttpRequest also has a property named as status. The status has following values"
},
{
"code": null,
"e": 32058,
"s": 32048,
"text": "200: “OK”"
},
{
"code": null,
"e": 32080,
"s": 32058,
"text": "404: “Page not found”"
},
{
"code": null,
"e": 32242,
"s": 32080,
"text": "Now remember it always that when readyState is 4 and status is 200, the response is ready.The whole thing described above is implemented in coding as given below"
},
{
"code": "<p id = \"dis\">< /p>req.onreadystatechange = function(){ if(req.readyState == 4 && req.status == 200){ document.getElementById(\"dis\").innerHTML = req.responseText; }}",
"e": 32415,
"s": 32242,
"text": null
},
{
"code": null,
"e": 32700,
"s": 32415,
"text": "(Note: This is only a section of code and moreover describing the communication between client and server so the code described above will not show any effect if run on IDE)In the above code if the condition is true (i.e the response is ready) then the result is displayed.Advantages:"
},
{
"code": null,
"e": 33060,
"s": 32700,
"text": "Speed is enhanced as there is no need to reload the page again.AJAX make asynchronous calls to a web server, this means client browsers avoid waiting for all the data to arrive before starting of rendering.Form validation can be done successfully through it.Bandwidth utilization – It saves memory when the data is fetched from the same page.More interactive."
},
{
"code": null,
"e": 33124,
"s": 33060,
"text": "Speed is enhanced as there is no need to reload the page again."
},
{
"code": null,
"e": 33268,
"s": 33124,
"text": "AJAX make asynchronous calls to a web server, this means client browsers avoid waiting for all the data to arrive before starting of rendering."
},
{
"code": null,
"e": 33321,
"s": 33268,
"text": "Form validation can be done successfully through it."
},
{
"code": null,
"e": 33406,
"s": 33321,
"text": "Bandwidth utilization – It saves memory when the data is fetched from the same page."
},
{
"code": null,
"e": 33424,
"s": 33406,
"text": "More interactive."
},
{
"code": null,
"e": 33439,
"s": 33424,
"text": "Disadvantages:"
},
{
"code": null,
"e": 33831,
"s": 33439,
"text": "Ajax is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support.Ajax can be problematic in Search engines as it uses Javascript for most of its parts.Source code written in AJAX is easily human readable. There will be some security issues in Ajax.Debugging is difficult.Problem with browser back button when using AJAX enabled pages."
},
{
"code": null,
"e": 33954,
"s": 33831,
"text": "Ajax is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support."
},
{
"code": null,
"e": 34041,
"s": 33954,
"text": "Ajax can be problematic in Search engines as it uses Javascript for most of its parts."
},
{
"code": null,
"e": 34139,
"s": 34041,
"text": "Source code written in AJAX is easily human readable. There will be some security issues in Ajax."
},
{
"code": null,
"e": 34163,
"s": 34139,
"text": "Debugging is difficult."
},
{
"code": null,
"e": 34227,
"s": 34163,
"text": "Problem with browser back button when using AJAX enabled pages."
},
{
"code": null,
"e": 34243,
"s": 34227,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 34254,
"s": 34243,
"text": "JavaScript"
},
{
"code": null,
"e": 34271,
"s": 34254,
"text": "Web Technologies"
},
{
"code": null,
"e": 34369,
"s": 34271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34378,
"s": 34369,
"text": "Comments"
},
{
"code": null,
"e": 34391,
"s": 34378,
"text": "Old Comments"
},
{
"code": null,
"e": 34436,
"s": 34391,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34508,
"s": 34436,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 34569,
"s": 34508,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 34621,
"s": 34569,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 34667,
"s": 34621,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 34709,
"s": 34667,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 34742,
"s": 34709,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34804,
"s": 34742,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34847,
"s": 34804,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
JUnit - Plug with Eclipse
|
To set up JUnit with eclipse, follow the steps given below.
Download a JUnit jar based on the operating system you have on your system.
Assume you have copied the above JAR file onto the folder C:\>JUnit.
Open eclipse → right click on project and click on property > Build Path > Configure Build Path and add the junit-4.10.jar in the libraries using the button Add External Jar.
We assume that your Eclipse has inbuilt JUnit plugin. If it is not available in C:\>eclipse\plugins directory, then you can download it from JUnit Plugin. Unzip the downloaded zip file in the plugin folder of the Eclipse. Finally restart Eclipse.
Now your Eclipse is ready for the development of JUnit test cases.
Create a project TestJunit in Eclipse at any location. Then create a class MessageUtil to test in the project.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public String printMessage(){
System.out.println(message);
return message;
}
}
Create a test class TestJunit in the project.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "Hello World";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
Following should be the project structure −
Finally, right click the program and run as JUnit to verify the output of the program.
Verify the result.
24 Lectures
2.5 hours
Nishita Bhatt
56 Lectures
7.5 hours
Dinesh Varyani
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2032,
"s": 1972,
"text": "To set up JUnit with eclipse, follow the steps given below."
},
{
"code": null,
"e": 2108,
"s": 2032,
"text": "Download a JUnit jar based on the operating system you have on your system."
},
{
"code": null,
"e": 2177,
"s": 2108,
"text": "Assume you have copied the above JAR file onto the folder C:\\>JUnit."
},
{
"code": null,
"e": 2352,
"s": 2177,
"text": "Open eclipse → right click on project and click on property > Build Path > Configure Build Path and add the junit-4.10.jar in the libraries using the button Add External Jar."
},
{
"code": null,
"e": 2599,
"s": 2352,
"text": "We assume that your Eclipse has inbuilt JUnit plugin. If it is not available in C:\\>eclipse\\plugins directory, then you can download it from JUnit Plugin. Unzip the downloaded zip file in the plugin folder of the Eclipse. Finally restart Eclipse."
},
{
"code": null,
"e": 2666,
"s": 2599,
"text": "Now your Eclipse is ready for the development of JUnit test cases."
},
{
"code": null,
"e": 2777,
"s": 2666,
"text": "Create a project TestJunit in Eclipse at any location. Then create a class MessageUtil to test in the project."
},
{
"code": null,
"e": 3152,
"s": 2777,
"text": " \n/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message;\n }\n \n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n} "
},
{
"code": null,
"e": 3198,
"s": 3152,
"text": "Create a test class TestJunit in the project."
},
{
"code": null,
"e": 3501,
"s": 3198,
"text": " \nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\t\n String message = \"Hello World\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\t \n assertEquals(message,messageUtil.printMessage());\n }\n}"
},
{
"code": null,
"e": 3545,
"s": 3501,
"text": "Following should be the project structure −"
},
{
"code": null,
"e": 3632,
"s": 3545,
"text": "Finally, right click the program and run as JUnit to verify the output of the program."
},
{
"code": null,
"e": 3651,
"s": 3632,
"text": "Verify the result."
},
{
"code": null,
"e": 3686,
"s": 3651,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3701,
"s": 3686,
"text": " Nishita Bhatt"
},
{
"code": null,
"e": 3736,
"s": 3701,
"text": "\n 56 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3752,
"s": 3736,
"text": " Dinesh Varyani"
},
{
"code": null,
"e": 3759,
"s": 3752,
"text": " Print"
},
{
"code": null,
"e": 3770,
"s": 3759,
"text": " Add Notes"
}
] |
XML Processing Modules in Python
|
XML stands for "Extensible Markup Language". It is mainly used in webpages, where the data has a specific structure. It has elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >. The characters between the start-tag and end-tag, are the element's content. Elements can contain other elements, which are called "child elements".
Below is the example of an XML file we are going to use in this tutorial.
<?xml version="1.0"?>
<Tutorials>
<Tutorial id="Tu101">
<author>Vicky, Matthew</author>
<title>Geo-Spatial Data Analysis</title>
<stream>Python</stream>
<price>4.95</price>
<publish_date>2020-07-01</publish_date>
<description>Learn geo Spatial data Analysis using Python.</description>
</Tutorial>
<Tutorial id="Tu102">
<author>Bolan, Kim</author>
<title>Data Structures</title>
<stream>Computer Science</stream>
<price>12.03</price>
<publish_date>2020-1-19</publish_date>
<description>Learn Data structures using different programming lanuages.</description>
</Tutorial>
<Tutorial id="Tu103">
<author>Sora, Everest</author>
<title>Analytics using Tensorflow</title>
<stream>Data Science</stream>
<price>7.11</price>
<publish_date>2020-1-19</publish_date>
<description>Learn Data analytics using Tensorflow.</description>
</Tutorial>
</Tutorials>
This module provides access to the root of the xml file and then we can access the contents of the inner elements. In the below example we use the attribute called text and get the content of those elements.
import xml.etree.ElementTree as ET
xml_tree = ET.parse('E:\\TutorialsList.xml')
xml_root = xml_tree.getroot()
# Header
print('Tutorial List :')
for xml_elmt in xml_root:
for inner_elmt in xml_elmt:
print(inner_elmt.text)
Running the above code gives us the following result −
Tutorial List :
Vicky, Matthew
Geo-Spatial Data Analysis
Python
4.95
2020-07-01
Learn geo Spatial data Analysis using Python.
Bolan, Kim
Data Structures
Computer Science
12.03
2020-1-19
Learn Data structures using different programming lanuages.
Sora, Everest
Analytics using Tensorflow
Data Science
7.11
2020-1-19
Learn Data analytics using Tensorflow.
We can get the list of attributes and their values in the root tag. Once we find the attributes, it helps us navigate the XML tree easily.
import xml.etree.ElementTree as ET
xml_tree = ET.parse('E:\\TutorialsList.xml')
xml_root = xml_tree.getroot()
# Header
print('Tutorial List :')
for movie in xml_root.iter('Tutorial'):
print(movie.attrib)
Running the above code gives us the following result −
Tutorial List :
{'id': 'Tu101'}
{'id': 'Tu102'}
{'id': 'Tu103'}
We can also filter the results out of the xml tree by using the findall() function of this module. In the below example we find out the id of the tutorial which has a price of 12.03.
import xml.etree.ElementTree as ET
xml_tree = ET.parse('E:\\TutorialsList.xml')
xml_root = xml_tree.getroot()
# Header
print('Tutorial List :')
for movie in xml_root.findall("./Tutorial/[price ='12.03']"):
print(movie.attrib)
Running the above code gives us the following result −
Tutorial List :
{'id': 'Tu102'}
We create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file. The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file designated by file into a DOM tree object.
from xml.dom.minidom import parse
import xml.dom.minidom
# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse('E:\\TutorialsList.xml')
collection = DOMTree.documentElement
# Get all the movies in the collection
tut_list = collection.getElementsByTagName("Tutorial")
print("*****Tutorials*****")
# Print details of each Tutorial.
for tut in tut_list:
strm = tut.getElementsByTagName('stream')[0]
print("Stream: ",strm.childNodes[0].data)
prc = tut.getElementsByTagName('price')[0]
print("Price: ", prc.childNodes[0].data)
Running the above code gives us the following result −
*****Tutorials*****
Stream: Python
Price: 4.95
Stream: Computer Science
Price: 12.03
Stream: Data Science
Price: 7.11
|
[
{
"code": null,
"e": 1451,
"s": 1062,
"text": "XML stands for \"Extensible Markup Language\". It is mainly used in webpages, where the data has a specific structure. It has elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >. The characters between the start-tag and end-tag, are the element's content. Elements can contain other elements, which are called \"child elements\"."
},
{
"code": null,
"e": 1525,
"s": 1451,
"text": "Below is the example of an XML file we are going to use in this tutorial."
},
{
"code": null,
"e": 2498,
"s": 1525,
"text": "<?xml version=\"1.0\"?>\n<Tutorials>\n <Tutorial id=\"Tu101\">\n <author>Vicky, Matthew</author>\n <title>Geo-Spatial Data Analysis</title>\n <stream>Python</stream>\n <price>4.95</price>\n <publish_date>2020-07-01</publish_date>\n <description>Learn geo Spatial data Analysis using Python.</description>\n </Tutorial>\n <Tutorial id=\"Tu102\">\n <author>Bolan, Kim</author>\n <title>Data Structures</title>\n <stream>Computer Science</stream>\n <price>12.03</price>\n <publish_date>2020-1-19</publish_date>\n <description>Learn Data structures using different programming lanuages.</description>\n </Tutorial>\n <Tutorial id=\"Tu103\">\n <author>Sora, Everest</author>\n <title>Analytics using Tensorflow</title>\n <stream>Data Science</stream>\n <price>7.11</price>\n <publish_date>2020-1-19</publish_date>\n <description>Learn Data analytics using Tensorflow.</description>\n </Tutorial>\n</Tutorials>"
},
{
"code": null,
"e": 2706,
"s": 2498,
"text": "This module provides access to the root of the xml file and then we can access the contents of the inner elements. In the below example we use the attribute called text and get the content of those elements."
},
{
"code": null,
"e": 2937,
"s": 2706,
"text": "import xml.etree.ElementTree as ET\nxml_tree = ET.parse('E:\\\\TutorialsList.xml')\nxml_root = xml_tree.getroot()\n# Header\nprint('Tutorial List :')\nfor xml_elmt in xml_root:\n for inner_elmt in xml_elmt:\n print(inner_elmt.text)\n"
},
{
"code": null,
"e": 2992,
"s": 2937,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3346,
"s": 2992,
"text": "Tutorial List :\nVicky, Matthew\nGeo-Spatial Data Analysis\nPython\n4.95\n2020-07-01\nLearn geo Spatial data Analysis using Python.\nBolan, Kim\nData Structures\nComputer Science\n12.03\n2020-1-19\nLearn Data structures using different programming lanuages.\nSora, Everest\nAnalytics using Tensorflow\nData Science\n7.11\n2020-1-19\nLearn Data analytics using Tensorflow."
},
{
"code": null,
"e": 3485,
"s": 3346,
"text": "We can get the list of attributes and their values in the root tag. Once we find the attributes, it helps us navigate the XML tree easily."
},
{
"code": null,
"e": 3692,
"s": 3485,
"text": "import xml.etree.ElementTree as ET\nxml_tree = ET.parse('E:\\\\TutorialsList.xml')\nxml_root = xml_tree.getroot()\n# Header\nprint('Tutorial List :')\nfor movie in xml_root.iter('Tutorial'):\n print(movie.attrib)"
},
{
"code": null,
"e": 3747,
"s": 3692,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3811,
"s": 3747,
"text": "Tutorial List :\n{'id': 'Tu101'}\n{'id': 'Tu102'}\n{'id': 'Tu103'}"
},
{
"code": null,
"e": 3994,
"s": 3811,
"text": "We can also filter the results out of the xml tree by using the findall() function of this module. In the below example we find out the id of the tutorial which has a price of 12.03."
},
{
"code": null,
"e": 4223,
"s": 3994,
"text": "import xml.etree.ElementTree as ET\nxml_tree = ET.parse('E:\\\\TutorialsList.xml')\nxml_root = xml_tree.getroot()\n# Header\nprint('Tutorial List :')\nfor movie in xml_root.findall(\"./Tutorial/[price ='12.03']\"):\n print(movie.attrib)"
},
{
"code": null,
"e": 4278,
"s": 4223,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 4310,
"s": 4278,
"text": "Tutorial List :\n{'id': 'Tu102'}"
},
{
"code": null,
"e": 4613,
"s": 4310,
"text": "We create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file. The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file designated by file into a DOM tree object."
},
{
"code": null,
"e": 5172,
"s": 4613,
"text": "from xml.dom.minidom import parse\nimport xml.dom.minidom\n\n# Open XML document using minidom parser\nDOMTree = xml.dom.minidom.parse('E:\\\\TutorialsList.xml')\ncollection = DOMTree.documentElement\n\n# Get all the movies in the collection\ntut_list = collection.getElementsByTagName(\"Tutorial\")\n\nprint(\"*****Tutorials*****\")\n# Print details of each Tutorial.\nfor tut in tut_list:\n\n strm = tut.getElementsByTagName('stream')[0]\n print(\"Stream: \",strm.childNodes[0].data)\n\n prc = tut.getElementsByTagName('price')[0]\n print(\"Price: \", prc.childNodes[0].data)\n"
},
{
"code": null,
"e": 5227,
"s": 5172,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 5345,
"s": 5227,
"text": "*****Tutorials*****\nStream: Python\nPrice: 4.95\nStream: Computer Science\nPrice: 12.03\nStream: Data Science\nPrice: 7.11"
}
] |
Explain dependency injection in C#
|
A dependency is an object that another object depends on. Dependency Injection (or inversion) is basically providing the objects that an object needs, instead of having it construct the objects themselves. It is a useful technique that makes testing easier, as it allows you to mock the dependencies.
For example, if class A calls a method on class B, which in turn calls a method on class C, that means A depends on B and B depends on C. Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C.
In the example, below, class Runner has a dependency on the class Logger. Notice that in the class Runner creates an instance of Logger in the constructor. There are a few problems with this code.
This ties the logger class to Runner and we can't substitute it with other classes,
without modifying Runner.
This ties the logger class to Runner and we can't substitute it with other classes,
without modifying Runner.
If Logger has any dependencies, then Worker has to configure them before
instantiating Logger.
If Logger has any dependencies, then Worker has to configure them before
instantiating Logger.
Testing is harder. If Logger is a resource-intensive class, such as accessing the
network or file system, it will slow the testing down. We can't replace it easily.
Testing is harder. If Logger is a resource-intensive class, such as accessing the
network or file system, it will slow the testing down. We can't replace it easily.
using System;
class Program{
static void Main(string[] args){
var runner = new Runner();
runner.Run();
}
}
class Runner{
private Logger _logger;
public Runner(){
_logger = new Logger();
}
public void Run(){
// Do some work
_logger.Log("Message to be logged");
}
}
class Logger{
public void Log(string message){
Console.WriteLine(message);
}
}
Using dependency injection, we modify the constructor of Runner to accept an interface ILogger, instead of a concrete object. We change the Logger class to implement ILogger. This allows us to pass an instance of the Logger class to the Runner's constructor. The benefit of this is that during testing, we can create a TestLogger class that implements ILogger and pass that to Runner's constructor.
Live Demo
using System;
class Program{
static void Main(string[] args){
var logger = new Logger();
var runner = new Runner(logger);
runner.Run();
}
}
class Runner{
private ILogger _logger;
public Runner(ILogger logger){
_logger = logger;
}
public void Run(){
// Do some work
_logger.Log("Message to be logged");
}
}
interface ILogger{
void Log(string message);
}
class Logger : ILogger{
public void Log(string message){
Console.WriteLine(message);
}
}
Message to be logged
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "A dependency is an object that another object depends on. Dependency Injection (or inversion) is basically providing the objects that an object needs, instead of having it construct the objects themselves. It is a useful technique that makes testing easier, as it allows you to mock the dependencies."
},
{
"code": null,
"e": 1685,
"s": 1363,
"text": "For example, if class A calls a method on class B, which in turn calls a method on class C, that means A depends on B and B depends on C. Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C."
},
{
"code": null,
"e": 1882,
"s": 1685,
"text": "In the example, below, class Runner has a dependency on the class Logger. Notice that in the class Runner creates an instance of Logger in the constructor. There are a few problems with this code."
},
{
"code": null,
"e": 1992,
"s": 1882,
"text": "This ties the logger class to Runner and we can't substitute it with other classes,\nwithout modifying Runner."
},
{
"code": null,
"e": 2102,
"s": 1992,
"text": "This ties the logger class to Runner and we can't substitute it with other classes,\nwithout modifying Runner."
},
{
"code": null,
"e": 2197,
"s": 2102,
"text": "If Logger has any dependencies, then Worker has to configure them before\ninstantiating Logger."
},
{
"code": null,
"e": 2292,
"s": 2197,
"text": "If Logger has any dependencies, then Worker has to configure them before\ninstantiating Logger."
},
{
"code": null,
"e": 2457,
"s": 2292,
"text": "Testing is harder. If Logger is a resource-intensive class, such as accessing the\nnetwork or file system, it will slow the testing down. We can't replace it easily."
},
{
"code": null,
"e": 2622,
"s": 2457,
"text": "Testing is harder. If Logger is a resource-intensive class, such as accessing the\nnetwork or file system, it will slow the testing down. We can't replace it easily."
},
{
"code": null,
"e": 3028,
"s": 2622,
"text": "using System;\nclass Program{\n static void Main(string[] args){\n var runner = new Runner();\n runner.Run();\n }\n}\nclass Runner{\n private Logger _logger;\n public Runner(){\n _logger = new Logger();\n }\n public void Run(){\n // Do some work\n _logger.Log(\"Message to be logged\");\n }\n}\nclass Logger{\n public void Log(string message){\n Console.WriteLine(message);\n }\n}"
},
{
"code": null,
"e": 3427,
"s": 3028,
"text": "Using dependency injection, we modify the constructor of Runner to accept an interface ILogger, instead of a concrete object. We change the Logger class to implement ILogger. This allows us to pass an instance of the Logger class to the Runner's constructor. The benefit of this is that during testing, we can create a TestLogger class that implements ILogger and pass that to Runner's constructor."
},
{
"code": null,
"e": 3438,
"s": 3427,
"text": " Live Demo"
},
{
"code": null,
"e": 3952,
"s": 3438,
"text": "using System;\nclass Program{\n static void Main(string[] args){\n var logger = new Logger();\n var runner = new Runner(logger);\n runner.Run();\n }\n}\nclass Runner{\n private ILogger _logger;\n public Runner(ILogger logger){\n _logger = logger;\n }\n public void Run(){\n // Do some work\n _logger.Log(\"Message to be logged\");\n }\n}\ninterface ILogger{\n void Log(string message);\n}\nclass Logger : ILogger{\n public void Log(string message){\n Console.WriteLine(message);\n }\n}"
},
{
"code": null,
"e": 3973,
"s": 3952,
"text": "Message to be logged"
}
] |
How to find the 95% confidence interval for the slope of regression line in R?
|
The slope of the regression line is a very important part of regression analysis, by finding the slope we get an estimate of the value by which the dependent variable is expected to increase or decrease. But the confidence interval provides the range of the slope values that we expect 95% of the times when the sample size is same. To find the 95% confidence for the slope of regression line we can use confint function with regression model object.
Consider the below data frame −
set.seed(1)
x <-rnorm(20)
y <-rnorm(20,2.5)
df <-data.frame(x,y)
df
x y
1 -0.62645381 3.4189774
2 0.18364332 3.2821363
3 -0.83562861 2.5745650
4 1.59528080 0.5106483
5 0.32950777 3.1198257
6 -0.82046838 2.4438713
7 0.48742905 2.3442045
8 0.73832471 1.0292476
9 0.57578135 2.0218499
10 -0.30538839 2.9179416
11 1.51178117 3.8586796
12 0.38984324 2.3972123
13 -0.62124058 2.8876716
14 -2.21469989 2.4461950
15 1.12493092 1.1229404
16 -0.04493361 2.0850054
17 -0.01619026 2.1057100
18 0.94383621 2.4406866
19 0.82122120 3.6000254
20 0.59390132 3.2631757
Creating regression model to predict y from x −
RegressionModel <-lm(y~x,data=df)
summary(RegressionModel)
Call:
lm(formula = y ~ x, data = df)
Residuals:
Min 1Q Median 3Q Max
-1.69133 -0.43739 -0.07132 0.68033 1.63937
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.5331 0.1998 12.677 2.08e-10 ***
x -0.2075 0.2195 -0.946 0.357
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.8738 on 18 degrees of freedom
Multiple R-squared: 0.04732, Adjusted R-squared: -0.00561
F-statistic: 0.894 on 1 and 18 DF, p-value: 0.3569
Finding the 95% confidence interval for the slope of the regression line −
confint(RegressionModel,'x',level=0.95)
2.5 % 97.5 %
x -0.6687129 0.2536177
Lets’ have a look at another example:
BloodPressure <-c(165,170,190,195,220)
Weight <-c(50,75,64,60,62)
data <-data.frame(BloodPressure,Weight)
data
BloodPressure Weight
1 165 50
2 170 75
3 190 64
4 195 60
5 220 62
RegM <-lm(BloodPressure~Weight,data=data)
summary(RegM)
Call:
lm(formula = BloodPressure ~ Weight, data = data)
Residuals:
1 2 3 4 5
-21.783 -19.277 1.820 7.219 32.020
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 181.79551 88.73672 2.049 0.133
Weight 0.09975 1.41495 0.070 0.948
Residual standard error: 25.34 on 3 degrees of freedom
Multiple R-squared: 0.001654, Adjusted R-squared: -0.3311
F-statistic: 0.00497 on 1 and 3 DF, p-value: 0.9482
confint(RegM,'Weight',level=0.95)
2.5 % 97.5 %
Weight -4.403255 4.602756
2.5 % 97.5 %
Weight -4.403255 4.602756
|
[
{
"code": null,
"e": 1513,
"s": 1062,
"text": "The slope of the regression line is a very important part of regression analysis, by finding the slope we get an estimate of the value by which the dependent variable is expected to increase or decrease. But the confidence interval provides the range of the slope values that we expect 95% of the times when the sample size is same. To find the 95% confidence for the slope of regression line we can use confint function with regression model object."
},
{
"code": null,
"e": 1545,
"s": 1513,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1613,
"s": 1545,
"text": "set.seed(1)\nx <-rnorm(20)\ny <-rnorm(20,2.5)\ndf <-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 2108,
"s": 1613,
"text": " x y\n1 -0.62645381 3.4189774\n2 0.18364332 3.2821363\n3 -0.83562861 2.5745650\n4 1.59528080 0.5106483\n5 0.32950777 3.1198257\n6 -0.82046838 2.4438713\n7 0.48742905 2.3442045\n8 0.73832471 1.0292476\n9 0.57578135 2.0218499\n10 -0.30538839 2.9179416\n11 1.51178117 3.8586796\n12 0.38984324 2.3972123\n13 -0.62124058 2.8876716\n14 -2.21469989 2.4461950\n15 1.12493092 1.1229404\n16 -0.04493361 2.0850054\n17 -0.01619026 2.1057100\n18 0.94383621 2.4406866\n19 0.82122120 3.6000254\n20 0.59390132 3.2631757"
},
{
"code": null,
"e": 2156,
"s": 2108,
"text": "Creating regression model to predict y from x −"
},
{
"code": null,
"e": 2215,
"s": 2156,
"text": "RegressionModel <-lm(y~x,data=df)\nsummary(RegressionModel)"
},
{
"code": null,
"e": 2688,
"s": 2215,
"text": "Call:\nlm(formula = y ~ x, data = df)\n\nResiduals:\nMin 1Q Median 3Q Max\n-1.69133 -0.43739 -0.07132 0.68033 1.63937\n\nCoefficients:\nEstimate Std. Error t value Pr(>|t|)\n(Intercept) 2.5331 0.1998 12.677 2.08e-10 ***\nx -0.2075 0.2195 -0.946 0.357\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\nResidual standard error: 0.8738 on 18 degrees of freedom\nMultiple R-squared: 0.04732, Adjusted R-squared: -0.00561\nF-statistic: 0.894 on 1 and 18 DF, p-value: 0.3569"
},
{
"code": null,
"e": 2763,
"s": 2688,
"text": "Finding the 95% confidence interval for the slope of the regression line −"
},
{
"code": null,
"e": 2988,
"s": 2763,
"text": "confint(RegressionModel,'x',level=0.95)\n2.5 % 97.5 %\nx -0.6687129 0.2536177\nLets’ have a look at another example:\nBloodPressure <-c(165,170,190,195,220)\nWeight <-c(50,75,64,60,62)\ndata <-data.frame(BloodPressure,Weight)\ndata"
},
{
"code": null,
"e": 3054,
"s": 2988,
"text": "BloodPressure Weight\n1 165 50\n2 170 75\n3 190 64\n4 195 60\n5 220 62"
},
{
"code": null,
"e": 3110,
"s": 3054,
"text": "RegM <-lm(BloodPressure~Weight,data=data)\nsummary(RegM)"
},
{
"code": null,
"e": 3516,
"s": 3110,
"text": "Call:\nlm(formula = BloodPressure ~ Weight, data = data)\nResiduals:\n1 2 3 4 5\n-21.783 -19.277 1.820 7.219 32.020\nCoefficients:\nEstimate Std. Error t value Pr(>|t|)\n(Intercept) 181.79551 88.73672 2.049 0.133\nWeight 0.09975 1.41495 0.070 0.948\nResidual standard error: 25.34 on 3 degrees of freedom\nMultiple R-squared: 0.001654, Adjusted R-squared: -0.3311\nF-statistic: 0.00497 on 1 and 3 DF, p-value: 0.9482"
},
{
"code": null,
"e": 3589,
"s": 3516,
"text": "confint(RegM,'Weight',level=0.95)\n2.5 % 97.5 %\nWeight -4.403255 4.602756"
},
{
"code": null,
"e": 3628,
"s": 3589,
"text": "2.5 % 97.5 %\nWeight -4.403255 4.602756"
}
] |
How can we use MySQL TRIM() to remove the whitespaces from all the rows and update table?
|
Suppose if a table has many values having whitespaces in the columns of a table then it is wastage of space. We can use TRIM() function to remove whitespaces from all the rows and update the table too in a single query. Following the example from ‘Employee’, having whitespaces in all its rows will exhibit the concept −
mysql> Select * from Employee;
+------+----------------------+----------------------+----------------------+
| Id | Name | Address | Department |
+------+----------------------+----------------------+----------------------+
| 100 | Raman | Delhi | IT |
| 101 | Mohan | Haryana | History |
| 102 | Shyam | Chandigarh | ENGLISH |
| 103 | Sukhjeet Singh | Patiala | Computer Engg. |
| 104 | Bimal Roy | Calcutta | Computer Engg. |
+------+----------------------+----------------------+----------------------+
5 rows in set (0.00 sec)
We can see from the above result set that Employee table is having so many whitespaces in its rows. It can be removed and updated with the following query −
mysql> Update Employee SET Id = TRIM(Id), Name = TRIM(Name), Address = TRIM(Address), DEPARTMENT = TRIM(Department);
Query OK, 5 rows affected (0.24 sec)
Rows matched: 5 Changed: 5 Warnings: 0
mysql> Select * from Employee;
+------+----------------+------------+----------------+
| Id | Name | Address | Department |
+------+----------------+------------+----------------+
| 100 | Raman | Delhi | IT |
| 101 | Mohan | Haryana | History |
| 102 | Shyam | Chandigarh | ENGLISH |
| 103 | Sukhjeet Singh | Patiala | Computer Engg. |
| 104 | Bimal Roy | Calcutta | Computer Engg. |
+------+----------------+------------+----------------+
5 rows in set (0.00 sec)
We can see from the above result set that all the whitespaces have been removed and the table is updated.
|
[
{
"code": null,
"e": 1383,
"s": 1062,
"text": "Suppose if a table has many values having whitespaces in the columns of a table then it is wastage of space. We can use TRIM() function to remove whitespaces from all the rows and update the table too in a single query. Following the example from ‘Employee’, having whitespaces in all its rows will exhibit the concept −"
},
{
"code": null,
"e": 2161,
"s": 1383,
"text": "mysql> Select * from Employee;\n+------+----------------------+----------------------+----------------------+\n| Id | Name | Address | Department |\n+------+----------------------+----------------------+----------------------+\n| 100 | Raman | Delhi | IT |\n| 101 | Mohan | Haryana | History |\n| 102 | Shyam | Chandigarh | ENGLISH |\n| 103 | Sukhjeet Singh | Patiala | Computer Engg. |\n| 104 | Bimal Roy | Calcutta | Computer Engg. | \n+------+----------------------+----------------------+----------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2318,
"s": 2161,
"text": "We can see from the above result set that Employee table is having so many whitespaces in its rows. It can be removed and updated with the following query −"
},
{
"code": null,
"e": 3072,
"s": 2318,
"text": "mysql> Update Employee SET Id = TRIM(Id), Name = TRIM(Name), Address = TRIM(Address), DEPARTMENT = TRIM(Department);\nQuery OK, 5 rows affected (0.24 sec)\nRows matched: 5 Changed: 5 Warnings: 0\n\nmysql> Select * from Employee;\n+------+----------------+------------+----------------+\n| Id | Name | Address | Department |\n+------+----------------+------------+----------------+\n| 100 | Raman | Delhi | IT |\n| 101 | Mohan | Haryana | History |\n| 102 | Shyam | Chandigarh | ENGLISH |\n| 103 | Sukhjeet Singh | Patiala | Computer Engg. |\n| 104 | Bimal Roy | Calcutta | Computer Engg. |\n+------+----------------+------------+----------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3178,
"s": 3072,
"text": "We can see from the above result set that all the whitespaces have been removed and the table is updated."
}
] |
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built in Python for automating ML worflows | Towards Data Science
|
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently.
PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes the experiment cycle exponentially fast and efficient.
PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it.
This tutorial assumes that you have some prior knowledge and experience with PyCaret. If you haven’t used it before, no problem — you can get a quick headstart through these tutorials:
PyCaret 2.2 is here — what’s new
Announcing PyCaret 2.0
Five things you don’t know about PyCaret
In my last tutorial, I have demonstrated how you can use PyCaret to forecast time-series data using Machine Learning through PyCaret Regression Module. If you haven’t read that yet, you can read Time Series Forecasting with PyCaret Regression Module tutorial before continuing with this one, as this tutorial builds upon some important concepts covered in the last tutorial.
Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries.
PyCaret’s default installation is a slim version of pycaret which only installs hard dependencies that are listed here.
# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]
When you install the full version of pycaret, all the optional dependencies as listed here are also installed.
PyCaret Regression Module is a supervised machine learning module used for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, or ‘predictors’).
The objective of regression is to predict continuous values such as sales amount, quantity, temperature, number of customers, etc. All modules in PyCaret provide many pre-processing features to prepare the data for modeling through the setup function. It has over 25 ready-to-use algorithms and several plots to analyze the performance of trained models.
For this tutorial, I will show the end-to-end implementation of multiple time-series data forecasting, including both the training as well as predicting future values.
I have used the Store Item Demand Forecasting Challenge dataset from Kaggle. This dataset has 10 different stores and each store has 50 items, i.e. total of 500 daily level time series data for five years (2013–2017).
# read the csv fileimport pandas as pddata = pd.read_csv('train.csv')data['date'] = pd.to_datetime(data['date'])# combine store and item column as time_seriesdata['store'] = ['store_' + str(i) for i in data['store']]data['item'] = ['item_' + str(i) for i in data['item']]data['time_series'] = data[['store', 'item']].apply(lambda x: '_'.join(x), axis=1)data.drop(['store', 'item'], axis=1, inplace=True)# extract features from datedata['month'] = [i.month for i in data['date']]data['year'] = [i.year for i in data['date']]data['day_of_week'] = [i.dayofweek for i in data['date']]data['day_of_year'] = [i.dayofyear for i in data['date']]data.head()
# check the unique time_seriesdata['time_series'].nunique()>>> 500
# plot multiple time series with moving avgs in a loopimport plotly.express as pxfor i in data['time_series'].unique(): subset = data[data['time_series'] == i] subset['moving_average'] = subset['sales'].rolling(30).mean() fig = px.line(subset, x="date", y=["sales","moving_average"], title = i, template = 'plotly_dark') fig.show()
Now that we have the data ready, let’s start the training loop. Notice that verbose = False in all functions to avoid printing results on the console while training.
The code below is a loop around time_series column we created during the data preparatory step. There are a total of 150 time series (10 stores x 50 items).
Line 10 below is filtering the dataset for time_series variable. The first part inside the loop is initializing the setup function, followed by compare_models to find the best model. Line 24–26 captures the results and appends the performance metrics of the best model in a list called all_results . The last part of the code uses the finalize_model function to retrain the best model on the entire dataset including the 5% left in the test set and saves the entire pipeline including the model as a pickle file.
We can now create a data frame from all_results list. It will display the best model selected for each time series.
concat_results = pd.concat(all_results,axis=0)concat_results.head()
Now that we have trained models, let’s use them to generate predictions, but first, we need to create the dataset for scoring (X variables).
# create a date range from 2013 to 2019all_dates = pd.date_range(start='2013-01-01', end = '2019-12-31', freq = 'D')# create empty dataframescore_df = pd.DataFrame()# add columns to datasetscore_df['date'] = all_datesscore_df['month'] = [i.month for i in score_df['date']]score_df['year'] = [i.year for i in score_df['date']]score_df['day_of_week'] = [i.dayofweek for i in score_df['date']]score_df['day_of_year'] = [i.dayofyear for i in score_df['date']]score_df.head()
Now let’s create a loop to load the trained pipelines and use the predict_model function to generate prediction labels.
from pycaret.regression import load_model, predict_modelall_score_df = []for i in tqdm(data['time_series'].unique()): l = load_model('trained_models/' + str(i), verbose=False) p = predict_model(l, data=score_df) p['time_series'] = i all_score_df.append(p)concat_df = pd.concat(all_score_df, axis=0)concat_df.head()
We will now join the dataand concat_df .
final_df = pd.merge(concat_df, data, how = 'left', left_on=['date', 'time_series'], right_on = ['date', 'time_series'])final_df.head()
We can now create a loop to see all plots.
for i in final_df['time_series'].unique()[:5]: sub_df = final_df[final_df['time_series'] == i] import plotly.express as px fig = px.line(sub_df, x="date", y=['sales', 'Label'], title=i, template = 'plotly_dark') fig.show()
I hope that you will appreciate the ease of use and simplicity in PyCaret. In less than 50 lines of code and one hour of experimentation, I have trained over 10,000 models (25 estimators x 500 time series) and productionalized 500 best models to generate predictions.
Next week I will be writing a tutorial on unsupervised anomaly detection on time-series data using PyCaret Anomaly Detection Module. Please follow me on Medium, LinkedIn, and Twitter to get more updates.
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.
Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE
DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret
Click on the links below to see the documentation and working examples.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
|
[
{
"code": null,
"e": 469,
"s": 172,
"text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently."
},
{
"code": null,
"e": 651,
"s": 469,
"text": "PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes the experiment cycle exponentially fast and efficient."
},
{
"code": null,
"e": 972,
"s": 651,
"text": "PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it."
},
{
"code": null,
"e": 1157,
"s": 972,
"text": "This tutorial assumes that you have some prior knowledge and experience with PyCaret. If you haven’t used it before, no problem — you can get a quick headstart through these tutorials:"
},
{
"code": null,
"e": 1190,
"s": 1157,
"text": "PyCaret 2.2 is here — what’s new"
},
{
"code": null,
"e": 1213,
"s": 1190,
"text": "Announcing PyCaret 2.0"
},
{
"code": null,
"e": 1254,
"s": 1213,
"text": "Five things you don’t know about PyCaret"
},
{
"code": null,
"e": 1629,
"s": 1254,
"text": "In my last tutorial, I have demonstrated how you can use PyCaret to forecast time-series data using Machine Learning through PyCaret Regression Module. If you haven’t read that yet, you can read Time Series Forecasting with PyCaret Regression Module tutorial before continuing with this one, as this tutorial builds upon some important concepts covered in the last tutorial."
},
{
"code": null,
"e": 1792,
"s": 1629,
"text": "Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries."
},
{
"code": null,
"e": 1912,
"s": 1792,
"text": "PyCaret’s default installation is a slim version of pycaret which only installs hard dependencies that are listed here."
},
{
"code": null,
"e": 2015,
"s": 1912,
"text": "# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]"
},
{
"code": null,
"e": 2126,
"s": 2015,
"text": "When you install the full version of pycaret, all the optional dependencies as listed here are also installed."
},
{
"code": null,
"e": 2392,
"s": 2126,
"text": "PyCaret Regression Module is a supervised machine learning module used for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, or ‘predictors’)."
},
{
"code": null,
"e": 2747,
"s": 2392,
"text": "The objective of regression is to predict continuous values such as sales amount, quantity, temperature, number of customers, etc. All modules in PyCaret provide many pre-processing features to prepare the data for modeling through the setup function. It has over 25 ready-to-use algorithms and several plots to analyze the performance of trained models."
},
{
"code": null,
"e": 2915,
"s": 2747,
"text": "For this tutorial, I will show the end-to-end implementation of multiple time-series data forecasting, including both the training as well as predicting future values."
},
{
"code": null,
"e": 3133,
"s": 2915,
"text": "I have used the Store Item Demand Forecasting Challenge dataset from Kaggle. This dataset has 10 different stores and each store has 50 items, i.e. total of 500 daily level time series data for five years (2013–2017)."
},
{
"code": null,
"e": 3782,
"s": 3133,
"text": "# read the csv fileimport pandas as pddata = pd.read_csv('train.csv')data['date'] = pd.to_datetime(data['date'])# combine store and item column as time_seriesdata['store'] = ['store_' + str(i) for i in data['store']]data['item'] = ['item_' + str(i) for i in data['item']]data['time_series'] = data[['store', 'item']].apply(lambda x: '_'.join(x), axis=1)data.drop(['store', 'item'], axis=1, inplace=True)# extract features from datedata['month'] = [i.month for i in data['date']]data['year'] = [i.year for i in data['date']]data['day_of_week'] = [i.dayofweek for i in data['date']]data['day_of_year'] = [i.dayofyear for i in data['date']]data.head()"
},
{
"code": null,
"e": 3849,
"s": 3782,
"text": "# check the unique time_seriesdata['time_series'].nunique()>>> 500"
},
{
"code": null,
"e": 4193,
"s": 3849,
"text": "# plot multiple time series with moving avgs in a loopimport plotly.express as pxfor i in data['time_series'].unique(): subset = data[data['time_series'] == i] subset['moving_average'] = subset['sales'].rolling(30).mean() fig = px.line(subset, x=\"date\", y=[\"sales\",\"moving_average\"], title = i, template = 'plotly_dark') fig.show()"
},
{
"code": null,
"e": 4359,
"s": 4193,
"text": "Now that we have the data ready, let’s start the training loop. Notice that verbose = False in all functions to avoid printing results on the console while training."
},
{
"code": null,
"e": 4516,
"s": 4359,
"text": "The code below is a loop around time_series column we created during the data preparatory step. There are a total of 150 time series (10 stores x 50 items)."
},
{
"code": null,
"e": 5029,
"s": 4516,
"text": "Line 10 below is filtering the dataset for time_series variable. The first part inside the loop is initializing the setup function, followed by compare_models to find the best model. Line 24–26 captures the results and appends the performance metrics of the best model in a list called all_results . The last part of the code uses the finalize_model function to retrain the best model on the entire dataset including the 5% left in the test set and saves the entire pipeline including the model as a pickle file."
},
{
"code": null,
"e": 5145,
"s": 5029,
"text": "We can now create a data frame from all_results list. It will display the best model selected for each time series."
},
{
"code": null,
"e": 5213,
"s": 5145,
"text": "concat_results = pd.concat(all_results,axis=0)concat_results.head()"
},
{
"code": null,
"e": 5354,
"s": 5213,
"text": "Now that we have trained models, let’s use them to generate predictions, but first, we need to create the dataset for scoring (X variables)."
},
{
"code": null,
"e": 5825,
"s": 5354,
"text": "# create a date range from 2013 to 2019all_dates = pd.date_range(start='2013-01-01', end = '2019-12-31', freq = 'D')# create empty dataframescore_df = pd.DataFrame()# add columns to datasetscore_df['date'] = all_datesscore_df['month'] = [i.month for i in score_df['date']]score_df['year'] = [i.year for i in score_df['date']]score_df['day_of_week'] = [i.dayofweek for i in score_df['date']]score_df['day_of_year'] = [i.dayofyear for i in score_df['date']]score_df.head()"
},
{
"code": null,
"e": 5945,
"s": 5825,
"text": "Now let’s create a loop to load the trained pipelines and use the predict_model function to generate prediction labels."
},
{
"code": null,
"e": 6272,
"s": 5945,
"text": "from pycaret.regression import load_model, predict_modelall_score_df = []for i in tqdm(data['time_series'].unique()): l = load_model('trained_models/' + str(i), verbose=False) p = predict_model(l, data=score_df) p['time_series'] = i all_score_df.append(p)concat_df = pd.concat(all_score_df, axis=0)concat_df.head()"
},
{
"code": null,
"e": 6313,
"s": 6272,
"text": "We will now join the dataand concat_df ."
},
{
"code": null,
"e": 6448,
"s": 6313,
"text": "final_df = pd.merge(concat_df, data, how = 'left', left_on=['date', 'time_series'], right_on = ['date', 'time_series'])final_df.head()"
},
{
"code": null,
"e": 6491,
"s": 6448,
"text": "We can now create a loop to see all plots."
},
{
"code": null,
"e": 6730,
"s": 6491,
"text": "for i in final_df['time_series'].unique()[:5]: sub_df = final_df[final_df['time_series'] == i] import plotly.express as px fig = px.line(sub_df, x=\"date\", y=['sales', 'Label'], title=i, template = 'plotly_dark') fig.show()"
},
{
"code": null,
"e": 6998,
"s": 6730,
"text": "I hope that you will appreciate the ease of use and simplicity in PyCaret. In less than 50 lines of code and one hour of experimentation, I have trained over 10,000 models (25 estimators x 500 time series) and productionalized 500 best models to generate predictions."
},
{
"code": null,
"e": 7202,
"s": 6998,
"text": "Next week I will be writing a tutorial on unsupervised anomaly detection on time-series data using PyCaret Anomaly Detection Module. Please follow me on Medium, LinkedIn, and Twitter to get more updates."
},
{
"code": null,
"e": 7392,
"s": 7202,
"text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository."
},
{
"code": null,
"e": 7454,
"s": 7392,
"text": "To hear more about PyCaret follow us on LinkedIn and Youtube."
},
{
"code": null,
"e": 7502,
"s": 7454,
"text": "Join us on our slack channel. Invite link here."
},
{
"code": null,
"e": 7965,
"s": 7502,
"text": "Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE"
},
{
"code": null,
"e": 8056,
"s": 7965,
"text": "DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret"
},
{
"code": null,
"e": 8128,
"s": 8056,
"text": "Click on the links below to see the documentation and working examples."
}
] |
C Program to sum the digits of a given number in single statement
|
In this section we will see how to find the sum of digits without writing multiple statements. In other
words, we will find the sum of digits in a single statement.
As we know that, to find the sum of digits we cut the last digit by taking the remainder after
dividing the number by 10, and then divide the number by 10 again and again until the number
becomes 0.
To do these task in a single statement the for loop can be used. As we know there are three
different sections in the for loop. In the initialization phase we are doing nothing in this case, then in
the condition checking phase are checking whether the number is greater than 0 or not. In the
increment decrement phase, we are doing multiple tasks. At first we are incrementing the sum by
taking the last digits of the number, and also reduce the number by dividing it by 10.
#include<stdio.h>
main() {
int n, sum = 0;
printf("Enter a number: "); //take the number from the user
scanf("%d", &n);
for(; n > 0; sum += n%10, n/= 10) {
}
printf("The sum of digits: %d", sum);
}
Enter a number: 457
The sum of digits: 16
|
[
{
"code": null,
"e": 1227,
"s": 1062,
"text": "In this section we will see how to find the sum of digits without writing multiple statements. In other\nwords, we will find the sum of digits in a single statement."
},
{
"code": null,
"e": 1426,
"s": 1227,
"text": "As we know that, to find the sum of digits we cut the last digit by taking the remainder after\ndividing the number by 10, and then divide the number by 10 again and again until the number\nbecomes 0."
},
{
"code": null,
"e": 1902,
"s": 1426,
"text": "To do these task in a single statement the for loop can be used. As we know there are three\ndifferent sections in the for loop. In the initialization phase we are doing nothing in this case, then in\nthe condition checking phase are checking whether the number is greater than 0 or not. In the\nincrement decrement phase, we are doing multiple tasks. At first we are incrementing the sum by\ntaking the last digits of the number, and also reduce the number by dividing it by 10."
},
{
"code": null,
"e": 2118,
"s": 1902,
"text": "#include<stdio.h>\nmain() {\n int n, sum = 0;\n printf(\"Enter a number: \"); //take the number from the user\n scanf(\"%d\", &n);\n for(; n > 0; sum += n%10, n/= 10) {\n }\n printf(\"The sum of digits: %d\", sum);\n}"
},
{
"code": null,
"e": 2160,
"s": 2118,
"text": "Enter a number: 457\nThe sum of digits: 16"
}
] |
Data Classes in Python | Set 4 (Inheritance) - GeeksforGeeks
|
12 Apr, 2019
Prerequisites: Inheritance In Python, Data Classes in Python | Set 3
In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited.
from dataclasses import dataclass @dataclassclass Article: title: str content: str author: str @dataclassclass GfgArticle(Article): language: str author: str upvotes: int = 0
Few points from above code:
Article is subclassed by GfgArticleBoth SuperClass and SubClass are DataClasses – although super-class or sub-class being a normal class is also possible. When a DataClass inherits a normal class, the __init__() from the super-class is overidden in sub-class.author in GfgArticle overrides the same in Article – As the basic concept of inheritance, the value for its assignment is first looked in the sub-class and followed up the tree in super-class.
Article is subclassed by GfgArticle
Both SuperClass and SubClass are DataClasses – although super-class or sub-class being a normal class is also possible. When a DataClass inherits a normal class, the __init__() from the super-class is overidden in sub-class.
author in GfgArticle overrides the same in Article – As the basic concept of inheritance, the value for its assignment is first looked in the sub-class and followed up the tree in super-class.
Behaviour of __init__() of GfgArticle:
If __init__() is not explicitly provided, the default __init__() expects attributes of super-class (Article) followed by attributes of sub-class as parameters.GfgArticle(title: str, content: str, author: str, language: str, upvotes: int = 0)Note: The signature expects author before language in-spite of opposite order of declaration in GfgArticle. This comes from the fact that attributes are scanned top to bottom from super-class followed by sub-class. So author is first scanned in Article then language is scanned in GfgArticle.dClassObj = GfgArticle("DataClass", "SuperCool DataStructure", "vibhu4agarwal", "Python3")print(dClassObj)Output:GfgArticle(title=’DataClass’, content=’SuperCool DataStructure’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)
GfgArticle(title: str, content: str, author: str, language: str, upvotes: int = 0)
Note: The signature expects author before language in-spite of opposite order of declaration in GfgArticle. This comes from the fact that attributes are scanned top to bottom from super-class followed by sub-class. So author is first scanned in Article then language is scanned in GfgArticle.
dClassObj = GfgArticle("DataClass", "SuperCool DataStructure", "vibhu4agarwal", "Python3")print(dClassObj)
Output:
GfgArticle(title=’DataClass’, content=’SuperCool DataStructure’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)
If __init__() is explicitly provided, it should somehow initialize all it’s own attributes as well as those in the super-class (Article).from dataclasses import dataclass @dataclassclass Article: title: str content: str author: str @dataclass(init = False)class GfgArticle(Article): language: str author: str upvotes: int = 0 def __init__(self, title): self.title = title self.language = "Python3" self.author = "vibhu4agarwal" self.content = "Inheritance Concepts" dClassObj = GfgArticle("DataClass")print(dClassObj)
from dataclasses import dataclass @dataclassclass Article: title: str content: str author: str @dataclass(init = False)class GfgArticle(Article): language: str author: str upvotes: int = 0 def __init__(self, title): self.title = title self.language = "Python3" self.author = "vibhu4agarwal" self.content = "Inheritance Concepts" dClassObj = GfgArticle("DataClass")print(dClassObj)
Output:
GfgArticle(title=’DataClass’, content=’Inheritance Concepts’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)
Note:
Parameters requirement in __init__() can be adjusted according to the need as long as it has some way of initializing all the attributes.
Order of initialization doesn’t matter. language is initialized before author, while content is initialized at last and it still works.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 23970,
"s": 23901,
"text": "Prerequisites: Inheritance In Python, Data Classes in Python | Set 3"
},
{
"code": null,
"e": 24161,
"s": 23970,
"text": "In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited."
},
{
"code": "from dataclasses import dataclass @dataclassclass Article: title: str content: str author: str @dataclassclass GfgArticle(Article): language: str author: str upvotes: int = 0",
"e": 24372,
"s": 24161,
"text": null
},
{
"code": null,
"e": 24400,
"s": 24372,
"text": "Few points from above code:"
},
{
"code": null,
"e": 24852,
"s": 24400,
"text": "Article is subclassed by GfgArticleBoth SuperClass and SubClass are DataClasses – although super-class or sub-class being a normal class is also possible. When a DataClass inherits a normal class, the __init__() from the super-class is overidden in sub-class.author in GfgArticle overrides the same in Article – As the basic concept of inheritance, the value for its assignment is first looked in the sub-class and followed up the tree in super-class."
},
{
"code": null,
"e": 24888,
"s": 24852,
"text": "Article is subclassed by GfgArticle"
},
{
"code": null,
"e": 25113,
"s": 24888,
"text": "Both SuperClass and SubClass are DataClasses – although super-class or sub-class being a normal class is also possible. When a DataClass inherits a normal class, the __init__() from the super-class is overidden in sub-class."
},
{
"code": null,
"e": 25306,
"s": 25113,
"text": "author in GfgArticle overrides the same in Article – As the basic concept of inheritance, the value for its assignment is first looked in the sub-class and followed up the tree in super-class."
},
{
"code": null,
"e": 25345,
"s": 25306,
"text": "Behaviour of __init__() of GfgArticle:"
},
{
"code": null,
"e": 26177,
"s": 25345,
"text": "If __init__() is not explicitly provided, the default __init__() expects attributes of super-class (Article) followed by attributes of sub-class as parameters.GfgArticle(title: str, content: str, author: str, language: str, upvotes: int = 0)Note: The signature expects author before language in-spite of opposite order of declaration in GfgArticle. This comes from the fact that attributes are scanned top to bottom from super-class followed by sub-class. So author is first scanned in Article then language is scanned in GfgArticle.dClassObj = GfgArticle(\"DataClass\", \"SuperCool DataStructure\", \"vibhu4agarwal\", \"Python3\")print(dClassObj)Output:GfgArticle(title=’DataClass’, content=’SuperCool DataStructure’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)"
},
{
"code": null,
"e": 26260,
"s": 26177,
"text": "GfgArticle(title: str, content: str, author: str, language: str, upvotes: int = 0)"
},
{
"code": null,
"e": 26553,
"s": 26260,
"text": "Note: The signature expects author before language in-spite of opposite order of declaration in GfgArticle. This comes from the fact that attributes are scanned top to bottom from super-class followed by sub-class. So author is first scanned in Article then language is scanned in GfgArticle."
},
{
"code": "dClassObj = GfgArticle(\"DataClass\", \"SuperCool DataStructure\", \"vibhu4agarwal\", \"Python3\")print(dClassObj)",
"e": 26726,
"s": 26553,
"text": null
},
{
"code": null,
"e": 26734,
"s": 26726,
"text": "Output:"
},
{
"code": null,
"e": 26854,
"s": 26734,
"text": "GfgArticle(title=’DataClass’, content=’SuperCool DataStructure’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)"
},
{
"code": null,
"e": 27434,
"s": 26854,
"text": "If __init__() is explicitly provided, it should somehow initialize all it’s own attributes as well as those in the super-class (Article).from dataclasses import dataclass @dataclassclass Article: title: str content: str author: str @dataclass(init = False)class GfgArticle(Article): language: str author: str upvotes: int = 0 def __init__(self, title): self.title = title self.language = \"Python3\" self.author = \"vibhu4agarwal\" self.content = \"Inheritance Concepts\" dClassObj = GfgArticle(\"DataClass\")print(dClassObj)"
},
{
"code": "from dataclasses import dataclass @dataclassclass Article: title: str content: str author: str @dataclass(init = False)class GfgArticle(Article): language: str author: str upvotes: int = 0 def __init__(self, title): self.title = title self.language = \"Python3\" self.author = \"vibhu4agarwal\" self.content = \"Inheritance Concepts\" dClassObj = GfgArticle(\"DataClass\")print(dClassObj)",
"e": 27877,
"s": 27434,
"text": null
},
{
"code": null,
"e": 27885,
"s": 27877,
"text": "Output:"
},
{
"code": null,
"e": 28002,
"s": 27885,
"text": "GfgArticle(title=’DataClass’, content=’Inheritance Concepts’, author=’vibhu4agarwal’, language=’Python3′, upvotes=0)"
},
{
"code": null,
"e": 28008,
"s": 28002,
"text": "Note:"
},
{
"code": null,
"e": 28146,
"s": 28008,
"text": "Parameters requirement in __init__() can be adjusted according to the need as long as it has some way of initializing all the attributes."
},
{
"code": null,
"e": 28282,
"s": 28146,
"text": "Order of initialization doesn’t matter. language is initialized before author, while content is initialized at last and it still works."
},
{
"code": null,
"e": 28289,
"s": 28282,
"text": "Python"
},
{
"code": null,
"e": 28387,
"s": 28289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28396,
"s": 28387,
"text": "Comments"
},
{
"code": null,
"e": 28409,
"s": 28396,
"text": "Old Comments"
},
{
"code": null,
"e": 28430,
"s": 28409,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 28462,
"s": 28430,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28485,
"s": 28462,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 28507,
"s": 28485,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28534,
"s": 28507,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28550,
"s": 28534,
"text": "Deque in Python"
},
{
"code": null,
"e": 28592,
"s": 28550,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28648,
"s": 28592,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28693,
"s": 28648,
"text": "Python - Ways to remove duplicates from list"
}
] |
PL/SQL - IF-THEN Statement
|
It is the simplest form of the IF control statement, frequently used in decision-making and changing the control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is FALSE or NULL, then the IF statement does nothing.
Syntax for IF-THEN statement is −
IF condition THEN
S;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement. Following is an example of the IF-THEN statement −
IF (a <= 20) THEN
c:= c+1;
END IF;
If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.
Let us try an example that will help you understand the concept −
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is less than 20
value of a is : 10
PL/SQL procedure successfully completed.
Consider we have a table and few records in the table as we had created in PL/SQL Variable Types
DECLARE
c_id customers.id%type := 1;
c_sal customers.salary%type;
BEGIN
SELECT salary
INTO c_sal
FROM customers
WHERE id = c_id;
IF (c_sal <= 2000) THEN
UPDATE customers
SET salary = salary + 1000
WHERE id = c_id;
dbms_output.put_line ('Salary updated');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Salary updated
PL/SQL procedure successfully completed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2209,
"s": 2065,
"text": "It is the simplest form of the IF control statement, frequently used in decision-making and changing the control flow of the program execution."
},
{
"code": null,
"e": 2451,
"s": 2209,
"text": "The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is FALSE or NULL, then the IF statement does nothing."
},
{
"code": null,
"e": 2485,
"s": 2451,
"text": "Syntax for IF-THEN statement is −"
},
{
"code": null,
"e": 2522,
"s": 2485,
"text": "IF condition THEN \n S; \nEND IF; \n"
},
{
"code": null,
"e": 2667,
"s": 2522,
"text": "Where condition is a Boolean or relational condition and S is a simple or compound statement. Following is an example of the IF-THEN statement −"
},
{
"code": null,
"e": 2705,
"s": 2667,
"text": "IF (a <= 20) THEN\n c:= c+1;\nEND IF;"
},
{
"code": null,
"e": 2977,
"s": 2705,
"text": "If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed."
},
{
"code": null,
"e": 3043,
"s": 2977,
"text": "Let us try an example that will help you understand the concept −"
},
{
"code": null,
"e": 3351,
"s": 3043,
"text": "DECLARE \n a number(2) := 10; \nBEGIN \n a:= 10; \n -- check the boolean condition using if statement \n IF( a < 20 ) THEN \n -- if condition is true then print the following \n dbms_output.put_line('a is less than 20 ' ); \n END IF; \n dbms_output.put_line('value of a is : ' || a); \nEND; \n/"
},
{
"code": null,
"e": 3437,
"s": 3351,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 3521,
"s": 3437,
"text": "a is less than 20 \nvalue of a is : 10 \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 3618,
"s": 3521,
"text": "Consider we have a table and few records in the table as we had created in PL/SQL Variable Types"
},
{
"code": null,
"e": 3960,
"s": 3618,
"text": "DECLARE \n c_id customers.id%type := 1; \n c_sal customers.salary%type; \nBEGIN \n SELECT salary \n INTO c_sal \n FROM customers \n WHERE id = c_id; \n IF (c_sal <= 2000) THEN \n UPDATE customers \n SET salary = salary + 1000 \n WHERE id = c_id; \n dbms_output.put_line ('Salary updated'); \n END IF; \nEND; \n/"
},
{
"code": null,
"e": 4046,
"s": 3960,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 4106,
"s": 4046,
"text": "Salary updated \n\nPL/SQL procedure successfully completed. "
},
{
"code": null,
"e": 4113,
"s": 4106,
"text": " Print"
},
{
"code": null,
"e": 4124,
"s": 4113,
"text": " Add Notes"
}
] |
continue statement in C
|
The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.
The syntax for a continue statement in C is as follows −
continue;
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2283,
"s": 2084,
"text": "The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between."
},
{
"code": null,
"e": 2511,
"s": 2283,
"text": "For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests."
},
{
"code": null,
"e": 2569,
"s": 2511,
"text": "The syntax for a continue statement in C is as follows −"
},
{
"code": null,
"e": 2580,
"s": 2569,
"text": "continue;\n"
},
{
"code": null,
"e": 2902,
"s": 2580,
"text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 10;\n\n /* do loop execution */\n do {\n \n if( a == 15) {\n /* skip the iteration */\n a = a + 1;\n continue;\n }\n\t\t\n printf(\"value of a: %d\\n\", a);\n a++;\n \n } while( a < 20 );\n \n return 0;\n}"
},
{
"code": null,
"e": 2983,
"s": 2902,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3119,
"s": 2983,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 3126,
"s": 3119,
"text": " Print"
},
{
"code": null,
"e": 3137,
"s": 3126,
"text": " Add Notes"
}
] |
3 Examples For Using Python Pandas More Efficiently | by Soner Yıldırım | Towards Data Science
|
Pandas is one of the most widely-used Python libraries in the data science ecosystem. It has numerous functions and methods to perform efficient and quick data analysis and manipulation.
In this article, we will go over 3 examples that show how to do some specific operations with Pandas.
The first and foremost requirement for practicing is data. I prepared a sales dataset that you can download from this repository on my GitHub page. Feel free to use it and follow along.
Let’s start with importing Pandas and reading the dataset into a data frame.
import pandas as pdsales = pd.read_csv("sales.csv")sales.head()
One of the most frequently used Pandas functions is the groupby. It basically allows for calculating aggregate values based on different categories in a column.
For instance, we can calculate the average product price for each product group as follows:
sales.groupby("product_group", as_index=False)["price"].mean()
There are several aggregate functions that we can use with the groupby such as min, max, mean, count, and so on. What I want to show here is that we can extend the capabilities of the groupby with a lambda function.
The data frame contains price and cost for each product. Consider we want to find the average profit of products in each product group. One method is to create a column that contain the profit information and then apply the mean function on it. If you do not prefer creating a new column, this operation can be done by applying a lambda function as follows.
sales.groupby("product_group").apply( lambda x: (x["price"] - x["cost"]).mean())product_groupPG1 98.071795PG2 42.973467PG3 26.299231PG4 13.141605PG5 18.657765PG6 15.200864dtype: float64
Duplicate rows in a data frame might cause serious issues. The analysis we do will not be correct so we need to make sure there are no duplicate rows in a data frame.
How we define duplicate rows depends on the dataset. In our case, two rows that have the same product code are considered to be duplicate. In some cases, two rows need to have the same values in all columns in order to be duplicates.
The duplicated and drop_duplicates functions come in quite handy when dealing with duplicate rows.
We can find the number of duplicate entries in the product code column as follows.
sales.duplicated(subset='product_code').sum()47
The duplicated function returns true if a product code is duplicated. By applying the sum function, we get the total number of duplicated product codes.
If we consider two rows being duplicate if they have the same product code and product group, then we pass these columns to the subset parameter as a list.
The drop_duplicated function drops the duplicated rows from the data frame.
sales_new = sales.drop_duplicates(subset="product_code", keep="first")sales_new.duplicated(subset="product_code").sum()0
The keep parameter is used for determining which one of the duplicated rows to be kept in the data frame.
For both duplicated and drop_duplicates functions, if we want to evaluate rows based on all the columns, we should not use the subset parameter.
We do not always have numerical data. It comes in different data types such as integer, float, string, object, datetime, and so on. In order to perform efficient and accurate operations, it is important to use appropriate data types.
Some functions and methods are only available for certain data types. Thus, before performing any analysis, we should convert the data types of columns that are not stored correctly.
Consider we have the following data frame.
df.dtypesA int64B float64C float64D objectE objectdtype: object
Column C seems to have integers but the data type is float because of the NaN value. Similarly, column E is stored with object data type but it should be boolean.
We can use the astype function to change the data types of each column separately. However, there is a more efficient option which is the convert_dtypes function. It converts columns to the best possible data types.
df_new = df.convert_dtypes()df_new.dtypesA Int64B Float64C Int64D stringE booleandtype: object
The best way to learn Pandas, or any other software tool, is through practicing. The more you get your hands dirty, the more you will make use of Pandas.
When you start working with real life datasets that need more cleaning and preprocessing, you will appreciate the functionality and efficiency of Pandas even better.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 359,
"s": 172,
"text": "Pandas is one of the most widely-used Python libraries in the data science ecosystem. It has numerous functions and methods to perform efficient and quick data analysis and manipulation."
},
{
"code": null,
"e": 461,
"s": 359,
"text": "In this article, we will go over 3 examples that show how to do some specific operations with Pandas."
},
{
"code": null,
"e": 647,
"s": 461,
"text": "The first and foremost requirement for practicing is data. I prepared a sales dataset that you can download from this repository on my GitHub page. Feel free to use it and follow along."
},
{
"code": null,
"e": 724,
"s": 647,
"text": "Let’s start with importing Pandas and reading the dataset into a data frame."
},
{
"code": null,
"e": 788,
"s": 724,
"text": "import pandas as pdsales = pd.read_csv(\"sales.csv\")sales.head()"
},
{
"code": null,
"e": 949,
"s": 788,
"text": "One of the most frequently used Pandas functions is the groupby. It basically allows for calculating aggregate values based on different categories in a column."
},
{
"code": null,
"e": 1041,
"s": 949,
"text": "For instance, we can calculate the average product price for each product group as follows:"
},
{
"code": null,
"e": 1104,
"s": 1041,
"text": "sales.groupby(\"product_group\", as_index=False)[\"price\"].mean()"
},
{
"code": null,
"e": 1320,
"s": 1104,
"text": "There are several aggregate functions that we can use with the groupby such as min, max, mean, count, and so on. What I want to show here is that we can extend the capabilities of the groupby with a lambda function."
},
{
"code": null,
"e": 1678,
"s": 1320,
"text": "The data frame contains price and cost for each product. Consider we want to find the average profit of products in each product group. One method is to create a column that contain the profit information and then apply the mean function on it. If you do not prefer creating a new column, this operation can be done by applying a lambda function as follows."
},
{
"code": null,
"e": 1884,
"s": 1678,
"text": "sales.groupby(\"product_group\").apply( lambda x: (x[\"price\"] - x[\"cost\"]).mean())product_groupPG1 98.071795PG2 42.973467PG3 26.299231PG4 13.141605PG5 18.657765PG6 15.200864dtype: float64"
},
{
"code": null,
"e": 2051,
"s": 1884,
"text": "Duplicate rows in a data frame might cause serious issues. The analysis we do will not be correct so we need to make sure there are no duplicate rows in a data frame."
},
{
"code": null,
"e": 2285,
"s": 2051,
"text": "How we define duplicate rows depends on the dataset. In our case, two rows that have the same product code are considered to be duplicate. In some cases, two rows need to have the same values in all columns in order to be duplicates."
},
{
"code": null,
"e": 2384,
"s": 2285,
"text": "The duplicated and drop_duplicates functions come in quite handy when dealing with duplicate rows."
},
{
"code": null,
"e": 2467,
"s": 2384,
"text": "We can find the number of duplicate entries in the product code column as follows."
},
{
"code": null,
"e": 2515,
"s": 2467,
"text": "sales.duplicated(subset='product_code').sum()47"
},
{
"code": null,
"e": 2668,
"s": 2515,
"text": "The duplicated function returns true if a product code is duplicated. By applying the sum function, we get the total number of duplicated product codes."
},
{
"code": null,
"e": 2824,
"s": 2668,
"text": "If we consider two rows being duplicate if they have the same product code and product group, then we pass these columns to the subset parameter as a list."
},
{
"code": null,
"e": 2900,
"s": 2824,
"text": "The drop_duplicated function drops the duplicated rows from the data frame."
},
{
"code": null,
"e": 3021,
"s": 2900,
"text": "sales_new = sales.drop_duplicates(subset=\"product_code\", keep=\"first\")sales_new.duplicated(subset=\"product_code\").sum()0"
},
{
"code": null,
"e": 3127,
"s": 3021,
"text": "The keep parameter is used for determining which one of the duplicated rows to be kept in the data frame."
},
{
"code": null,
"e": 3272,
"s": 3127,
"text": "For both duplicated and drop_duplicates functions, if we want to evaluate rows based on all the columns, we should not use the subset parameter."
},
{
"code": null,
"e": 3506,
"s": 3272,
"text": "We do not always have numerical data. It comes in different data types such as integer, float, string, object, datetime, and so on. In order to perform efficient and accurate operations, it is important to use appropriate data types."
},
{
"code": null,
"e": 3689,
"s": 3506,
"text": "Some functions and methods are only available for certain data types. Thus, before performing any analysis, we should convert the data types of columns that are not stored correctly."
},
{
"code": null,
"e": 3732,
"s": 3689,
"text": "Consider we have the following data frame."
},
{
"code": null,
"e": 3815,
"s": 3732,
"text": "df.dtypesA int64B float64C float64D objectE objectdtype: object"
},
{
"code": null,
"e": 3978,
"s": 3815,
"text": "Column C seems to have integers but the data type is float because of the NaN value. Similarly, column E is stored with object data type but it should be boolean."
},
{
"code": null,
"e": 4194,
"s": 3978,
"text": "We can use the astype function to change the data types of each column separately. However, there is a more efficient option which is the convert_dtypes function. It converts columns to the best possible data types."
},
{
"code": null,
"e": 4309,
"s": 4194,
"text": "df_new = df.convert_dtypes()df_new.dtypesA Int64B Float64C Int64D stringE booleandtype: object"
},
{
"code": null,
"e": 4463,
"s": 4309,
"text": "The best way to learn Pandas, or any other software tool, is through practicing. The more you get your hands dirty, the more you will make use of Pandas."
},
{
"code": null,
"e": 4629,
"s": 4463,
"text": "When you start working with real life datasets that need more cleaning and preprocessing, you will appreciate the functionality and efficiency of Pandas even better."
}
] |
PostgreSQL - Boolean Data Type - GeeksforGeeks
|
08 Jun, 2020
In this article, we will look into the PostgreSQL Boolean data type and it’s implementation while designing a database table. PostgreSQL boolean data type has 3 states namely TRUE< FALSE and NULL. It uses single byte for storing boolean value and can be abbreviated as BOOL.The below table depicts all valid literal values for TRUE and FALSE in PostgreSQL:
Now, let’s look into a few examples. For the same reason let’s create a sample database(say, bookstore) using the below command:
CREATE DATABASE bookstore;
Add a table (say, book_availability) to the bookstore database using the below command:
CREATE TABLE book_availability (
book_id INT NOT NULL PRIMARY KEY,
available BOOLEAN NOT NULL
);
Now insert some data to the book_availability table using the below command:
INSERT INTO book_availability (book_id, available)
VALUES
(100, TRUE),
(200, FALSE),
(300, 't'),
(400, '1'),
(500, 'y'),
(600, 'yes'),
(700, 'no'),
(800, '0');
Now that our database is ready let’s look into some examples.
Example 1:In this example we will query for all the available books in the bookstore.
SELECT
*
FROM
book_availability
WHERE
available = 'yes';
Output:Example 2:In this example we will query for all books that are NOT available in the bookstore.
SELECT
*
FROM
book_availability
WHERE
available = 'no';
Output:
Example 3:In this example we will make the use of NOT operator to check for books that are not available in the bookstore.
SELECT
*
FROM
book_availability
WHERE
NOT available;
Output:
postgreSQL
postgreSQL-dataTypes
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 - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
How to use PostgreSQL Database in Django?
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Select Into
PostgreSQL - LIMIT with OFFSET clause
|
[
{
"code": null,
"e": 27920,
"s": 27892,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 28277,
"s": 27920,
"text": "In this article, we will look into the PostgreSQL Boolean data type and it’s implementation while designing a database table. PostgreSQL boolean data type has 3 states namely TRUE< FALSE and NULL. It uses single byte for storing boolean value and can be abbreviated as BOOL.The below table depicts all valid literal values for TRUE and FALSE in PostgreSQL:"
},
{
"code": null,
"e": 28406,
"s": 28277,
"text": "Now, let’s look into a few examples. For the same reason let’s create a sample database(say, bookstore) using the below command:"
},
{
"code": null,
"e": 28433,
"s": 28406,
"text": "CREATE DATABASE bookstore;"
},
{
"code": null,
"e": 28521,
"s": 28433,
"text": "Add a table (say, book_availability) to the bookstore database using the below command:"
},
{
"code": null,
"e": 28626,
"s": 28521,
"text": "CREATE TABLE book_availability (\n book_id INT NOT NULL PRIMARY KEY,\n available BOOLEAN NOT NULL\n);"
},
{
"code": null,
"e": 28703,
"s": 28626,
"text": "Now insert some data to the book_availability table using the below command:"
},
{
"code": null,
"e": 28895,
"s": 28703,
"text": "INSERT INTO book_availability (book_id, available)\nVALUES\n (100, TRUE),\n (200, FALSE),\n (300, 't'),\n (400, '1'),\n (500, 'y'),\n (600, 'yes'),\n (700, 'no'),\n (800, '0');"
},
{
"code": null,
"e": 28957,
"s": 28895,
"text": "Now that our database is ready let’s look into some examples."
},
{
"code": null,
"e": 29043,
"s": 28957,
"text": "Example 1:In this example we will query for all the available books in the bookstore."
},
{
"code": null,
"e": 29112,
"s": 29043,
"text": "SELECT\n *\nFROM\n book_availability\nWHERE\n available = 'yes';"
},
{
"code": null,
"e": 29214,
"s": 29112,
"text": "Output:Example 2:In this example we will query for all books that are NOT available in the bookstore."
},
{
"code": null,
"e": 29282,
"s": 29214,
"text": "SELECT\n *\nFROM\n book_availability\nWHERE\n available = 'no';"
},
{
"code": null,
"e": 29290,
"s": 29282,
"text": "Output:"
},
{
"code": null,
"e": 29413,
"s": 29290,
"text": "Example 3:In this example we will make the use of NOT operator to check for books that are not available in the bookstore."
},
{
"code": null,
"e": 29478,
"s": 29413,
"text": "SELECT\n *\nFROM\n book_availability\nWHERE\n NOT available;"
},
{
"code": null,
"e": 29486,
"s": 29478,
"text": "Output:"
},
{
"code": null,
"e": 29497,
"s": 29486,
"text": "postgreSQL"
},
{
"code": null,
"e": 29518,
"s": 29497,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 29529,
"s": 29518,
"text": "PostgreSQL"
},
{
"code": null,
"e": 29627,
"s": 29529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29636,
"s": 29627,
"text": "Comments"
},
{
"code": null,
"e": 29649,
"s": 29636,
"text": "Old Comments"
},
{
"code": null,
"e": 29681,
"s": 29649,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 29708,
"s": 29681,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 29731,
"s": 29708,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 29771,
"s": 29731,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 29826,
"s": 29771,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 29868,
"s": 29826,
"text": "How to use PostgreSQL Database in Django?"
},
{
"code": null,
"e": 29892,
"s": 29868,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 29916,
"s": 29892,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 29941,
"s": 29916,
"text": "PostgreSQL - Select Into"
}
] |
An Introduction to Genetic Algorithms | by Anh T. Dang | Towards Data Science
|
Genetic Algorithms (GAs) are a part of Evolutionary Computing (EC), which is a rapidly growing area of Artificial Intelligence (AI). It inspired by the process of biological evolution based on Charles Darwin’s theory of natural selection, where fitter individuals are more likely to pass on their genes to the next generation. We, as human beings, also are the result of thousands of years of evolution.
The GA, developed by John Holland and his collaborators in the 1960s and 1970s.
As early as 1962, John Holland’s work on adaptive systems1 laid the foundation for later developments.
By the 1975, the publication of the book “Adaptation in Natural and Artificial Systems”2, by Holland and his students and colleagues.
The GA got popular in the late 1980s by was being applied to a broad range of subjects that are not easy to solve using other techniques.
In 1992, John Koza has used genetic algorithm to evolve programs to perform certain tasks. He called his method “genetic programming” (GP)3.
For thousands of years, humans have acted as agents of genetic selection, by breeding offspring with desired traits. All our domesticated animals and food crops are the results. Let review the genetic terms in nature as follows.
Each cell of a living thing contains chromosomes — strings of DNA.
Each chromosome contains a set of genes — blocks of DNA
Each gene determines some aspect of the organism (like eye colour)
A collection of genes is sometimes called a genotype
A collection of aspects (like eye colour) is sometimes called a phenotype
Reproduction (crossover) involves recombination of genes from parents and then small amounts of mutation (errors) in copying
The fitness of an organism is how much it can reproduce before it dies
Evolution based on “survival of the fittest”
Genetic Algorithms are categorized as global search heuristics. A genetic algorithm is a search technique used in computing to find true or approximate solutions to optimization and search problems. It uses techniques inspired by biological evolution such as inheritance, mutation, selection, and crossover.
We look at the basic process behind a genetic algorithm as follows.
Initialize population: genetic algorithms begin by initializing a Population of candidate solutions. This is typically done randomly to provide even coverage of the entire search space. A candidate solution is a Chromosome that is characterized by a set of parameters known as Genes.
Evaluate: next, the population is evaluated by assigning a fitness value to each individual in the population. In this stage we would often want to take note of the current fittest solution, and the average fitness of the population.
After evaluation, the algorithm decides whether it should terminate the search depending on the termination conditions set. Usually this will be because the algorithm has reached a fixed number of generations or an adequate solution has been found.
When the termination condition is finally met, the algorithm will break out of the loop and typically return its finial search results back to the user.
Selection: if the termination condition is not met, the population goes through a selection stage in which individuals from the population are selected based on their fitness score, the higher the fitness, the better chance an individual has of being selected.
Two pairs of selected individuals called parents.
Crossover: the next stage is to apply crossover and mutation to the selected individuals. This stage is where new individuals (children) are created for the next generation.
Mutation: at this point the new population goes back to the evaluation step and the process starts again. We call each cycle of this loop a generation.
Now, let’s see how to crack a password using a genetic algorithm. Imagine that a friend asks you to solve the following challenge: “You must find the three-letter word I set up as a password in my computer”.
In my example, we’ll start with a password of length 3, with each digit in the password being a letter. An example of password would be: nkA. We will start with a randomly generated initial sequence of letters, then change one random letter at a time until the word is “Anh”.
At first, we guess any randomly generated words made of three letters, such as “Ink, aNj, cDh”. The word Ink and cDh have exactly one letter in common with Anh, the password. We say that they have a score of 1. The word aNj has a score of 0 since it has no any matching letters with the password.
Since we haven’t found the solution, we can produce a new generation of words by combing some of the word we already have. For example, they are “Inh, aDj". From these two new words, the word Inh has a score of 2 and is very close to the password. We say that this second generation is better than the first second since it is closer to the solution.
A third-generation can be formed in which the word Inh can produce the word Anh in which the I is randomly mutated into A. This example is pretty simple to understand GA.
_letters = [a..zA..Z]target = "Anh"guess = get 3 random letters from _letters while guess != target: index = get random value from [0..length of target] guess[index] = get 1 random letter from _letters
Now, we will implement the example in Python language. Each digit in the password would be considered a Gene. We need a gene set to use for building guesses. For this example that will be a generic set of letters.
geneSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
It also needs a target password to guess.
target = "Anh"
Next the algorithm needs a way to generate a random string from the gene set.
import randomdef generate_parent(length): genes = [] while len(genes) < length: sampleSize = min(length - len(genes), len(geneSet)) genes.extend(random.sample(geneSet, sampleSize)) return ''.join(genes)
The fitness value the genetic algorithm provides is the only feedback the engine gets to guide it toward a solution. In this project the fitness value is the total number of letters in the guess that match the letter in the same position of the password.
def get_fitness(guess): return sum(1 for expected, actual in zip(target, guess) if expected == actual)
Next, the engine needs a way to produce a new guess by mutating the current one.
def mutate(parent): index = random.randrange(0, len(parent)) childGenes = list(parent) newGene, alternate = random.sample(geneSet, 2) childGenes[index] = alternate \ if newGene == childGenes[index] \ else newGene return ''.join(childGenes)
We also need display function to show information. Normally the display function also outputs the fitness value and how much time has elapsed.
import datetimedef display(guess): timeDiff = datetime.datetime.now() - startTime fitness = get_fitness(guess) print("{0}\t{1}\t{2}".format(guess, fitness, str(timeDiff)))
Finally, we will try to run this solution by using the above functions as following.
random.seed()geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"target = "Anh"startTime = datetime.datetime.now()bestParent = generate_parent(len(target))bestFitness = get_fitness(bestParent)display(bestParent)while True: child = mutate(bestParent) childFitness = get_fitness(child) if bestFitness >= childFitness: continue display(child) if childFitness >= len(bestParent): break bestFitness = childFitness bestParent = child
Run the above code and we’ll see the following output.
It’s very easy to understand about genetic algorithms. Right?
[1] Outline for a Logical Theory of Adaptive Systems
[2] Adaptation in Natural and Artificial Systems
[3] Genetic Programming: On the Programming of Computers by Means of Natural Selection
|
[
{
"code": null,
"e": 576,
"s": 172,
"text": "Genetic Algorithms (GAs) are a part of Evolutionary Computing (EC), which is a rapidly growing area of Artificial Intelligence (AI). It inspired by the process of biological evolution based on Charles Darwin’s theory of natural selection, where fitter individuals are more likely to pass on their genes to the next generation. We, as human beings, also are the result of thousands of years of evolution."
},
{
"code": null,
"e": 656,
"s": 576,
"text": "The GA, developed by John Holland and his collaborators in the 1960s and 1970s."
},
{
"code": null,
"e": 759,
"s": 656,
"text": "As early as 1962, John Holland’s work on adaptive systems1 laid the foundation for later developments."
},
{
"code": null,
"e": 893,
"s": 759,
"text": "By the 1975, the publication of the book “Adaptation in Natural and Artificial Systems”2, by Holland and his students and colleagues."
},
{
"code": null,
"e": 1031,
"s": 893,
"text": "The GA got popular in the late 1980s by was being applied to a broad range of subjects that are not easy to solve using other techniques."
},
{
"code": null,
"e": 1172,
"s": 1031,
"text": "In 1992, John Koza has used genetic algorithm to evolve programs to perform certain tasks. He called his method “genetic programming” (GP)3."
},
{
"code": null,
"e": 1401,
"s": 1172,
"text": "For thousands of years, humans have acted as agents of genetic selection, by breeding offspring with desired traits. All our domesticated animals and food crops are the results. Let review the genetic terms in nature as follows."
},
{
"code": null,
"e": 1468,
"s": 1401,
"text": "Each cell of a living thing contains chromosomes — strings of DNA."
},
{
"code": null,
"e": 1524,
"s": 1468,
"text": "Each chromosome contains a set of genes — blocks of DNA"
},
{
"code": null,
"e": 1591,
"s": 1524,
"text": "Each gene determines some aspect of the organism (like eye colour)"
},
{
"code": null,
"e": 1644,
"s": 1591,
"text": "A collection of genes is sometimes called a genotype"
},
{
"code": null,
"e": 1718,
"s": 1644,
"text": "A collection of aspects (like eye colour) is sometimes called a phenotype"
},
{
"code": null,
"e": 1843,
"s": 1718,
"text": "Reproduction (crossover) involves recombination of genes from parents and then small amounts of mutation (errors) in copying"
},
{
"code": null,
"e": 1914,
"s": 1843,
"text": "The fitness of an organism is how much it can reproduce before it dies"
},
{
"code": null,
"e": 1959,
"s": 1914,
"text": "Evolution based on “survival of the fittest”"
},
{
"code": null,
"e": 2267,
"s": 1959,
"text": "Genetic Algorithms are categorized as global search heuristics. A genetic algorithm is a search technique used in computing to find true or approximate solutions to optimization and search problems. It uses techniques inspired by biological evolution such as inheritance, mutation, selection, and crossover."
},
{
"code": null,
"e": 2335,
"s": 2267,
"text": "We look at the basic process behind a genetic algorithm as follows."
},
{
"code": null,
"e": 2619,
"s": 2335,
"text": "Initialize population: genetic algorithms begin by initializing a Population of candidate solutions. This is typically done randomly to provide even coverage of the entire search space. A candidate solution is a Chromosome that is characterized by a set of parameters known as Genes."
},
{
"code": null,
"e": 2853,
"s": 2619,
"text": "Evaluate: next, the population is evaluated by assigning a fitness value to each individual in the population. In this stage we would often want to take note of the current fittest solution, and the average fitness of the population."
},
{
"code": null,
"e": 3102,
"s": 2853,
"text": "After evaluation, the algorithm decides whether it should terminate the search depending on the termination conditions set. Usually this will be because the algorithm has reached a fixed number of generations or an adequate solution has been found."
},
{
"code": null,
"e": 3255,
"s": 3102,
"text": "When the termination condition is finally met, the algorithm will break out of the loop and typically return its finial search results back to the user."
},
{
"code": null,
"e": 3516,
"s": 3255,
"text": "Selection: if the termination condition is not met, the population goes through a selection stage in which individuals from the population are selected based on their fitness score, the higher the fitness, the better chance an individual has of being selected."
},
{
"code": null,
"e": 3566,
"s": 3516,
"text": "Two pairs of selected individuals called parents."
},
{
"code": null,
"e": 3740,
"s": 3566,
"text": "Crossover: the next stage is to apply crossover and mutation to the selected individuals. This stage is where new individuals (children) are created for the next generation."
},
{
"code": null,
"e": 3892,
"s": 3740,
"text": "Mutation: at this point the new population goes back to the evaluation step and the process starts again. We call each cycle of this loop a generation."
},
{
"code": null,
"e": 4100,
"s": 3892,
"text": "Now, let’s see how to crack a password using a genetic algorithm. Imagine that a friend asks you to solve the following challenge: “You must find the three-letter word I set up as a password in my computer”."
},
{
"code": null,
"e": 4376,
"s": 4100,
"text": "In my example, we’ll start with a password of length 3, with each digit in the password being a letter. An example of password would be: nkA. We will start with a randomly generated initial sequence of letters, then change one random letter at a time until the word is “Anh”."
},
{
"code": null,
"e": 4673,
"s": 4376,
"text": "At first, we guess any randomly generated words made of three letters, such as “Ink, aNj, cDh”. The word Ink and cDh have exactly one letter in common with Anh, the password. We say that they have a score of 1. The word aNj has a score of 0 since it has no any matching letters with the password."
},
{
"code": null,
"e": 5024,
"s": 4673,
"text": "Since we haven’t found the solution, we can produce a new generation of words by combing some of the word we already have. For example, they are “Inh, aDj\". From these two new words, the word Inh has a score of 2 and is very close to the password. We say that this second generation is better than the first second since it is closer to the solution."
},
{
"code": null,
"e": 5195,
"s": 5024,
"text": "A third-generation can be formed in which the word Inh can produce the word Anh in which the I is randomly mutated into A. This example is pretty simple to understand GA."
},
{
"code": null,
"e": 5406,
"s": 5195,
"text": "_letters = [a..zA..Z]target = \"Anh\"guess = get 3 random letters from _letters while guess != target: index = get random value from [0..length of target] guess[index] = get 1 random letter from _letters"
},
{
"code": null,
"e": 5620,
"s": 5406,
"text": "Now, we will implement the example in Python language. Each digit in the password would be considered a Gene. We need a gene set to use for building guesses. For this example that will be a generic set of letters."
},
{
"code": null,
"e": 5685,
"s": 5620,
"text": "geneSet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\""
},
{
"code": null,
"e": 5727,
"s": 5685,
"text": "It also needs a target password to guess."
},
{
"code": null,
"e": 5742,
"s": 5727,
"text": "target = \"Anh\""
},
{
"code": null,
"e": 5820,
"s": 5742,
"text": "Next the algorithm needs a way to generate a random string from the gene set."
},
{
"code": null,
"e": 6046,
"s": 5820,
"text": "import randomdef generate_parent(length): genes = [] while len(genes) < length: sampleSize = min(length - len(genes), len(geneSet)) genes.extend(random.sample(geneSet, sampleSize)) return ''.join(genes)"
},
{
"code": null,
"e": 6301,
"s": 6046,
"text": "The fitness value the genetic algorithm provides is the only feedback the engine gets to guide it toward a solution. In this project the fitness value is the total number of letters in the guess that match the letter in the same position of the password."
},
{
"code": null,
"e": 6421,
"s": 6301,
"text": "def get_fitness(guess): return sum(1 for expected, actual in zip(target, guess) if expected == actual)"
},
{
"code": null,
"e": 6502,
"s": 6421,
"text": "Next, the engine needs a way to produce a new guess by mutating the current one."
},
{
"code": null,
"e": 6771,
"s": 6502,
"text": "def mutate(parent): index = random.randrange(0, len(parent)) childGenes = list(parent) newGene, alternate = random.sample(geneSet, 2) childGenes[index] = alternate \\ if newGene == childGenes[index] \\ else newGene return ''.join(childGenes)"
},
{
"code": null,
"e": 6914,
"s": 6771,
"text": "We also need display function to show information. Normally the display function also outputs the fitness value and how much time has elapsed."
},
{
"code": null,
"e": 7095,
"s": 6914,
"text": "import datetimedef display(guess): timeDiff = datetime.datetime.now() - startTime fitness = get_fitness(guess) print(\"{0}\\t{1}\\t{2}\".format(guess, fitness, str(timeDiff)))"
},
{
"code": null,
"e": 7180,
"s": 7095,
"text": "Finally, we will try to run this solution by using the above functions as following."
},
{
"code": null,
"e": 7656,
"s": 7180,
"text": "random.seed()geneSet = \" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"target = \"Anh\"startTime = datetime.datetime.now()bestParent = generate_parent(len(target))bestFitness = get_fitness(bestParent)display(bestParent)while True: child = mutate(bestParent) childFitness = get_fitness(child) if bestFitness >= childFitness: continue display(child) if childFitness >= len(bestParent): break bestFitness = childFitness bestParent = child"
},
{
"code": null,
"e": 7711,
"s": 7656,
"text": "Run the above code and we’ll see the following output."
},
{
"code": null,
"e": 7773,
"s": 7711,
"text": "It’s very easy to understand about genetic algorithms. Right?"
},
{
"code": null,
"e": 7826,
"s": 7773,
"text": "[1] Outline for a Logical Theory of Adaptive Systems"
},
{
"code": null,
"e": 7875,
"s": 7826,
"text": "[2] Adaptation in Natural and Artificial Systems"
}
] |
ASCII sum difference of strings in JavaScript
|
ASCII is a 7-bit character code where every single bit represents a unique character. Every
English alphabet has a unique decimal ascii code.
We are required to write a function that takes in two strings and calculates their ascii scores (i.e., the sum of ascii decimal of each character of string) and returns the difference.
Let’s write the code for this function −
The code for this will be −
const str1 = 'This is an example sting';
const str2 = 'This is the second string';
const calculateScore = (str = '') => {
return str.split("").reduce((acc, val) => {
return acc + val.charCodeAt(0);
}, 0);
};
const ASCIIDifference = (str1, str2) => {
const firstScore = calculateScore(str1);
const secondScore = calculateScore(str2);
return Math.abs(firstScore - secondScore);
};
console.log(ASCIIDifference(str1, str2));
The output in the console −
116
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "ASCII is a 7-bit character code where every single bit represents a unique character. Every\nEnglish alphabet has a unique decimal ascii code."
},
{
"code": null,
"e": 1389,
"s": 1204,
"text": "We are required to write a function that takes in two strings and calculates their ascii scores (i.e., the sum of ascii decimal of each character of string) and returns the difference."
},
{
"code": null,
"e": 1430,
"s": 1389,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 1458,
"s": 1430,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1900,
"s": 1458,
"text": "const str1 = 'This is an example sting';\nconst str2 = 'This is the second string';\nconst calculateScore = (str = '') => {\n return str.split(\"\").reduce((acc, val) => {\n return acc + val.charCodeAt(0);\n }, 0);\n};\nconst ASCIIDifference = (str1, str2) => {\n const firstScore = calculateScore(str1);\n const secondScore = calculateScore(str2);\n return Math.abs(firstScore - secondScore);\n};\nconsole.log(ASCIIDifference(str1, str2));"
},
{
"code": null,
"e": 1928,
"s": 1900,
"text": "The output in the console −"
},
{
"code": null,
"e": 1932,
"s": 1928,
"text": "116"
}
] |
MariaDB - Create Database
|
Creation or deletion of databases in MariaDB requires privileges typically only given to root users or admins. Under these accounts, you have two options for creating a database − the mysqladmin binary and a PHP script.
The following example demonstrates the use of the mysqladmin binary in creating a database with the name Products −
[root@host]# mysqladmin -u root -p create PRODUCTS
Enter password:******
PHP employs the mysql_query function in creating a MariaDB database. The function uses two parameters, one optional, and returns either a value of “true” when successful, or “false” when not.
Review the following create database script syntax −
bool mysql_query( sql, connection );
The description of the parameters is given below −
sql
This required parameter consists of the SQL query needed to perform the operation.
connection
When not specified, this optional parameter uses the most recent connection used.
Try the following example code for creating a database −
<html>
<head>
<title>Create a MariaDB Database</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE PRODUCTS';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database PRODUCTS created successfully\n";
mysql_close($conn);
?>
</body>
</html>
On successful deletion, you will see the following output −
mysql> Database PRODUCTS created successfully
mysql> SHOW DATABASES;
+-----------------------+
| Database |
+-----------------------+
| PRODUCTS |
+-----------------------+
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2582,
"s": 2362,
"text": "Creation or deletion of databases in MariaDB requires privileges typically only given to root users or admins. Under these accounts, you have two options for creating a database − the mysqladmin binary and a PHP script."
},
{
"code": null,
"e": 2698,
"s": 2582,
"text": "The following example demonstrates the use of the mysqladmin binary in creating a database with the name Products −"
},
{
"code": null,
"e": 2772,
"s": 2698,
"text": "[root@host]# mysqladmin -u root -p create PRODUCTS\nEnter password:******\n"
},
{
"code": null,
"e": 2964,
"s": 2772,
"text": "PHP employs the mysql_query function in creating a MariaDB database. The function uses two parameters, one optional, and returns either a value of “true” when successful, or “false” when not."
},
{
"code": null,
"e": 3017,
"s": 2964,
"text": "Review the following create database script syntax −"
},
{
"code": null,
"e": 3055,
"s": 3017,
"text": "bool mysql_query( sql, connection );\n"
},
{
"code": null,
"e": 3106,
"s": 3055,
"text": "The description of the parameters is given below −"
},
{
"code": null,
"e": 3110,
"s": 3106,
"text": "sql"
},
{
"code": null,
"e": 3193,
"s": 3110,
"text": "This required parameter consists of the SQL query needed to perform the operation."
},
{
"code": null,
"e": 3204,
"s": 3193,
"text": "connection"
},
{
"code": null,
"e": 3286,
"s": 3204,
"text": "When not specified, this optional parameter uses the most recent connection used."
},
{
"code": null,
"e": 3343,
"s": 3286,
"text": "Try the following example code for creating a database −"
},
{
"code": null,
"e": 4059,
"s": 3343,
"text": "<html>\n <head>\n <title>Create a MariaDB Database</title>\n </head>\n\n <body>\n <?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n\n echo 'Connected successfully<br />';\n $sql = 'CREATE DATABASE PRODUCTS';\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not create database: ' . mysql_error());\n }\n\n echo \"Database PRODUCTS created successfully\\n\";\n mysql_close($conn);\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 4119,
"s": 4059,
"text": "On successful deletion, you will see the following output −"
},
{
"code": null,
"e": 4327,
"s": 4119,
"text": "mysql> Database PRODUCTS created successfully \nmysql> SHOW DATABASES; \n+-----------------------+ \n| Database | \n+-----------------------+ \n| PRODUCTS | \n+-----------------------+ \n"
},
{
"code": null,
"e": 4334,
"s": 4327,
"text": " Print"
},
{
"code": null,
"e": 4345,
"s": 4334,
"text": " Add Notes"
}
] |
hibernate cache | caching in hibernate | hibernate caching
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In the previous tutorials, we have discussed different states of hibernate object and also we discussed how load() and get() methods are working internally. Now we are going to discuss one more important topic in hibernate, what is hibernate cache and how it works exactly.
A cache is a local buffer. It improves the performance of the application by reducing the number of trips (hits) between Java application and database. Caching In hibernate are of 2 types :
First Level Cache
Second Level Cache
In Hibernate, when a session is opened then hibernate automatically opens a cache along with that session. When a session is closed then automatically cache also closed. Every session is associated with a corresponding cache. As a programmer we no need of doing any settings (configurations) either to enable or disable the first-level cache.
When a program wants an object from the database then hibernate first checks for that object in level1 cache. If that object does not exist in level1 cache then it checks in the second-level cache. If not exist in the second-level cache, then only hibernate goes to the database.
As we were discussed in the top 10 advantages of hibernate, caching in hibernate is the most powerful feature than compared with the other ORM frameworks. Hibernate also gives an excellent API to manage the states of objects too.
As we discussed, when a session is opened then automatically hibernate opens a cache. The life cycle of the cache is completely managed by the hibernate itself.
For each and every session, there will be a separate cache is opened. So level 1 cache is also called a local cache. When we are loading an object, hibernate first checks for that object in the local cache. If not existed then only it goes to the database and load an object.
On the above diagram,
Step 1 : We are trying to get the Student data from the database by using session.get(Student.class, 101); In this step Hibernate goes to first level cache and checks for the Student. But as this is the first request, Student object is not available in the cache.
Step 2 : In step 2 hibernate goes to Database to get the Student object.
Step 3 : In step 3 hibernate get an object from the database and save that object in the cache.
Step 4 : In step 4 returns that object to program.
After that, whenever the program wants that Student object, hibernate will directly get that object from the cache itself. We can see that in the Step a and Step b. Hence using hibernate cache mechanism the performance of an application will be increased.
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbOperations {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Student student = (Student) session.get(Student.class, 111);
/**
* At the first time there is no Student Object in first level cache,
* hence hibernate will go to database and get the Student Object, we
* can find the select statements in the output.
*
*/
System.out.println("Student Name : " + student.getName());
System.out.println("Student Id : " + student.getId());
System.out.println("Student Roll Number : " + student.getRollNumber());
System.out.println("=================================");
/**
* Here we are using the same session object to get the Student Details,
* that are already existed in the first level cache hence Hibernate
* will get the details from Session Cache.
*
*/
Student student2 = (Student) session.get(Student.class, 111);
System.out.println("Student Name : " + student2.getName());
System.out.println("Student Id : " + student2.getId());
System.out.println("Student Roll Number : " + student2.getRollNumber());
session.close();
}
}
Output :
Oct 09, 2015 11:29:03 PM org.hibernate.envers.boot.internal.EnversServiceImpl configure
INFO: Envers integration enabled? : true
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Student Name : John Student Id : 111 Student Roll Number : 7
================================================
Student Name : John Student Id : 111 Student Roll Number : 7
On the above example, if we observe output carefully to get the Student details for the first time to hibernate went to the database. We can find the database select query in the output. But in the second time the select query not executed, because the Students were taken from hibernate cache (First level cache) itself.
Suppose if want to read an object from the database only, but not from the cache then we can remove that object the cache by calling evict() method.
We can also delete all objects from the cache by calling clear() method.
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbOperations {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Student student = (Student) session.get(Student.class, 111);
System.out.println("Student Name : " + student.getName());
System.out.println("Student Id : " + student.getId());
System.out.println("Student Roll Number : " + student.getRollNumber());
System.out.println("=================================");
Student student2 = (Student) session.get(Student.class, 111);
System.out.println("Student 2 Name : " + student2.getName());
System.out.println("Student 2 Id : " + student2.getId());
System.out.println("Student 2 Roll Number : " + student2.getRollNumber());
System.out.println("=================================");
session.evict(student);
Student student3 = (Student) session.get(Student.class, 111);
System.out.println("Student 3 Name : " + student3.getName());
System.out.println("Student 3 Id : " + student3.getId());
System.out.println("Student 3 Roll Number : " + student3.getRollNumber());
session.close();
}
}
Output :
INFO: Envers integration enabled? : true
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Student Name : John Student Id : 111 Student Roll Number : 7
=================================
Student 2 Name : John Student 2 Id : 111 Student 2 Roll Number : 7
=================================
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Student 3 Name : John Student 3 Id : 111 Student 3 Roll Number : 7
When the above program is executed, then two times hibernate goes to the database for loading an object.
when evict() method is called hibernate finds the object, whether it existed in cache or not based on id property.
An only problem with the cache is if an object is updated in database explicitly or by another thread, then the changes are not automatically affected on the object stored in the cache.
It is the developer responsibility to refresh a session at regular intervals by calling session.refresh().
Happy Learning 🙂
Hibernate session differences between load() and get()
Hibernate Native SQL Query Example
Top 7 Interview Questions in Hibernate
Hibernate Filter Example Xml Configuration
Top 10 Advantages of Hibernate
Basic Hibernate Example with XML Configuration
HQL update, delete Query Example
Singleton Hibernate SessionFactory Example
Spring Boot Hazelcast Cache Example
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
hibernate update query example
Table per Class Strategy in Hibernate Inheritance
Hibernate session differences between load() and get()
Hibernate Native SQL Query Example
Top 7 Interview Questions in Hibernate
Hibernate Filter Example Xml Configuration
Top 10 Advantages of Hibernate
Basic Hibernate Example with XML Configuration
HQL update, delete Query Example
Singleton Hibernate SessionFactory Example
Spring Boot Hazelcast Cache Example
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
hibernate update query example
Table per Class Strategy in Hibernate Inheritance
Δ
Hibernate – Introduction
Hibernate – Advantages
Hibernate – Download and Setup
Hibernate – Sql Dialect list
Hibernate – Helloworld – XML
Hibernate – Install Tools in Eclipse
Hibernate – Object States
Hibernate – Helloworld – Annotations
Hibernate – One to One Mapping – XML
Hibernate – One to One Mapping foreign key – XML
Hibernate – One To Many -XML
Hibernate – One To Many – Annotations
Hibernate – Many to Many Mapping – XML
Hibernate – Many to One – XML
Hibernate – Composite Key Mapping
Hibernate – Named Query
Hibernate – Native SQL Query
Hibernate – load() vs get()
Hibernate Criteria API with Example
Hibernate – Restrictions
Hibernate – Projection
Hibernate – Query Language (HQL)
Hibernate – Groupby Criteria HQL
Hibernate – Orderby Criteria
Hibernate – HQLSelect Operation
Hibernate – HQL Update, Delete
Hibernate – Update Query
Hibernate – Update vs Merge
Hibernate – Right Join
Hibernate – Left Join
Hibernate – Pagination
Hibernate – Generator Classes
Hibernate – Custom Generator
Hibernate – Inheritance Mappings
Hibernate – Table per Class
Hibernate – Table per Sub Class
Hibernate – Table per Concrete Class
Hibernate – Table per Class Annotations
Hibernate – Stored Procedures
Hibernate – @Formula Annotation
Hibernate – Singleton SessionFactory
Hibernate – Interceptor
hbm2ddl.auto Example in Hibernate XML Config
Hibernate – First Level Cache
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 672,
"s": 398,
"text": "In the previous tutorials, we have discussed different states of hibernate object and also we discussed how load() and get() methods are working internally. Now we are going to discuss one more important topic in hibernate, what is hibernate cache and how it works exactly."
},
{
"code": null,
"e": 862,
"s": 672,
"text": "A cache is a local buffer. It improves the performance of the application by reducing the number of trips (hits) between Java application and database. Caching In hibernate are of 2 types :"
},
{
"code": null,
"e": 880,
"s": 862,
"text": "First Level Cache"
},
{
"code": null,
"e": 899,
"s": 880,
"text": "Second Level Cache"
},
{
"code": null,
"e": 1242,
"s": 899,
"text": "In Hibernate, when a session is opened then hibernate automatically opens a cache along with that session. When a session is closed then automatically cache also closed. Every session is associated with a corresponding cache. As a programmer we no need of doing any settings (configurations) either to enable or disable the first-level cache."
},
{
"code": null,
"e": 1522,
"s": 1242,
"text": "When a program wants an object from the database then hibernate first checks for that object in level1 cache. If that object does not exist in level1 cache then it checks in the second-level cache. If not exist in the second-level cache, then only hibernate goes to the database."
},
{
"code": null,
"e": 1752,
"s": 1522,
"text": "As we were discussed in the top 10 advantages of hibernate, caching in hibernate is the most powerful feature than compared with the other ORM frameworks. Hibernate also gives an excellent API to manage the states of objects too."
},
{
"code": null,
"e": 1913,
"s": 1752,
"text": "As we discussed, when a session is opened then automatically hibernate opens a cache. The life cycle of the cache is completely managed by the hibernate itself."
},
{
"code": null,
"e": 2189,
"s": 1913,
"text": "For each and every session, there will be a separate cache is opened. So level 1 cache is also called a local cache. When we are loading an object, hibernate first checks for that object in the local cache. If not existed then only it goes to the database and load an object."
},
{
"code": null,
"e": 2211,
"s": 2189,
"text": "On the above diagram,"
},
{
"code": null,
"e": 2475,
"s": 2211,
"text": "Step 1 : We are trying to get the Student data from the database by using session.get(Student.class, 101); In this step Hibernate goes to first level cache and checks for the Student. But as this is the first request, Student object is not available in the cache."
},
{
"code": null,
"e": 2548,
"s": 2475,
"text": "Step 2 : In step 2 hibernate goes to Database to get the Student object."
},
{
"code": null,
"e": 2644,
"s": 2548,
"text": "Step 3 : In step 3 hibernate get an object from the database and save that object in the cache."
},
{
"code": null,
"e": 2695,
"s": 2644,
"text": "Step 4 : In step 4 returns that object to program."
},
{
"code": null,
"e": 2951,
"s": 2695,
"text": "After that, whenever the program wants that Student object, hibernate will directly get that object from the cache itself. We can see that in the Step a and Step b. Hence using hibernate cache mechanism the performance of an application will be increased."
},
{
"code": null,
"e": 4613,
"s": 2951,
"text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class DbOperations {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n\n Student student = (Student) session.get(Student.class, 111);\n\n /**\n * At the first time there is no Student Object in first level cache,\n * hence hibernate will go to database and get the Student Object, we\n * can find the select statements in the output.\n *\n */\n System.out.println(\"Student Name : \" + student.getName());\n System.out.println(\"Student Id : \" + student.getId());\n System.out.println(\"Student Roll Number : \" + student.getRollNumber());\n\n System.out.println(\"=================================\");\n\n /**\n * Here we are using the same session object to get the Student Details,\n * that are already existed in the first level cache hence Hibernate\n * will get the details from Session Cache.\n *\n */\n Student student2 = (Student) session.get(Student.class, 111);\n System.out.println(\"Student Name : \" + student2.getName());\n System.out.println(\"Student Id : \" + student2.getId());\n System.out.println(\"Student Roll Number : \" + student2.getRollNumber());\n\n session.close();\n\n }\n}"
},
{
"code": null,
"e": 4622,
"s": 4613,
"text": "Output :"
},
{
"code": null,
"e": 5103,
"s": 4622,
"text": "Oct 09, 2015 11:29:03 PM org.hibernate.envers.boot.internal.EnversServiceImpl configure \nINFO: Envers integration enabled? : true \nHibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Student Name : John Student Id : 111 Student Roll Number : 7\n================================================ \nStudent Name : John Student Id : 111 Student Roll Number : 7"
},
{
"code": null,
"e": 5425,
"s": 5103,
"text": "On the above example, if we observe output carefully to get the Student details for the first time to hibernate went to the database. We can find the database select query in the output. But in the second time the select query not executed, because the Students were taken from hibernate cache (First level cache) itself."
},
{
"code": null,
"e": 5574,
"s": 5425,
"text": "Suppose if want to read an object from the database only, but not from the cache then we can remove that object the cache by calling evict() method."
},
{
"code": null,
"e": 5647,
"s": 5574,
"text": "We can also delete all objects from the cache by calling clear() method."
},
{
"code": null,
"e": 7213,
"s": 5647,
"text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class DbOperations {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n\n Student student = (Student) session.get(Student.class, 111);\n\n System.out.println(\"Student Name : \" + student.getName());\n System.out.println(\"Student Id : \" + student.getId());\n System.out.println(\"Student Roll Number : \" + student.getRollNumber());\n\n System.out.println(\"=================================\");\n\n Student student2 = (Student) session.get(Student.class, 111);\n\n System.out.println(\"Student 2 Name : \" + student2.getName());\n System.out.println(\"Student 2 Id : \" + student2.getId());\n System.out.println(\"Student 2 Roll Number : \" + student2.getRollNumber());\n\n System.out.println(\"=================================\");\n\n session.evict(student);\n Student student3 = (Student) session.get(Student.class, 111);\n\n System.out.println(\"Student 3 Name : \" + student3.getName());\n System.out.println(\"Student 3 Id : \" + student3.getId());\n System.out.println(\"Student 3 Roll Number : \" + student3.getRollNumber());\n\n session.close();\n\n }\n}"
},
{
"code": null,
"e": 7222,
"s": 7213,
"text": "Output :"
},
{
"code": null,
"e": 7888,
"s": 7222,
"text": "INFO: Envers integration enabled? : true \nHibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Student Name : John Student Id : 111 Student Roll Number : 7 \n================================= \nStudent 2 Name : John Student 2 Id : 111 Student 2 Roll Number : 7 \n================================= \nHibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Student 3 Name : John Student 3 Id : 111 Student 3 Roll Number : 7"
},
{
"code": null,
"e": 7993,
"s": 7888,
"text": "When the above program is executed, then two times hibernate goes to the database for loading an object."
},
{
"code": null,
"e": 8108,
"s": 7993,
"text": "when evict() method is called hibernate finds the object, whether it existed in cache or not based on id property."
},
{
"code": null,
"e": 8294,
"s": 8108,
"text": "An only problem with the cache is if an object is updated in database explicitly or by another thread, then the changes are not automatically affected on the object stored in the cache."
},
{
"code": null,
"e": 8401,
"s": 8294,
"text": "It is the developer responsibility to refresh a session at regular intervals by calling session.refresh()."
},
{
"code": null,
"e": 8418,
"s": 8401,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 9026,
"s": 8418,
"text": "\nHibernate session differences between load() and get()\nHibernate Native SQL Query Example\nTop 7 Interview Questions in Hibernate\nHibernate Filter Example Xml Configuration\nTop 10 Advantages of Hibernate\nBasic Hibernate Example with XML Configuration\nHQL update, delete Query Example\nSingleton Hibernate SessionFactory Example\nSpring Boot Hazelcast Cache Example\nWhat is Hibernate\nHibernate 4 Example with Annotations Mysql\nDifferent types of Object States in Hibernate\nDifference between update vs merge in Hibernate example\nhibernate update query example\nTable per Class Strategy in Hibernate Inheritance\n"
},
{
"code": null,
"e": 9081,
"s": 9026,
"text": "Hibernate session differences between load() and get()"
},
{
"code": null,
"e": 9116,
"s": 9081,
"text": "Hibernate Native SQL Query Example"
},
{
"code": null,
"e": 9155,
"s": 9116,
"text": "Top 7 Interview Questions in Hibernate"
},
{
"code": null,
"e": 9198,
"s": 9155,
"text": "Hibernate Filter Example Xml Configuration"
},
{
"code": null,
"e": 9229,
"s": 9198,
"text": "Top 10 Advantages of Hibernate"
},
{
"code": null,
"e": 9276,
"s": 9229,
"text": "Basic Hibernate Example with XML Configuration"
},
{
"code": null,
"e": 9309,
"s": 9276,
"text": "HQL update, delete Query Example"
},
{
"code": null,
"e": 9352,
"s": 9309,
"text": "Singleton Hibernate SessionFactory Example"
},
{
"code": null,
"e": 9388,
"s": 9352,
"text": "Spring Boot Hazelcast Cache Example"
},
{
"code": null,
"e": 9406,
"s": 9388,
"text": "What is Hibernate"
},
{
"code": null,
"e": 9449,
"s": 9406,
"text": "Hibernate 4 Example with Annotations Mysql"
},
{
"code": null,
"e": 9495,
"s": 9449,
"text": "Different types of Object States in Hibernate"
},
{
"code": null,
"e": 9551,
"s": 9495,
"text": "Difference between update vs merge in Hibernate example"
},
{
"code": null,
"e": 9582,
"s": 9551,
"text": "hibernate update query example"
},
{
"code": null,
"e": 9632,
"s": 9582,
"text": "Table per Class Strategy in Hibernate Inheritance"
},
{
"code": null,
"e": 9638,
"s": 9636,
"text": "Δ"
},
{
"code": null,
"e": 9664,
"s": 9638,
"text": " Hibernate – Introduction"
},
{
"code": null,
"e": 9688,
"s": 9664,
"text": " Hibernate – Advantages"
},
{
"code": null,
"e": 9720,
"s": 9688,
"text": " Hibernate – Download and Setup"
},
{
"code": null,
"e": 9750,
"s": 9720,
"text": " Hibernate – Sql Dialect list"
},
{
"code": null,
"e": 9780,
"s": 9750,
"text": " Hibernate – Helloworld – XML"
},
{
"code": null,
"e": 9818,
"s": 9780,
"text": " Hibernate – Install Tools in Eclipse"
},
{
"code": null,
"e": 9845,
"s": 9818,
"text": " Hibernate – Object States"
},
{
"code": null,
"e": 9883,
"s": 9845,
"text": " Hibernate – Helloworld – Annotations"
},
{
"code": null,
"e": 9921,
"s": 9883,
"text": " Hibernate – One to One Mapping – XML"
},
{
"code": null,
"e": 9971,
"s": 9921,
"text": " Hibernate – One to One Mapping foreign key – XML"
},
{
"code": null,
"e": 10001,
"s": 9971,
"text": " Hibernate – One To Many -XML"
},
{
"code": null,
"e": 10040,
"s": 10001,
"text": " Hibernate – One To Many – Annotations"
},
{
"code": null,
"e": 10080,
"s": 10040,
"text": " Hibernate – Many to Many Mapping – XML"
},
{
"code": null,
"e": 10111,
"s": 10080,
"text": " Hibernate – Many to One – XML"
},
{
"code": null,
"e": 10146,
"s": 10111,
"text": " Hibernate – Composite Key Mapping"
},
{
"code": null,
"e": 10171,
"s": 10146,
"text": " Hibernate – Named Query"
},
{
"code": null,
"e": 10201,
"s": 10171,
"text": " Hibernate – Native SQL Query"
},
{
"code": null,
"e": 10230,
"s": 10201,
"text": " Hibernate – load() vs get()"
},
{
"code": null,
"e": 10267,
"s": 10230,
"text": " Hibernate Criteria API with Example"
},
{
"code": null,
"e": 10293,
"s": 10267,
"text": " Hibernate – Restrictions"
},
{
"code": null,
"e": 10317,
"s": 10293,
"text": " Hibernate – Projection"
},
{
"code": null,
"e": 10351,
"s": 10317,
"text": " Hibernate – Query Language (HQL)"
},
{
"code": null,
"e": 10385,
"s": 10351,
"text": " Hibernate – Groupby Criteria HQL"
},
{
"code": null,
"e": 10415,
"s": 10385,
"text": " Hibernate – Orderby Criteria"
},
{
"code": null,
"e": 10448,
"s": 10415,
"text": " Hibernate – HQLSelect Operation"
},
{
"code": null,
"e": 10480,
"s": 10448,
"text": " Hibernate – HQL Update, Delete"
},
{
"code": null,
"e": 10506,
"s": 10480,
"text": " Hibernate – Update Query"
},
{
"code": null,
"e": 10535,
"s": 10506,
"text": " Hibernate – Update vs Merge"
},
{
"code": null,
"e": 10559,
"s": 10535,
"text": " Hibernate – Right Join"
},
{
"code": null,
"e": 10582,
"s": 10559,
"text": " Hibernate – Left Join"
},
{
"code": null,
"e": 10606,
"s": 10582,
"text": " Hibernate – Pagination"
},
{
"code": null,
"e": 10637,
"s": 10606,
"text": " Hibernate – Generator Classes"
},
{
"code": null,
"e": 10667,
"s": 10637,
"text": " Hibernate – Custom Generator"
},
{
"code": null,
"e": 10701,
"s": 10667,
"text": " Hibernate – Inheritance Mappings"
},
{
"code": null,
"e": 10730,
"s": 10701,
"text": " Hibernate – Table per Class"
},
{
"code": null,
"e": 10763,
"s": 10730,
"text": " Hibernate – Table per Sub Class"
},
{
"code": null,
"e": 10801,
"s": 10763,
"text": " Hibernate – Table per Concrete Class"
},
{
"code": null,
"e": 10843,
"s": 10801,
"text": " Hibernate – Table per Class Annotations"
},
{
"code": null,
"e": 10874,
"s": 10843,
"text": " Hibernate – Stored Procedures"
},
{
"code": null,
"e": 10907,
"s": 10874,
"text": " Hibernate – @Formula Annotation"
},
{
"code": null,
"e": 10945,
"s": 10907,
"text": " Hibernate – Singleton SessionFactory"
},
{
"code": null,
"e": 10970,
"s": 10945,
"text": " Hibernate – Interceptor"
},
{
"code": null,
"e": 11016,
"s": 10970,
"text": " hbm2ddl.auto Example in Hibernate XML Config"
}
] |
Cypress - Configuration of JSON File
|
Cypress configurations consist of some key-value pairs that are applicable to all tests within a framework. Cypress default configurations are available under the Settings tab->Configuration (expand it) in the Test Runner window.
If we look further down in the same window, we shall have the existing values of multiple configurations given by Cypress like the timeouts, environment variables, folder path, and so on.
It is displayed below −
If we look further down in the same window, we shall have the existing values of multiple configurations given by Cypress like the timeouts, environment variables, folder path, and so on.
It is displayed below −
To override the default configurations from the cypress.json file, we have to specify the key-value pairs.
The implementation for overriding the default values for JSON file is as follows −
{
"baseUrl" : "https://www.google.com/"
}
Here, the key is baseUrl and the value is https://www.google.com/. Once the tests are
run again, the changes are reflected in the global configurations, as shown below −
The implementation of actual test for overriding default values of the JSON file is as follows −
describe('Tutorialspoint', function () {
// test case
it('First Test', function (){
// launch application from configuration
cy.visit("/")
});
});
Execution Results
The output is as follows −
The execution logs show that the baseUrl has been obtained from the cypress.json file and it is applicable to all tests within the framework.
We can override the default configurations from the test scripts, which become applicable to an individual test step, within the test case and not to the complete framework.
This is done with the help of the config command in Cypress.
For example, if we want to increase the default timeout for a particular test step, implementation shall be as follows −
//set default time out to nine seconds from following steps in test
Cypress.config('defaultCommandTimeout',9000)
landPage.selectUser().click()
Simultaneously if the defaultCommandTimeout value is set to seven seconds in the cypress.json file, then Cypress shall give preference to the timeout applied to the test step(i.e nine seconds).
Finally, it gives preference to the default configurations.
We can disable the feature to override the default configurations from the cypress.json.
The configuration in cypress.json is as follows −
{
"defaultCommandTimeout" : "9000"
}
To disable the above configuration, run the below mentioned command −
npx cypress open --config-file false
After running the above command, the Settings tab of the Test Runner window will show the config flag set to false.
Also, defaultCommandTimeout is set to four seconds, which is set by the default configuration and not overridden by cypress.json value of nine seconds.
73 Lectures
12 hours
Rahul Shetty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2727,
"s": 2497,
"text": "Cypress configurations consist of some key-value pairs that are applicable to all tests within a framework. Cypress default configurations are available under the Settings tab->Configuration (expand it) in the Test Runner window."
},
{
"code": null,
"e": 2915,
"s": 2727,
"text": "If we look further down in the same window, we shall have the existing values of multiple configurations given by Cypress like the timeouts, environment variables, folder path, and so on."
},
{
"code": null,
"e": 2939,
"s": 2915,
"text": "It is displayed below −"
},
{
"code": null,
"e": 3127,
"s": 2939,
"text": "If we look further down in the same window, we shall have the existing values of multiple configurations given by Cypress like the timeouts, environment variables, folder path, and so on."
},
{
"code": null,
"e": 3151,
"s": 3127,
"text": "It is displayed below −"
},
{
"code": null,
"e": 3258,
"s": 3151,
"text": "To override the default configurations from the cypress.json file, we have to specify the key-value pairs."
},
{
"code": null,
"e": 3341,
"s": 3258,
"text": "The implementation for overriding the default values for JSON file is as follows −"
},
{
"code": null,
"e": 3386,
"s": 3341,
"text": "{\n \"baseUrl\" : \"https://www.google.com/\"\n}"
},
{
"code": null,
"e": 3556,
"s": 3386,
"text": "Here, the key is baseUrl and the value is https://www.google.com/. Once the tests are\nrun again, the changes are reflected in the global configurations, as shown below −"
},
{
"code": null,
"e": 3653,
"s": 3556,
"text": "The implementation of actual test for overriding default values of the JSON file is as follows −"
},
{
"code": null,
"e": 3818,
"s": 3653,
"text": "describe('Tutorialspoint', function () {\n// test case\n it('First Test', function (){\n // launch application from configuration\n cy.visit(\"/\")\n });\n});"
},
{
"code": null,
"e": 3836,
"s": 3818,
"text": "Execution Results"
},
{
"code": null,
"e": 3863,
"s": 3836,
"text": "The output is as follows −"
},
{
"code": null,
"e": 4005,
"s": 3863,
"text": "The execution logs show that the baseUrl has been obtained from the cypress.json file and it is applicable to all tests within the framework."
},
{
"code": null,
"e": 4179,
"s": 4005,
"text": "We can override the default configurations from the test scripts, which become applicable to an individual test step, within the test case and not to the complete framework."
},
{
"code": null,
"e": 4240,
"s": 4179,
"text": "This is done with the help of the config command in Cypress."
},
{
"code": null,
"e": 4361,
"s": 4240,
"text": "For example, if we want to increase the default timeout for a particular test step, implementation shall be as follows −"
},
{
"code": null,
"e": 4505,
"s": 4361,
"text": "//set default time out to nine seconds from following steps in test\nCypress.config('defaultCommandTimeout',9000)\nlandPage.selectUser().click()\n"
},
{
"code": null,
"e": 4699,
"s": 4505,
"text": "Simultaneously if the defaultCommandTimeout value is set to seven seconds in the cypress.json file, then Cypress shall give preference to the timeout applied to the test step(i.e nine seconds)."
},
{
"code": null,
"e": 4759,
"s": 4699,
"text": "Finally, it gives preference to the default configurations."
},
{
"code": null,
"e": 4848,
"s": 4759,
"text": "We can disable the feature to override the default configurations from the cypress.json."
},
{
"code": null,
"e": 4898,
"s": 4848,
"text": "The configuration in cypress.json is as follows −"
},
{
"code": null,
"e": 4939,
"s": 4898,
"text": "{\n \"defaultCommandTimeout\" : \"9000\"\n}\n"
},
{
"code": null,
"e": 5009,
"s": 4939,
"text": "To disable the above configuration, run the below mentioned command −"
},
{
"code": null,
"e": 5047,
"s": 5009,
"text": "npx cypress open --config-file false\n"
},
{
"code": null,
"e": 5163,
"s": 5047,
"text": "After running the above command, the Settings tab of the Test Runner window will show the config flag set to false."
},
{
"code": null,
"e": 5315,
"s": 5163,
"text": "Also, defaultCommandTimeout is set to four seconds, which is set by the default configuration and not overridden by cypress.json value of nine seconds."
},
{
"code": null,
"e": 5349,
"s": 5315,
"text": "\n 73 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 5363,
"s": 5349,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 5370,
"s": 5363,
"text": " Print"
},
{
"code": null,
"e": 5381,
"s": 5370,
"text": " Add Notes"
}
] |
How To Evaluate Unsupervised Learning Models | by Callum Ballard | Towards Data Science
|
So far in this blog series, we have looked at how to create automated playlists of songs by clustering a collection of tracks, based purely on their audio features. Previously, we worked on a toy example of 32 songs and showed how Hierarchical Agglomerative Clustering (HAC) can automatically create sub-groups of similar songs. We were able to verify the results of this clustering exercise through our existing knowledge of the songs (our algorithm confirmed that Motörhead and Black Sabbath are musically similar — go figure).
But what if we don’t have such prior knowledge of our data? What if the data isn’t even labelled (as is the case in many real-life clustering cases)? Even if it is, what if these labels are initially meaningless to us? There are plenty of artists that I’ve never even heard of, and if we’re trying to group thousands of tracks then it’s clearly impractical to manually verify every cluster. In these cases, we need some kind of mathematical measure for how ‘successful’ our clustering has been.
To explore how we might go about doing this, we once again turn to Spotify’s API. Suppose we take the songs from four very different playlists:
Rap UK
Smooth Jazz
Classical Essentials
Essential K-Pop
If we merge these into a single dataset, an unsupervised machine learning algorithm ought to be able to group their songs into four clusters that somewhat resemble the original four playlists.
Before we get started, we may indeed want to check our assumption that songs from these diverse playlists are indeed ‘different’. Of course, visualising more than two features simultaneously on a single chart is challenging. However, if we plot a scatter matrix of all features, colour-coded by playlist, we can see that there are plenty of metric combinations that demonstrate the distinct characteristics of each genre.
We saw in the previous blog that running a clustering algorithm in Scikit-Learn is very simple:
#We scale the data to ensure that#feature units don't impact distancesfrom sklearn.preprocessing import StandardScalersclaer = StandardScaler()X_scaled = scaler.fit_transform(X)#This scaled data can then be fed into the HAC algorithmfrom sklearn.cluster import AgglomerativeClustering#We can tell it how many clusters we're aiming foragg_clust = AgglomerativeClustering(n_clusters=4)assigned_clusters = agg_clust.fit_predict(X_scaled)
We also saw that HAC has three different ‘linkage criteria’ — the method by which the algorithm iteravely joins clusters together:
ward (default): picks the two clusters to merge in a way that the variance within all clusters increases the least. Generally, this leads to clusters that are fairly equally sized.
complete (or maximum linkage): merges the two clusters that have the smallest maximum distance between their points.
average: merges the two clusters that have the smallest average distance between all the points.
Let’s see how these three linkage criteria deal with the genre playlist dataset. We represent our results in a matrix, showing what percentage of each playlist’s songs have ended up in each cluster (the clusters have been named, arbitrarily, ‘A’, ‘B’, ‘C’, and ‘D’).
Of course, if the clustering had been pefect, we’d expect each row and each column of the matrix to contain exactly one entry of 100% (it needn’t be in a diagonal, of course, since the cluster name assignment is arbitrary).
It’s worth mentioning that there is another common type of clustering, K-Means, which works slightly differently. Whereas HAC iteratively decreases the number of clusters by merging them together, K-Means clustering maintains a fixed number of clusters (the titular k), but iteratively changes the members of each cluster.
K-Means is simple to implement in Python:
#We scale the data to ensure that#feature units don't impact distancesfrom sklearn.preprocessing import StandardScalersclaer = StandardScaler()X_scaled = scaler.fit_transform(X)#This scaled data can then be fed into the K-Means alorithmfrom sklearn.cluster import KMeans#We can tell it how many clusters we're aiming forkm_clust = KMeans(n_clusters=4)assigned_clusters = km_clust.fit_predict(X_scaled)
If we apply K-Means clustering to the playlist dataset, we get the following:
While these matrices are good for ‘eyeballing’ our results, they’re far from mathematically rigorous. Let’s consider some metrics to actually help us assign a number to our cluster quality.
The Adjusted Rand Index is a variation on the classic Rand Index, and attempts to express what proportion of the cluster assignments are ‘correct’. It computes a similarity measure between two different clusterings by considering all pairs of samples, and counting pairs that are assigned in the same or different clusters predicted, against the true clusterings, adjusting for random chance.
This (as well as the other metrics we’ll consider) can be evaluated using Scikit-Learn.
from sklearn import metricsmetrics.adjusted_rand_score(predicted_labels, actual)
The Adjusted Rand index is bounded between -1 and 1. Closer to 1 is good, while closer to -1 is bad.
We see that K-Means and Ward Linkage have a high score. We’d expect this, based on the matrices we previously observed.
The Fowlkes Mallow Score is similar, in as much that it tells you the degree to which cluster assignments are ‘correct’. In particular, it calculates the geometric mean between precision and recall. It’s bounded between 0 and 1, with higher values being better.
metrics.fowlkes_mallows_score(predicted_labels, actual)
We similar rankings to the Adjusted Rand Index — which we would expect, given that they’re two methods of trying to answer the same question.
It’s worth noting that we needed to know the original labels in order to compute these metrics. Given that dealing with unlabelled data is one of the main use cases of unsupervised learning, we require some other metrics that evaluate clustering results without needing to refer to ‘true’ labels.
Suppose we have the following results from three separate clustering analyses.
Evidently, the ‘tighter’ we can make our clusters, the better. Is there some way to ascribe a number to this idea of ‘tightness’?
The Silhouette Score attempts to describe how similar a datapoint is to other datapoints in its cluster, relative to datapoints not in its cluster (this is aggregated over all datapoints to get the score for an overall clustering). In other words, it thinks about how ‘distinct’ the clusters are in space — indeed one could use any measure of ‘distance’ to calculate the score.
It is bounded between -1 and 1. Closer to -1 suggests incorrect clustering, while closer to +1 shows that each cluster is very dense.
metrics.silhouette_score(scaled_feature_data, cluster_labels)
We see that none of the clusters have super-high Silhouette Scores. Interestingly, we see that the Average Linkage clusters have the highest scores. Remember, however, that this algorithm produced two clusters that each contained just a single datapoint, which is unlikely to be a desirable outcome in a real-world situation (a lesson that you often can’t rely on a single metric to make decisions about the quality of an algorithm!)
The Calinski Harabaz Index is the ratio of the variance of a datapoint compared to points in other clusters, against the variance compared to points within its cluster. Since we want this first part to be high, and the second part to be low, a high CH index is desirable. Unlike other metrics we have seen, this score is not bounded.
metrics.calinski_harabasz_score(scaled_feature_data, cluster_labels)
Here we see that our K-Means and Ward Linkage algorithms score highly. The Complete and Average linkage algorithms are punished for having one or two large clusters, which will have a higher level of intra-variance.
This is the latest blog in my ‘Music By Numbers’ column, which uses data to tell stories about music. I’d love to hear any comments about the above analysis — feel free to leave a message below, or reach out to me through LinkedIn!
|
[
{
"code": null,
"e": 703,
"s": 172,
"text": "So far in this blog series, we have looked at how to create automated playlists of songs by clustering a collection of tracks, based purely on their audio features. Previously, we worked on a toy example of 32 songs and showed how Hierarchical Agglomerative Clustering (HAC) can automatically create sub-groups of similar songs. We were able to verify the results of this clustering exercise through our existing knowledge of the songs (our algorithm confirmed that Motörhead and Black Sabbath are musically similar — go figure)."
},
{
"code": null,
"e": 1198,
"s": 703,
"text": "But what if we don’t have such prior knowledge of our data? What if the data isn’t even labelled (as is the case in many real-life clustering cases)? Even if it is, what if these labels are initially meaningless to us? There are plenty of artists that I’ve never even heard of, and if we’re trying to group thousands of tracks then it’s clearly impractical to manually verify every cluster. In these cases, we need some kind of mathematical measure for how ‘successful’ our clustering has been."
},
{
"code": null,
"e": 1342,
"s": 1198,
"text": "To explore how we might go about doing this, we once again turn to Spotify’s API. Suppose we take the songs from four very different playlists:"
},
{
"code": null,
"e": 1349,
"s": 1342,
"text": "Rap UK"
},
{
"code": null,
"e": 1361,
"s": 1349,
"text": "Smooth Jazz"
},
{
"code": null,
"e": 1382,
"s": 1361,
"text": "Classical Essentials"
},
{
"code": null,
"e": 1398,
"s": 1382,
"text": "Essential K-Pop"
},
{
"code": null,
"e": 1591,
"s": 1398,
"text": "If we merge these into a single dataset, an unsupervised machine learning algorithm ought to be able to group their songs into four clusters that somewhat resemble the original four playlists."
},
{
"code": null,
"e": 2013,
"s": 1591,
"text": "Before we get started, we may indeed want to check our assumption that songs from these diverse playlists are indeed ‘different’. Of course, visualising more than two features simultaneously on a single chart is challenging. However, if we plot a scatter matrix of all features, colour-coded by playlist, we can see that there are plenty of metric combinations that demonstrate the distinct characteristics of each genre."
},
{
"code": null,
"e": 2109,
"s": 2013,
"text": "We saw in the previous blog that running a clustering algorithm in Scikit-Learn is very simple:"
},
{
"code": null,
"e": 2544,
"s": 2109,
"text": "#We scale the data to ensure that#feature units don't impact distancesfrom sklearn.preprocessing import StandardScalersclaer = StandardScaler()X_scaled = scaler.fit_transform(X)#This scaled data can then be fed into the HAC algorithmfrom sklearn.cluster import AgglomerativeClustering#We can tell it how many clusters we're aiming foragg_clust = AgglomerativeClustering(n_clusters=4)assigned_clusters = agg_clust.fit_predict(X_scaled)"
},
{
"code": null,
"e": 2675,
"s": 2544,
"text": "We also saw that HAC has three different ‘linkage criteria’ — the method by which the algorithm iteravely joins clusters together:"
},
{
"code": null,
"e": 2856,
"s": 2675,
"text": "ward (default): picks the two clusters to merge in a way that the variance within all clusters increases the least. Generally, this leads to clusters that are fairly equally sized."
},
{
"code": null,
"e": 2973,
"s": 2856,
"text": "complete (or maximum linkage): merges the two clusters that have the smallest maximum distance between their points."
},
{
"code": null,
"e": 3070,
"s": 2973,
"text": "average: merges the two clusters that have the smallest average distance between all the points."
},
{
"code": null,
"e": 3337,
"s": 3070,
"text": "Let’s see how these three linkage criteria deal with the genre playlist dataset. We represent our results in a matrix, showing what percentage of each playlist’s songs have ended up in each cluster (the clusters have been named, arbitrarily, ‘A’, ‘B’, ‘C’, and ‘D’)."
},
{
"code": null,
"e": 3561,
"s": 3337,
"text": "Of course, if the clustering had been pefect, we’d expect each row and each column of the matrix to contain exactly one entry of 100% (it needn’t be in a diagonal, of course, since the cluster name assignment is arbitrary)."
},
{
"code": null,
"e": 3884,
"s": 3561,
"text": "It’s worth mentioning that there is another common type of clustering, K-Means, which works slightly differently. Whereas HAC iteratively decreases the number of clusters by merging them together, K-Means clustering maintains a fixed number of clusters (the titular k), but iteratively changes the members of each cluster."
},
{
"code": null,
"e": 3926,
"s": 3884,
"text": "K-Means is simple to implement in Python:"
},
{
"code": null,
"e": 4328,
"s": 3926,
"text": "#We scale the data to ensure that#feature units don't impact distancesfrom sklearn.preprocessing import StandardScalersclaer = StandardScaler()X_scaled = scaler.fit_transform(X)#This scaled data can then be fed into the K-Means alorithmfrom sklearn.cluster import KMeans#We can tell it how many clusters we're aiming forkm_clust = KMeans(n_clusters=4)assigned_clusters = km_clust.fit_predict(X_scaled)"
},
{
"code": null,
"e": 4406,
"s": 4328,
"text": "If we apply K-Means clustering to the playlist dataset, we get the following:"
},
{
"code": null,
"e": 4596,
"s": 4406,
"text": "While these matrices are good for ‘eyeballing’ our results, they’re far from mathematically rigorous. Let’s consider some metrics to actually help us assign a number to our cluster quality."
},
{
"code": null,
"e": 4989,
"s": 4596,
"text": "The Adjusted Rand Index is a variation on the classic Rand Index, and attempts to express what proportion of the cluster assignments are ‘correct’. It computes a similarity measure between two different clusterings by considering all pairs of samples, and counting pairs that are assigned in the same or different clusters predicted, against the true clusterings, adjusting for random chance."
},
{
"code": null,
"e": 5077,
"s": 4989,
"text": "This (as well as the other metrics we’ll consider) can be evaluated using Scikit-Learn."
},
{
"code": null,
"e": 5158,
"s": 5077,
"text": "from sklearn import metricsmetrics.adjusted_rand_score(predicted_labels, actual)"
},
{
"code": null,
"e": 5259,
"s": 5158,
"text": "The Adjusted Rand index is bounded between -1 and 1. Closer to 1 is good, while closer to -1 is bad."
},
{
"code": null,
"e": 5379,
"s": 5259,
"text": "We see that K-Means and Ward Linkage have a high score. We’d expect this, based on the matrices we previously observed."
},
{
"code": null,
"e": 5641,
"s": 5379,
"text": "The Fowlkes Mallow Score is similar, in as much that it tells you the degree to which cluster assignments are ‘correct’. In particular, it calculates the geometric mean between precision and recall. It’s bounded between 0 and 1, with higher values being better."
},
{
"code": null,
"e": 5697,
"s": 5641,
"text": "metrics.fowlkes_mallows_score(predicted_labels, actual)"
},
{
"code": null,
"e": 5839,
"s": 5697,
"text": "We similar rankings to the Adjusted Rand Index — which we would expect, given that they’re two methods of trying to answer the same question."
},
{
"code": null,
"e": 6136,
"s": 5839,
"text": "It’s worth noting that we needed to know the original labels in order to compute these metrics. Given that dealing with unlabelled data is one of the main use cases of unsupervised learning, we require some other metrics that evaluate clustering results without needing to refer to ‘true’ labels."
},
{
"code": null,
"e": 6215,
"s": 6136,
"text": "Suppose we have the following results from three separate clustering analyses."
},
{
"code": null,
"e": 6345,
"s": 6215,
"text": "Evidently, the ‘tighter’ we can make our clusters, the better. Is there some way to ascribe a number to this idea of ‘tightness’?"
},
{
"code": null,
"e": 6723,
"s": 6345,
"text": "The Silhouette Score attempts to describe how similar a datapoint is to other datapoints in its cluster, relative to datapoints not in its cluster (this is aggregated over all datapoints to get the score for an overall clustering). In other words, it thinks about how ‘distinct’ the clusters are in space — indeed one could use any measure of ‘distance’ to calculate the score."
},
{
"code": null,
"e": 6857,
"s": 6723,
"text": "It is bounded between -1 and 1. Closer to -1 suggests incorrect clustering, while closer to +1 shows that each cluster is very dense."
},
{
"code": null,
"e": 6919,
"s": 6857,
"text": "metrics.silhouette_score(scaled_feature_data, cluster_labels)"
},
{
"code": null,
"e": 7353,
"s": 6919,
"text": "We see that none of the clusters have super-high Silhouette Scores. Interestingly, we see that the Average Linkage clusters have the highest scores. Remember, however, that this algorithm produced two clusters that each contained just a single datapoint, which is unlikely to be a desirable outcome in a real-world situation (a lesson that you often can’t rely on a single metric to make decisions about the quality of an algorithm!)"
},
{
"code": null,
"e": 7687,
"s": 7353,
"text": "The Calinski Harabaz Index is the ratio of the variance of a datapoint compared to points in other clusters, against the variance compared to points within its cluster. Since we want this first part to be high, and the second part to be low, a high CH index is desirable. Unlike other metrics we have seen, this score is not bounded."
},
{
"code": null,
"e": 7756,
"s": 7687,
"text": "metrics.calinski_harabasz_score(scaled_feature_data, cluster_labels)"
},
{
"code": null,
"e": 7972,
"s": 7756,
"text": "Here we see that our K-Means and Ward Linkage algorithms score highly. The Complete and Average linkage algorithms are punished for having one or two large clusters, which will have a higher level of intra-variance."
}
] |
Tryit Editor v3.6 - Show Node.js Command Prompt
|
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myusername",
password: "mypassword"
});
con.connect(function(err) {
if (err) throw err;
|
[
{
"code": null,
"e": 30,
"s": 0,
"text": "var mysql = require('mysql');"
},
{
"code": null,
"e": 32,
"s": 30,
"text": ""
},
{
"code": null,
"e": 67,
"s": 32,
"text": "var con = mysql.createConnection({"
},
{
"code": null,
"e": 88,
"s": 67,
"text": " host: \"localhost\","
},
{
"code": null,
"e": 110,
"s": 88,
"text": " user: \"myusername\","
},
{
"code": null,
"e": 135,
"s": 110,
"text": " password: \"mypassword\""
},
{
"code": null,
"e": 139,
"s": 135,
"text": "});"
},
{
"code": null,
"e": 141,
"s": 139,
"text": ""
},
{
"code": null,
"e": 169,
"s": 141,
"text": "con.connect(function(err) {"
}
] |
ReactJS - Event management
|
Event management is one of the important features in a web application. It enables the user to interact with the application. React support all events available in a web application. React event handling is very similar to DOM events with little changes. Let us learn how to handle events in a React application in this chapter.
Let us see the step-by-step process of handling an event in a React component.
Define an event handler method to handle the given event.
Define an event handler method to handle the given event.
log() {
cosole.log("Event is fired");
}
React provides an alternative syntax using lambda function to define event handler. The lambda syntax is −
log = () => {
cosole.log("Event is fired");
}
If you want to know the target of the event, then add an argument e in the handler method. React will send the event target details to the handler method.
log(e) {
cosole.log("Event is fired");
console.log(e.target);
}
The alternative lambda syntax is −
log = (e) => {
cosole.log("Event is fired");
console.log(e.target);
}
If you want to send extra details during an event, then add the extra details as initial argument and then add argument (e) for event target.
log(extra, e) {
cosole.log("Event is fired");
console.log(e.target);
console.log(extra);
console.log(this);
}
The alternative lambda syntax is as follows −
log = (extra, e) => {
cosole.log("Event is fired");
console.log(e.target);
console.log(extra);
console.log(this);
}
Bind the event handler method in the constructor of the component. This will ensure the availability of this in the event handler method.
constructor(props) {
super(props);
this.logContent = this.logContent.bind(this);
}
If the event handler is defined in alternate lambda syntax, then the binding is not needed. this keyword will be automatically bound to the event handler method.
Set the event handler method for the specific event as specified below −
<div onClick={this.log}> ... </div>
To set extra arguments, bind the event handler method and then pass the extra information as second argument.
<div onClick={this.log.bind(this, extra)}> ... </div>
The alternate lambda syntax is as follows −
<div onClick={this.log(extra, e)}> ... </div>
Here,
Create a event-aware component
Create a event-aware component
Introduce events in Expense manager app
Introduce events in Expense manager app
|
[
{
"code": null,
"e": 2496,
"s": 2167,
"text": "Event management is one of the important features in a web application. It enables the user to interact with the application. React support all events available in a web application. React event handling is very similar to DOM events with little changes. Let us learn how to handle events in a React application in this chapter."
},
{
"code": null,
"e": 2575,
"s": 2496,
"text": "Let us see the step-by-step process of handling an event in a React component."
},
{
"code": null,
"e": 2633,
"s": 2575,
"text": "Define an event handler method to handle the given event."
},
{
"code": null,
"e": 2691,
"s": 2633,
"text": "Define an event handler method to handle the given event."
},
{
"code": null,
"e": 2736,
"s": 2691,
"text": "log() { \n cosole.log(\"Event is fired\"); \n}"
},
{
"code": null,
"e": 2843,
"s": 2736,
"text": "React provides an alternative syntax using lambda function to define event handler. The lambda syntax is −"
},
{
"code": null,
"e": 2894,
"s": 2843,
"text": "log = () => { \n cosole.log(\"Event is fired\"); \n}"
},
{
"code": null,
"e": 3049,
"s": 2894,
"text": "If you want to know the target of the event, then add an argument e in the handler method. React will send the event target details to the handler method."
},
{
"code": null,
"e": 3122,
"s": 3049,
"text": "log(e) { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n}"
},
{
"code": null,
"e": 3157,
"s": 3122,
"text": "The alternative lambda syntax is −"
},
{
"code": null,
"e": 3236,
"s": 3157,
"text": "log = (e) => { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n}"
},
{
"code": null,
"e": 3378,
"s": 3236,
"text": "If you want to send extra details during an event, then add the extra details as initial argument and then add argument (e) for event target."
},
{
"code": null,
"e": 3505,
"s": 3378,
"text": "log(extra, e) { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n console.log(extra); \n console.log(this); \n}"
},
{
"code": null,
"e": 3551,
"s": 3505,
"text": "The alternative lambda syntax is as follows −"
},
{
"code": null,
"e": 3684,
"s": 3551,
"text": "log = (extra, e) => { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n console.log(extra); \n console.log(this); \n}"
},
{
"code": null,
"e": 3822,
"s": 3684,
"text": "Bind the event handler method in the constructor of the component. This will ensure the availability of this in the event handler method."
},
{
"code": null,
"e": 3914,
"s": 3822,
"text": "constructor(props) { \n super(props); \n this.logContent = this.logContent.bind(this); \n}"
},
{
"code": null,
"e": 4076,
"s": 3914,
"text": "If the event handler is defined in alternate lambda syntax, then the binding is not needed. this keyword will be automatically bound to the event handler method."
},
{
"code": null,
"e": 4149,
"s": 4076,
"text": "Set the event handler method for the specific event as specified below −"
},
{
"code": null,
"e": 4186,
"s": 4149,
"text": "<div onClick={this.log}> ... </div>\n"
},
{
"code": null,
"e": 4296,
"s": 4186,
"text": "To set extra arguments, bind the event handler method and then pass the extra information as second argument."
},
{
"code": null,
"e": 4351,
"s": 4296,
"text": "<div onClick={this.log.bind(this, extra)}> ... </div>\n"
},
{
"code": null,
"e": 4395,
"s": 4351,
"text": "The alternate lambda syntax is as follows −"
},
{
"code": null,
"e": 4442,
"s": 4395,
"text": "<div onClick={this.log(extra, e)}> ... </div>\n"
},
{
"code": null,
"e": 4448,
"s": 4442,
"text": "Here,"
},
{
"code": null,
"e": 4479,
"s": 4448,
"text": "Create a event-aware component"
},
{
"code": null,
"e": 4510,
"s": 4479,
"text": "Create a event-aware component"
},
{
"code": null,
"e": 4550,
"s": 4510,
"text": "Introduce events in Expense manager app"
}
] |
Wildcards in Java
|
25 Feb, 2022
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type. Unlike arrays, different instantiations of a generic type are not compatible with each other, not even explicitly. This incompatibility may be softened by the wildcard if ? is used as an actual type parameter.
These wildcards can be used when you want to relax the restrictions on a variable. For example, say you want to write a method that works on List < Integer >, List < Double >, and List < Number >, you can do this using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?’), followed by the extends keyword, followed by its upper bound.
public static void add(List<? extends Number> list)
Implementation:
Java
// Java program to demonstrate Upper Bounded Wildcards import java.util.Arrays;import java.util.List; class WildcardDemo { public static void main(String[] args) { // Upper Bounded Integer List List<Integer> list1 = Arrays.asList(4, 5, 6, 7); // printing the sum of elements in list System.out.println("Total sum is:" + sum(list1)); // Double list List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1); // printing the sum of elements in list System.out.print("Total sum is:" + sum(list2)); } private static double sum(List<? extends Number> list) { double sum = 0.0; for (Number i : list) { sum += i.doubleValue(); } return sum; }}
Total sum is:22.0
Total sum is:15.299999999999999
Explanation:
In the above program, list1 and list2 are objects of the List class. list1 is a collection of Integer and list2 is a collection of Double. Both of them are being passed to method sum which has a wildcard that extends Number. This means that list being passed can be of any field or subclass of that field. Here, Integer and Double are subclasses of class Number.
It is expressed using the wildcard character (‘?’), followed by the super keyword, followed by its lower bound: <? super A>.
Syntax: Collectiontype <? super A>
Implementation:
Java
// Java program to demonstrate Lower Bounded Wildcards import java.util.Arrays;import java.util.List; class WildcardDemo { public static void main(String[] args) { // Lower Bounded Integer List List<Integer> list1 = Arrays.asList(4, 5, 6, 7); // Integer list object is being passed printOnlyIntegerClassorSuperClass(list1); // Number list List<Number> list2 = Arrays.asList(4, 5, 6, 7); // Integer list object is being passed printOnlyIntegerClassorSuperClass(list2); } public static void printOnlyIntegerClassorSuperClass( List<? super Integer> list) { System.out.println(list); }}
[4, 5, 6, 7]
[4, 5, 6, 7]
Explanation:
Here arguments can be Integer or superclass of Integer(which is Number). The method printOnlyIntegerClassorSuperClass will only take Integer or its superclass objects. However, if we pass a list of types Double then we will get a compilation error. It is because only the Integer field or its superclass can be passed. Double is not the superclass of Integer.
Note: Use extend wildcard when you want to get values out of a structure and super wildcard when you put values in a structure. Don’t use wildcard when you get and put values in a structure. You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.
This wildcard type is specified using the wildcard character (?), for example, List. This is called a list of unknown types. These are useful in the following cases –
When writing a method that can be employed using functionality provided in Object class.
When the code is using methods in the generic class that doesn’t depend on the type parameter
Implementation:
Java
// Java program to demonstrate Unbounded wildcard import java.util.Arrays;import java.util.List; class unboundedwildcardemo { public static void main(String[] args) { // Integer List List<Integer> list1 = Arrays.asList(1, 2, 3); // Double list List<Double> list2 = Arrays.asList(1.1, 2.2, 3.3); printlist(list1); printlist(list2); } private static void printlist(List<?> list) { System.out.println(list); }}
[1, 2, 3]
[1.1, 2.2, 3.3]
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
krrishh
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 503,
"s": 52,
"text": "The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type. Unlike arrays, different instantiations of a generic type are not compatible with each other, not even explicitly. This incompatibility may be softened by the wildcard if ? is used as an actual type parameter."
},
{
"code": null,
"e": 750,
"s": 503,
"text": "These wildcards can be used when you want to relax the restrictions on a variable. For example, say you want to write a method that works on List < Integer >, List < Double >, and List < Number >, you can do this using an upper bounded wildcard. "
},
{
"code": null,
"e": 885,
"s": 750,
"text": "To declare an upper-bounded wildcard, use the wildcard character (‘?’), followed by the extends keyword, followed by its upper bound. "
},
{
"code": null,
"e": 937,
"s": 885,
"text": "public static void add(List<? extends Number> list)"
},
{
"code": null,
"e": 953,
"s": 937,
"text": "Implementation:"
},
{
"code": null,
"e": 958,
"s": 953,
"text": "Java"
},
{
"code": "// Java program to demonstrate Upper Bounded Wildcards import java.util.Arrays;import java.util.List; class WildcardDemo { public static void main(String[] args) { // Upper Bounded Integer List List<Integer> list1 = Arrays.asList(4, 5, 6, 7); // printing the sum of elements in list System.out.println(\"Total sum is:\" + sum(list1)); // Double list List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1); // printing the sum of elements in list System.out.print(\"Total sum is:\" + sum(list2)); } private static double sum(List<? extends Number> list) { double sum = 0.0; for (Number i : list) { sum += i.doubleValue(); } return sum; }}",
"e": 1706,
"s": 958,
"text": null
},
{
"code": null,
"e": 1756,
"s": 1706,
"text": "Total sum is:22.0\nTotal sum is:15.299999999999999"
},
{
"code": null,
"e": 1769,
"s": 1756,
"text": "Explanation:"
},
{
"code": null,
"e": 2132,
"s": 1769,
"text": "In the above program, list1 and list2 are objects of the List class. list1 is a collection of Integer and list2 is a collection of Double. Both of them are being passed to method sum which has a wildcard that extends Number. This means that list being passed can be of any field or subclass of that field. Here, Integer and Double are subclasses of class Number."
},
{
"code": null,
"e": 2258,
"s": 2132,
"text": "It is expressed using the wildcard character (‘?’), followed by the super keyword, followed by its lower bound: <? super A>. "
},
{
"code": null,
"e": 2294,
"s": 2258,
"text": " Syntax: Collectiontype <? super A>"
},
{
"code": null,
"e": 2311,
"s": 2294,
"text": "Implementation: "
},
{
"code": null,
"e": 2316,
"s": 2311,
"text": "Java"
},
{
"code": "// Java program to demonstrate Lower Bounded Wildcards import java.util.Arrays;import java.util.List; class WildcardDemo { public static void main(String[] args) { // Lower Bounded Integer List List<Integer> list1 = Arrays.asList(4, 5, 6, 7); // Integer list object is being passed printOnlyIntegerClassorSuperClass(list1); // Number list List<Number> list2 = Arrays.asList(4, 5, 6, 7); // Integer list object is being passed printOnlyIntegerClassorSuperClass(list2); } public static void printOnlyIntegerClassorSuperClass( List<? super Integer> list) { System.out.println(list); }}",
"e": 2991,
"s": 2316,
"text": null
},
{
"code": null,
"e": 3017,
"s": 2991,
"text": "[4, 5, 6, 7]\n[4, 5, 6, 7]"
},
{
"code": null,
"e": 3030,
"s": 3017,
"text": "Explanation:"
},
{
"code": null,
"e": 3390,
"s": 3030,
"text": "Here arguments can be Integer or superclass of Integer(which is Number). The method printOnlyIntegerClassorSuperClass will only take Integer or its superclass objects. However, if we pass a list of types Double then we will get a compilation error. It is because only the Integer field or its superclass can be passed. Double is not the superclass of Integer."
},
{
"code": null,
"e": 3691,
"s": 3390,
"text": "Note: Use extend wildcard when you want to get values out of a structure and super wildcard when you put values in a structure. Don’t use wildcard when you get and put values in a structure. You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both."
},
{
"code": null,
"e": 3858,
"s": 3691,
"text": "This wildcard type is specified using the wildcard character (?), for example, List. This is called a list of unknown types. These are useful in the following cases –"
},
{
"code": null,
"e": 3947,
"s": 3858,
"text": "When writing a method that can be employed using functionality provided in Object class."
},
{
"code": null,
"e": 4041,
"s": 3947,
"text": "When the code is using methods in the generic class that doesn’t depend on the type parameter"
},
{
"code": null,
"e": 4057,
"s": 4041,
"text": "Implementation:"
},
{
"code": null,
"e": 4062,
"s": 4057,
"text": "Java"
},
{
"code": "// Java program to demonstrate Unbounded wildcard import java.util.Arrays;import java.util.List; class unboundedwildcardemo { public static void main(String[] args) { // Integer List List<Integer> list1 = Arrays.asList(1, 2, 3); // Double list List<Double> list2 = Arrays.asList(1.1, 2.2, 3.3); printlist(list1); printlist(list2); } private static void printlist(List<?> list) { System.out.println(list); }}",
"e": 4543,
"s": 4062,
"text": null
},
{
"code": null,
"e": 4569,
"s": 4543,
"text": "[1, 2, 3]\n[1.1, 2.2, 3.3]"
},
{
"code": null,
"e": 4992,
"s": 4569,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5008,
"s": 4992,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 5016,
"s": 5008,
"text": "krrishh"
},
{
"code": null,
"e": 5021,
"s": 5016,
"text": "Java"
},
{
"code": null,
"e": 5026,
"s": 5021,
"text": "Java"
}
] |
Binary search in sorted vector of pairs
|
12 Jun, 2022
How to apply STL binary_search to vector of pairs(key, value), given that vector is sorted by its first value(key) struct compare in the code contains two functions which compares the key(searching element) with the first element in the vector
CPP
/* C++ code to demonstrate how Binary Searchcan be applied on a vector of pairs */#include <bits/stdc++.h>using namespace std; struct compare { bool operator()(const pair<int, int>& value, const int& key) { return (value.first < key); } bool operator()(const int& key, const pair<int, int>& value) { return (key < value.first); }}; int main(){ // initializing the vector of pairs vector<pair<int, int> > vect; // insertion of pairs (key, value) in vector vect vect.push_back(make_pair(1, 20)); vect.push_back(make_pair(3, 42)); vect.push_back(make_pair(4, 36)); vect.push_back(make_pair(2, 80)); vect.push_back(make_pair(7, 50)); vect.push_back(make_pair(9, 20)); vect.push_back(make_pair(3, 29)); // sorting the vector according to key sort(vect.begin(), vect.end()); // printing the sorted vector cout << "KEY" << '\t' << "ELEMENT" << endl; for (pair<int, int>& x : vect) cout << x.first << '\t' << x.second << endl; // searching for the key element 3 cout << "search for key 3 in vector" << endl; if (binary_search(vect.begin(), vect.end(), 3, compare())) cout << "Element found"; else cout << "Element not found"; return 0;}
KEY ELEMENT
1 20
2 80
3 29
3 42
4 36
7 50
9 20
search for key 3 in vector
Element found
Time complexity: O(n log n) (As sort() function is used)
Auxiliary Space: O(1)
Code_Mech
codewithrathi
cpp-pair
cpp-vector
STL
C++
Searching
Searching
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 297,
"s": 52,
"text": "How to apply STL binary_search to vector of pairs(key, value), given that vector is sorted by its first value(key) struct compare in the code contains two functions which compares the key(searching element) with the first element in the vector "
},
{
"code": null,
"e": 301,
"s": 297,
"text": "CPP"
},
{
"code": "/* C++ code to demonstrate how Binary Searchcan be applied on a vector of pairs */#include <bits/stdc++.h>using namespace std; struct compare { bool operator()(const pair<int, int>& value, const int& key) { return (value.first < key); } bool operator()(const int& key, const pair<int, int>& value) { return (key < value.first); }}; int main(){ // initializing the vector of pairs vector<pair<int, int> > vect; // insertion of pairs (key, value) in vector vect vect.push_back(make_pair(1, 20)); vect.push_back(make_pair(3, 42)); vect.push_back(make_pair(4, 36)); vect.push_back(make_pair(2, 80)); vect.push_back(make_pair(7, 50)); vect.push_back(make_pair(9, 20)); vect.push_back(make_pair(3, 29)); // sorting the vector according to key sort(vect.begin(), vect.end()); // printing the sorted vector cout << \"KEY\" << '\\t' << \"ELEMENT\" << endl; for (pair<int, int>& x : vect) cout << x.first << '\\t' << x.second << endl; // searching for the key element 3 cout << \"search for key 3 in vector\" << endl; if (binary_search(vect.begin(), vect.end(), 3, compare())) cout << \"Element found\"; else cout << \"Element not found\"; return 0;}",
"e": 1458,
"s": 301,
"text": null
},
{
"code": null,
"e": 1570,
"s": 1458,
"text": "KEY ELEMENT\n1 20\n2 80\n3 29\n3 42\n4 36\n7 50\n9 20\nsearch for key 3 in vector\nElement found"
},
{
"code": null,
"e": 1627,
"s": 1570,
"text": "Time complexity: O(n log n) (As sort() function is used)"
},
{
"code": null,
"e": 1649,
"s": 1627,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1659,
"s": 1649,
"text": "Code_Mech"
},
{
"code": null,
"e": 1673,
"s": 1659,
"text": "codewithrathi"
},
{
"code": null,
"e": 1682,
"s": 1673,
"text": "cpp-pair"
},
{
"code": null,
"e": 1693,
"s": 1682,
"text": "cpp-vector"
},
{
"code": null,
"e": 1697,
"s": 1693,
"text": "STL"
},
{
"code": null,
"e": 1701,
"s": 1697,
"text": "C++"
},
{
"code": null,
"e": 1711,
"s": 1701,
"text": "Searching"
},
{
"code": null,
"e": 1721,
"s": 1711,
"text": "Searching"
},
{
"code": null,
"e": 1725,
"s": 1721,
"text": "STL"
},
{
"code": null,
"e": 1729,
"s": 1725,
"text": "CPP"
},
{
"code": null,
"e": 1827,
"s": 1729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1851,
"s": 1827,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1871,
"s": 1851,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1904,
"s": 1871,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1929,
"s": 1904,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1973,
"s": 1929,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1987,
"s": 1973,
"text": "Binary Search"
},
{
"code": null,
"e": 2055,
"s": 1987,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 2069,
"s": 2055,
"text": "Linear Search"
},
{
"code": null,
"e": 2125,
"s": 2069,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
lshw command in Linux with Examples
|
23 May, 2019
lshw(list hardware) is a small Linux/Unix tool which is used to generate the detailed information of the system’s hardware configuration from various files in the /proc directory. lshw can also report exact memory configuration, firmware version, mainboard configuration, CPU version and speed, cache memory configuration, bus speed, etc on DMI-capable x86 or IA-64(Itanium family of 64 microprocessors) system and some PowerPC machine. This command needs root permission to show full information else partial information will be displayed.
Syntax:
lshw [-format] [-options ...]
Where format can be:
-html: Output hardware tree as HTML.
-xml: Output hardware tree as XML.
-short: Output hardware paths.
-businfo: Output bus information.
Example 1: To display full hardware information.
Input:
Output:
Example 2: Lists hardware in a compact format.
Input:
Output:
Options:
-class CLASS: This option is used when we only want lshw command to show a certain class of hardware.Example 1: To lists all disks and storage controllers in the system.Example 2: To lists all network interfaces in HTML file say geeksforgeeks.html.Input:A file namely geeksforgeeks.html will be created in the home directory as soon as we execute the command. The image shown below is the output displayed in the created html file.Output:
Example 1: To lists all disks and storage controllers in the system.
Example 2: To lists all network interfaces in HTML file say geeksforgeeks.html.
Input:
A file namely geeksforgeeks.html will be created in the home directory as soon as we execute the command. The image shown below is the output displayed in the created html file.
Output:
-disable TEST, -enable TEST : This option is used to enable or disable a test like pci, isapnp, cpuid, usb, network, dmi, device-tree, cpuinfo, spd, etc.Example: To enable pci.Input:Output:
Example: To enable pci.
Input:
Output:
-quiet: This option is used when the user don’t want lshw to display status.
-sanitize: This option is used to sanitize output i.e. when we don’t want sensitive information like serial numbers, etc to be displayed.Example: To check hardware information without the serial number or any other sensitive information.Input:Output:You can see in the fourth line of the above output, the serial number is not displayed instead it shows [REMOVED].
Example: To check hardware information without the serial number or any other sensitive information.
Input:
Output:
You can see in the fourth line of the above output, the serial number is not displayed instead it shows [REMOVED].
-numeric: This option is used to when the user also want lshw to display numeric IDs (for PCI, USB, etc.)Example: To check numeric IDs of class disk.
Example: To check numeric IDs of class disk.
-version: Displays the version of lshw and exits.
–help: Display help related information, available command line options and exit.
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 569,
"s": 28,
"text": "lshw(list hardware) is a small Linux/Unix tool which is used to generate the detailed information of the system’s hardware configuration from various files in the /proc directory. lshw can also report exact memory configuration, firmware version, mainboard configuration, CPU version and speed, cache memory configuration, bus speed, etc on DMI-capable x86 or IA-64(Itanium family of 64 microprocessors) system and some PowerPC machine. This command needs root permission to show full information else partial information will be displayed."
},
{
"code": null,
"e": 577,
"s": 569,
"text": "Syntax:"
},
{
"code": null,
"e": 607,
"s": 577,
"text": "lshw [-format] [-options ...]"
},
{
"code": null,
"e": 628,
"s": 607,
"text": "Where format can be:"
},
{
"code": null,
"e": 665,
"s": 628,
"text": "-html: Output hardware tree as HTML."
},
{
"code": null,
"e": 700,
"s": 665,
"text": "-xml: Output hardware tree as XML."
},
{
"code": null,
"e": 731,
"s": 700,
"text": "-short: Output hardware paths."
},
{
"code": null,
"e": 765,
"s": 731,
"text": "-businfo: Output bus information."
},
{
"code": null,
"e": 814,
"s": 765,
"text": "Example 1: To display full hardware information."
},
{
"code": null,
"e": 821,
"s": 814,
"text": "Input:"
},
{
"code": null,
"e": 829,
"s": 821,
"text": "Output:"
},
{
"code": null,
"e": 876,
"s": 829,
"text": "Example 2: Lists hardware in a compact format."
},
{
"code": null,
"e": 883,
"s": 876,
"text": "Input:"
},
{
"code": null,
"e": 891,
"s": 883,
"text": "Output:"
},
{
"code": null,
"e": 900,
"s": 891,
"text": "Options:"
},
{
"code": null,
"e": 1339,
"s": 900,
"text": "-class CLASS: This option is used when we only want lshw command to show a certain class of hardware.Example 1: To lists all disks and storage controllers in the system.Example 2: To lists all network interfaces in HTML file say geeksforgeeks.html.Input:A file namely geeksforgeeks.html will be created in the home directory as soon as we execute the command. The image shown below is the output displayed in the created html file.Output:"
},
{
"code": null,
"e": 1408,
"s": 1339,
"text": "Example 1: To lists all disks and storage controllers in the system."
},
{
"code": null,
"e": 1488,
"s": 1408,
"text": "Example 2: To lists all network interfaces in HTML file say geeksforgeeks.html."
},
{
"code": null,
"e": 1495,
"s": 1488,
"text": "Input:"
},
{
"code": null,
"e": 1673,
"s": 1495,
"text": "A file namely geeksforgeeks.html will be created in the home directory as soon as we execute the command. The image shown below is the output displayed in the created html file."
},
{
"code": null,
"e": 1681,
"s": 1673,
"text": "Output:"
},
{
"code": null,
"e": 1871,
"s": 1681,
"text": "-disable TEST, -enable TEST : This option is used to enable or disable a test like pci, isapnp, cpuid, usb, network, dmi, device-tree, cpuinfo, spd, etc.Example: To enable pci.Input:Output:"
},
{
"code": null,
"e": 1895,
"s": 1871,
"text": "Example: To enable pci."
},
{
"code": null,
"e": 1902,
"s": 1895,
"text": "Input:"
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Output:"
},
{
"code": null,
"e": 1987,
"s": 1910,
"text": "-quiet: This option is used when the user don’t want lshw to display status."
},
{
"code": null,
"e": 2352,
"s": 1987,
"text": "-sanitize: This option is used to sanitize output i.e. when we don’t want sensitive information like serial numbers, etc to be displayed.Example: To check hardware information without the serial number or any other sensitive information.Input:Output:You can see in the fourth line of the above output, the serial number is not displayed instead it shows [REMOVED]."
},
{
"code": null,
"e": 2453,
"s": 2352,
"text": "Example: To check hardware information without the serial number or any other sensitive information."
},
{
"code": null,
"e": 2460,
"s": 2453,
"text": "Input:"
},
{
"code": null,
"e": 2468,
"s": 2460,
"text": "Output:"
},
{
"code": null,
"e": 2583,
"s": 2468,
"text": "You can see in the fourth line of the above output, the serial number is not displayed instead it shows [REMOVED]."
},
{
"code": null,
"e": 2733,
"s": 2583,
"text": "-numeric: This option is used to when the user also want lshw to display numeric IDs (for PCI, USB, etc.)Example: To check numeric IDs of class disk."
},
{
"code": null,
"e": 2778,
"s": 2733,
"text": "Example: To check numeric IDs of class disk."
},
{
"code": null,
"e": 2828,
"s": 2778,
"text": "-version: Displays the version of lshw and exits."
},
{
"code": null,
"e": 2910,
"s": 2828,
"text": "–help: Display help related information, available command line options and exit."
},
{
"code": null,
"e": 2924,
"s": 2910,
"text": "linux-command"
},
{
"code": null,
"e": 2944,
"s": 2924,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 2955,
"s": 2944,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3053,
"s": 2955,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3079,
"s": 3053,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3114,
"s": 3079,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3151,
"s": 3114,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3180,
"s": 3151,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3219,
"s": 3180,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 3259,
"s": 3219,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3296,
"s": 3259,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3333,
"s": 3296,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 3367,
"s": 3333,
"text": "mv command in Linux with examples"
}
] |
What is Regex in Golang?
|
19 May, 2020
A Regular Expression (or RegEx) is a special sequence of characters that defines a search pattern that is used for matching specific text. In Golang, there’s a built-in package for regular expressions, called the regexp package which contains all list of actions like filtering, replacing, validating, or extracting. It uses the RE2 syntax standards. The MatchString() function reports whether the string passed as a parameter contains any match of the regular expression pattern.
Syntax:
func MatchString(pattern string, s string)
Returns: matched bool, err error
Example:
// Golang program to illustrate the// string matching using regexp// in-built functionpackage main import ( "fmt" "regexp") func main() { // string in which the pattern // is to be found str := "geeksforgeeks" // returns true if the pattern is present // in the string, else returns false // err is nil if the regexp is valid match1, err := regexp.MatchString("geeks", str) fmt.Println("Match: ", match1, " Error: ", err) // this returns false as the match // is unsuccessful str2 := "ComputerScience" match2, err := regexp.MatchString("geeks", str2) fmt.Println("Match: ", match2, "Error: ", err) // this will throw an error // as the pattern is not valid match3, err := regexp.MatchString("geek(s", str2) fmt.Println("Match: ", match3, "Error: ", err)}
Output:
Match: true Error: <nil>
Match: false Error: <nil>
Match: false Error: error parsing regexp: missing closing ): `geek(s`
To store complicated regular expressions for reuse later, Compile() method parses a regular expression and returns a Regexp object if successful which can be used to match the text. Prototype of the function is:
func Compile(expr string) (*Regexp, error)
There are other various methods provided in the regexp package to match strings as shown:
// Golang program to illustrate the// string matching using regexp// in-built functionspackage main import ( "fmt" "regexp" "strings") func main() { // a regex object which // can be reused later re, _ := regexp.Compile("geek") // string to be matched str := "I love geeksforgeeks" // returns the slice of first // and last index match := re.FindStringIndex(str) fmt.Println(match) str2 := "I love computer science" // prints an empty slice // as there is no match match2 := re.FindStringIndex(str2) fmt.Println(match2) // finds the first or leftmost // match to a given pattern. re2, _ := regexp.Compile("[0-9]+-v.*g") // matches one or more numbers followed // by v and any number of characters upto g match3 := re2.FindString("20024-vani_gupta") fmt.Println(match3) // returns a slice of all successive // matches of the expression match4 := re.FindAllStringSubmatchIndex("I'am a geek at"+ " geeksforgeeks", -1) fmt.Println(match4) // returns a copy and replaces // matches with the replacement string re3, _ := regexp.Compile(" ") match5 := re3.ReplaceAllString("All I do"+ " is code everytime.", "+") fmt.Println(match5) // returns a copy in which all matches are // replaced by return value of function re4, _ := regexp.Compile("[aeiou]+") match6 := re4.ReplaceAllStringFunc("All I do"+ " is code everytime.", strings.ToUpper) fmt.Println(match6)}
Output:
[7 11]
[]
20024-vani_g
[[7 11] [15 19] [23 27]]
All+I+do+is+code+everytime.
All I dO Is cOdE EvErytImE.
Golang-Misc
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Golang Maps
Interfaces in Golang
Data Types in Go
Slices in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to Assign Default Value for Struct Field in Golang?
Pointers in Golang
How to iterate over an Array using for loop in Golang?
Go Programming Language (Introduction)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 533,
"s": 52,
"text": "A Regular Expression (or RegEx) is a special sequence of characters that defines a search pattern that is used for matching specific text. In Golang, there’s a built-in package for regular expressions, called the regexp package which contains all list of actions like filtering, replacing, validating, or extracting. It uses the RE2 syntax standards. The MatchString() function reports whether the string passed as a parameter contains any match of the regular expression pattern."
},
{
"code": null,
"e": 541,
"s": 533,
"text": "Syntax:"
},
{
"code": null,
"e": 584,
"s": 541,
"text": "func MatchString(pattern string, s string)"
},
{
"code": null,
"e": 617,
"s": 584,
"text": "Returns: matched bool, err error"
},
{
"code": null,
"e": 626,
"s": 617,
"text": "Example:"
},
{
"code": "// Golang program to illustrate the// string matching using regexp// in-built functionpackage main import ( \"fmt\" \"regexp\") func main() { // string in which the pattern // is to be found str := \"geeksforgeeks\" // returns true if the pattern is present // in the string, else returns false // err is nil if the regexp is valid match1, err := regexp.MatchString(\"geeks\", str) fmt.Println(\"Match: \", match1, \" Error: \", err) // this returns false as the match // is unsuccessful str2 := \"ComputerScience\" match2, err := regexp.MatchString(\"geeks\", str2) fmt.Println(\"Match: \", match2, \"Error: \", err) // this will throw an error // as the pattern is not valid match3, err := regexp.MatchString(\"geek(s\", str2) fmt.Println(\"Match: \", match3, \"Error: \", err)}",
"e": 1448,
"s": 626,
"text": null
},
{
"code": null,
"e": 1456,
"s": 1448,
"text": "Output:"
},
{
"code": null,
"e": 1585,
"s": 1456,
"text": "Match: true Error: <nil>\nMatch: false Error: <nil>\nMatch: false Error: error parsing regexp: missing closing ): `geek(s`\n"
},
{
"code": null,
"e": 1797,
"s": 1585,
"text": "To store complicated regular expressions for reuse later, Compile() method parses a regular expression and returns a Regexp object if successful which can be used to match the text. Prototype of the function is:"
},
{
"code": null,
"e": 1840,
"s": 1797,
"text": "func Compile(expr string) (*Regexp, error)"
},
{
"code": null,
"e": 1930,
"s": 1840,
"text": "There are other various methods provided in the regexp package to match strings as shown:"
},
{
"code": "// Golang program to illustrate the// string matching using regexp// in-built functionspackage main import ( \"fmt\" \"regexp\" \"strings\") func main() { // a regex object which // can be reused later re, _ := regexp.Compile(\"geek\") // string to be matched str := \"I love geeksforgeeks\" // returns the slice of first // and last index match := re.FindStringIndex(str) fmt.Println(match) str2 := \"I love computer science\" // prints an empty slice // as there is no match match2 := re.FindStringIndex(str2) fmt.Println(match2) // finds the first or leftmost // match to a given pattern. re2, _ := regexp.Compile(\"[0-9]+-v.*g\") // matches one or more numbers followed // by v and any number of characters upto g match3 := re2.FindString(\"20024-vani_gupta\") fmt.Println(match3) // returns a slice of all successive // matches of the expression match4 := re.FindAllStringSubmatchIndex(\"I'am a geek at\"+ \" geeksforgeeks\", -1) fmt.Println(match4) // returns a copy and replaces // matches with the replacement string re3, _ := regexp.Compile(\" \") match5 := re3.ReplaceAllString(\"All I do\"+ \" is code everytime.\", \"+\") fmt.Println(match5) // returns a copy in which all matches are // replaced by return value of function re4, _ := regexp.Compile(\"[aeiou]+\") match6 := re4.ReplaceAllStringFunc(\"All I do\"+ \" is code everytime.\", strings.ToUpper) fmt.Println(match6)}",
"e": 3488,
"s": 1930,
"text": null
},
{
"code": null,
"e": 3496,
"s": 3488,
"text": "Output:"
},
{
"code": null,
"e": 3601,
"s": 3496,
"text": "[7 11]\n[]\n20024-vani_g\n[[7 11] [15 19] [23 27]]\nAll+I+do+is+code+everytime.\nAll I dO Is cOdE EvErytImE.\n"
},
{
"code": null,
"e": 3613,
"s": 3601,
"text": "Golang-Misc"
},
{
"code": null,
"e": 3620,
"s": 3613,
"text": "Picked"
},
{
"code": null,
"e": 3632,
"s": 3620,
"text": "Go Language"
},
{
"code": null,
"e": 3730,
"s": 3632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3742,
"s": 3730,
"text": "Golang Maps"
},
{
"code": null,
"e": 3763,
"s": 3742,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 3780,
"s": 3763,
"text": "Data Types in Go"
},
{
"code": null,
"e": 3797,
"s": 3780,
"text": "Slices in Golang"
},
{
"code": null,
"e": 3826,
"s": 3797,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 3858,
"s": 3826,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 3914,
"s": 3858,
"text": "How to Assign Default Value for Struct Field in Golang?"
},
{
"code": null,
"e": 3933,
"s": 3914,
"text": "Pointers in Golang"
},
{
"code": null,
"e": 3988,
"s": 3933,
"text": "How to iterate over an Array using for loop in Golang?"
}
] |
Solve the Linear Equation of Single Variable
|
30 Jul, 2018
Given a linear equation, task is to find the value of variable used. The equation contains only ‘+’, ‘-‘ operation, the variable and its coefficient.
If there is no solution for the equation, return “No solution”.If there are infinite solutions for the equation, return “Infinite solutions”.If there is exactly one solution for the equation, ensure that the value of x is an integer.
If there is no solution for the equation, return “No solution”.
If there are infinite solutions for the equation, return “Infinite solutions”.
If there is exactly one solution for the equation, ensure that the value of x is an integer.
Examples :
Input : "x + 5 - 3 + x = 6 + x - 2"
Output : "x = 2"
Input : "x = x"
Output : "Infinite solutions"
Input: "2x = x"
Output: "x = 0"
Input: "x = x + 2"
Output: "No solution"
Approach : The idea is to use two pointers to update two parameters: the coefficient of variable used and the total sum. On the left and right side of ‘=’, use opposite signs for each numbers which is taken care of by a sign variable, which will flip once ‘=’ is seen.
Now, in case of a unique solution, the ratio of the effective total and coefficient gives the required result. In case of infinite solutions, both the effective total and coefficient turns out to be zero e.g. x + 1 = x + 1. In case of no solution, the coefficient of x turns out to be zero, but the effective total is non-zero.
C++
Java
Python3
C#
PHP
// CPP program to solve the given equation#include <bits/stdc++.h>using namespace std; // Function to solve the given equationstring solveEquation(string equation){ int n = equation.size(), sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation[j] == '+' || equation[j] == '-') { if (j > i) total += sign * stoi(equation.substr(i, j - i)); i = j; } // For cases such as: x, -x, +x else if (equation[j] == 'x') { if ((i == j) || equation[j - 1] == '+') coeff += sign; else if (equation[j - 1] == '-') coeff -= sign; else coeff += sign * stoi(equation.substr(i, j - i)); i = j + 1; } // Flip sign once '=' is seen else if (equation[j] == '=') { if (j > i) total += sign * stoi(equation.substr(i, j - i)); sign = -1; i = j + 1; } } // There may be a number left in the end if (i < n) total += sign * stoi(equation.substr(i)); // For infinite solutions if (coeff == 0 && total == 0) return "Infinite solutions"; // For no solution if (coeff == 0 && total) return "No solution"; // x = total sum / coeff of x // '-' sign indicates moving // numeric value to right hand side int ans = -total / coeff; return "x=" + to_string(ans);} // Driver codeint main(){ string equation = "x+5-3+x=6+x-2"; cout << solveEquation(equation); return 0;}
// Java program to solve// the given equationimport java.io.*; class GFG{// Function to solve // the given equationstatic String solveEquation(String equation){ int n = equation.length(), sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation.charAt(j) == '+' || equation.charAt(j) == '-') { if (j > i) total += sign * Integer.parseInt( equation.substring(i, j)); i = j; } // For cases such // as: x, -x, +x else if (equation.charAt(j) == 'x') { if ((i == j) || equation.charAt(j - 1) == '+') coeff += sign; else if (equation.charAt(j - 1) == '-') coeff -= sign; else coeff += sign * Integer.parseInt( equation.substring(i, j)); i = j + 1; } // Flip sign once // '=' is seen else if (equation.charAt(j) == '=') { if (j > i) total += sign * Integer.parseInt( equation.substring(i, j)); sign = -1; i = j + 1; } } // There may be a // number left in the end if (i < n) total = total + sign * Integer.parseInt( equation.substring(i)); // For infinite // solutions if (coeff == 0 && total == 0) return "Infinite solutions"; // For no solution if (coeff == 0 && total != 0) return "No solution"; // x = total sum / coeff // of x '-' sign indicates // moving numeric value to // right hand side int ans = -total / coeff; return (Integer.toString(ans));} // Driver codepublic static void main(String args[]){ String equation = new String("x+5-3+x=6+x-2"); System.out.print("x = " + solveEquation(equation));}} // This code is contributed by // Manish Shaw(manishshaw1)
# Python program to solve# the given equation # def to solve # the given equationdef solveEquation(equation) : n = len(equation) sign = 1 coeff = 0 total = 0 i = 0 # Traverse the equation for j in range(0, n) : if (equation[j] == '+' or equation[j] == '-') : if (j > i) : total = (total + sign * int(equation[i: j])) i = j # For cases such # as: x, -x, +x elif (equation[j] == 'x') : if ((i == j) or equation[j - 1] == '+') : coeff += sign elif (equation[j - 1] == '-') : coeff = coeff - sign else : coeff = (coeff + sign * int(equation[i: j])) i = j + 1 # Flip sign once # '=' is seen elif (equation[j] == '=') : if (j > i) : total = (total + sign * int(equation[i: j])) sign = -1 i = j + 1 # There may be a number # left in the end if (i < n) : total = (total + sign * int(equation[i: len(equation)])) # For infinite solutions if (coeff == 0 and total == 0) : return "Infinite solutions" # For no solution if (coeff == 0 and total) : return "No solution" # x = total sum / coeff of x # '-' sign indicates moving # numeric value to right hand side ans = -total / coeff return int(ans) # Driver codeequation = "x+5-3+x=6+x-2"print ("x = {}" . format(solveEquation(equation))) # This code is contributed by # Manish Shaw(manishshaw1)
// C# program to solve// the given equationusing System; class GFG{ // Function to solve // the given equation static string solveEquation(string equation) { int n = equation.Length, sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation[j] == '+' || equation[j] == '-') { if (j > i) total += sign * Int32.Parse( equation.Substring(i, j - i)); i = j; } // For cases such // as: x, -x, +x else if (equation[j] == 'x') { if ((i == j) || equation[j - 1] == '+') coeff += sign; else if (equation[j - 1] == '-') coeff -= sign; else coeff += sign * Int32.Parse( equation.Substring(i, j - i)); i = j + 1; } // Flip sign once // '=' is seen else if (equation[j] == '=') { if (j > i) total += sign * Int32.Parse( equation.Substring(i, j - i)); sign = -1; i = j + 1; } } // There may be a // number left in the end if (i < n) total += sign * Int32.Parse( equation.Substring(i)); // For infinite // solutions if (coeff == 0 && total == 0) return "Infinite solutions"; // For no solution if (coeff == 0 && total != 0) return "No solution"; // x = total sum / coeff // of x '-' sign indicates // moving numeric value to // right hand side int ans = -total / coeff; return "x = " + ans.ToString(); } // Driver code static void Main() { string equation = "x+5-3+x=6+x-2"; Console.Write(solveEquation(equation)); }} // This code is contributed by // Manish Shaw(manishshaw1)
<?php// PHP program to solve// the given equation // Function to solve // the given equationfunction solveEquation($equation){ $n = strlen($equation); $sign = 1; $coeff = 0; $total = 0; $i = 0; // Traverse the equation for ($j = 0; $j < $n; $j++) { if ($equation[$j] == '+' || $equation[$j] == '-') { if ($j > $i) $total += $sign * intval(substr($equation, $i, $j - $i)); $i = $j; } // For cases such // as: x, -x, +x else if ($equation[$j] == 'x') { if (($i == $j) || $equation[$j - 1] == '+') $coeff += $sign; else if ($equation[$j - 1] == '-') $coeff -= $sign; else $coeff += $sign * intval(substr($equation, $i, $j - $i)); $i = $j + 1; } // Flip sign once // '=' is seen else if ($equation[$j] == '=') { if ($j > $i) $total += $sign * intval(substr($equation, $i, $j - $i)); $sign = -1; $i = $j + 1; } } // There may be a number // left in the end if ($i < $n) $total += $sign * intval(substr($equation, $i)); // For infinite solutions if ($coeff == 0 && $total == 0) return "Infinite solutions"; // For no solution if ($coeff == 0 && $total) return "No solution"; // x = total sum / coeff of x // '-' sign indicates moving // numeric value to right hand side $ans = -$total / $coeff; return "x = " . $ans;} // Driver code$equation = "x+5-3+x=6+x-2";echo (solveEquation($equation)); // This code is contributed by // Manish Shaw(manishshaw1)?>
x = 2
Time complexity : O(n), where n is the length of equation string.Auxiliary Space : O(1)
manishshaw1
expression-evaluation
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Count ways to reach the n'th stair
Check if a number is Palindrome
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Product of Array except itself
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jul, 2018"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "Given a linear equation, task is to find the value of variable used. The equation contains only ‘+’, ‘-‘ operation, the variable and its coefficient."
},
{
"code": null,
"e": 436,
"s": 202,
"text": "If there is no solution for the equation, return “No solution”.If there are infinite solutions for the equation, return “Infinite solutions”.If there is exactly one solution for the equation, ensure that the value of x is an integer."
},
{
"code": null,
"e": 500,
"s": 436,
"text": "If there is no solution for the equation, return “No solution”."
},
{
"code": null,
"e": 579,
"s": 500,
"text": "If there are infinite solutions for the equation, return “Infinite solutions”."
},
{
"code": null,
"e": 672,
"s": 579,
"text": "If there is exactly one solution for the equation, ensure that the value of x is an integer."
},
{
"code": null,
"e": 683,
"s": 672,
"text": "Examples :"
},
{
"code": null,
"e": 859,
"s": 683,
"text": "Input : \"x + 5 - 3 + x = 6 + x - 2\"\nOutput : \"x = 2\"\n\nInput : \"x = x\"\nOutput : \"Infinite solutions\"\n\nInput: \"2x = x\"\nOutput: \"x = 0\"\n\nInput: \"x = x + 2\"\nOutput: \"No solution\"\n"
},
{
"code": null,
"e": 1128,
"s": 859,
"text": "Approach : The idea is to use two pointers to update two parameters: the coefficient of variable used and the total sum. On the left and right side of ‘=’, use opposite signs for each numbers which is taken care of by a sign variable, which will flip once ‘=’ is seen."
},
{
"code": null,
"e": 1456,
"s": 1128,
"text": "Now, in case of a unique solution, the ratio of the effective total and coefficient gives the required result. In case of infinite solutions, both the effective total and coefficient turns out to be zero e.g. x + 1 = x + 1. In case of no solution, the coefficient of x turns out to be zero, but the effective total is non-zero."
},
{
"code": null,
"e": 1460,
"s": 1456,
"text": "C++"
},
{
"code": null,
"e": 1465,
"s": 1460,
"text": "Java"
},
{
"code": null,
"e": 1473,
"s": 1465,
"text": "Python3"
},
{
"code": null,
"e": 1476,
"s": 1473,
"text": "C#"
},
{
"code": null,
"e": 1480,
"s": 1476,
"text": "PHP"
},
{
"code": "// CPP program to solve the given equation#include <bits/stdc++.h>using namespace std; // Function to solve the given equationstring solveEquation(string equation){ int n = equation.size(), sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation[j] == '+' || equation[j] == '-') { if (j > i) total += sign * stoi(equation.substr(i, j - i)); i = j; } // For cases such as: x, -x, +x else if (equation[j] == 'x') { if ((i == j) || equation[j - 1] == '+') coeff += sign; else if (equation[j - 1] == '-') coeff -= sign; else coeff += sign * stoi(equation.substr(i, j - i)); i = j + 1; } // Flip sign once '=' is seen else if (equation[j] == '=') { if (j > i) total += sign * stoi(equation.substr(i, j - i)); sign = -1; i = j + 1; } } // There may be a number left in the end if (i < n) total += sign * stoi(equation.substr(i)); // For infinite solutions if (coeff == 0 && total == 0) return \"Infinite solutions\"; // For no solution if (coeff == 0 && total) return \"No solution\"; // x = total sum / coeff of x // '-' sign indicates moving // numeric value to right hand side int ans = -total / coeff; return \"x=\" + to_string(ans);} // Driver codeint main(){ string equation = \"x+5-3+x=6+x-2\"; cout << solveEquation(equation); return 0;}",
"e": 3091,
"s": 1480,
"text": null
},
{
"code": "// Java program to solve// the given equationimport java.io.*; class GFG{// Function to solve // the given equationstatic String solveEquation(String equation){ int n = equation.length(), sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation.charAt(j) == '+' || equation.charAt(j) == '-') { if (j > i) total += sign * Integer.parseInt( equation.substring(i, j)); i = j; } // For cases such // as: x, -x, +x else if (equation.charAt(j) == 'x') { if ((i == j) || equation.charAt(j - 1) == '+') coeff += sign; else if (equation.charAt(j - 1) == '-') coeff -= sign; else coeff += sign * Integer.parseInt( equation.substring(i, j)); i = j + 1; } // Flip sign once // '=' is seen else if (equation.charAt(j) == '=') { if (j > i) total += sign * Integer.parseInt( equation.substring(i, j)); sign = -1; i = j + 1; } } // There may be a // number left in the end if (i < n) total = total + sign * Integer.parseInt( equation.substring(i)); // For infinite // solutions if (coeff == 0 && total == 0) return \"Infinite solutions\"; // For no solution if (coeff == 0 && total != 0) return \"No solution\"; // x = total sum / coeff // of x '-' sign indicates // moving numeric value to // right hand side int ans = -total / coeff; return (Integer.toString(ans));} // Driver codepublic static void main(String args[]){ String equation = new String(\"x+5-3+x=6+x-2\"); System.out.print(\"x = \" + solveEquation(equation));}} // This code is contributed by // Manish Shaw(manishshaw1)",
"e": 5322,
"s": 3091,
"text": null
},
{
"code": "# Python program to solve# the given equation # def to solve # the given equationdef solveEquation(equation) : n = len(equation) sign = 1 coeff = 0 total = 0 i = 0 # Traverse the equation for j in range(0, n) : if (equation[j] == '+' or equation[j] == '-') : if (j > i) : total = (total + sign * int(equation[i: j])) i = j # For cases such # as: x, -x, +x elif (equation[j] == 'x') : if ((i == j) or equation[j - 1] == '+') : coeff += sign elif (equation[j - 1] == '-') : coeff = coeff - sign else : coeff = (coeff + sign * int(equation[i: j])) i = j + 1 # Flip sign once # '=' is seen elif (equation[j] == '=') : if (j > i) : total = (total + sign * int(equation[i: j])) sign = -1 i = j + 1 # There may be a number # left in the end if (i < n) : total = (total + sign * int(equation[i: len(equation)])) # For infinite solutions if (coeff == 0 and total == 0) : return \"Infinite solutions\" # For no solution if (coeff == 0 and total) : return \"No solution\" # x = total sum / coeff of x # '-' sign indicates moving # numeric value to right hand side ans = -total / coeff return int(ans) # Driver codeequation = \"x+5-3+x=6+x-2\"print (\"x = {}\" . format(solveEquation(equation))) # This code is contributed by # Manish Shaw(manishshaw1)",
"e": 7071,
"s": 5322,
"text": null
},
{
"code": "// C# program to solve// the given equationusing System; class GFG{ // Function to solve // the given equation static string solveEquation(string equation) { int n = equation.Length, sign = 1, coeff = 0; int total = 0, i = 0; // Traverse the equation for (int j = 0; j < n; j++) { if (equation[j] == '+' || equation[j] == '-') { if (j > i) total += sign * Int32.Parse( equation.Substring(i, j - i)); i = j; } // For cases such // as: x, -x, +x else if (equation[j] == 'x') { if ((i == j) || equation[j - 1] == '+') coeff += sign; else if (equation[j - 1] == '-') coeff -= sign; else coeff += sign * Int32.Parse( equation.Substring(i, j - i)); i = j + 1; } // Flip sign once // '=' is seen else if (equation[j] == '=') { if (j > i) total += sign * Int32.Parse( equation.Substring(i, j - i)); sign = -1; i = j + 1; } } // There may be a // number left in the end if (i < n) total += sign * Int32.Parse( equation.Substring(i)); // For infinite // solutions if (coeff == 0 && total == 0) return \"Infinite solutions\"; // For no solution if (coeff == 0 && total != 0) return \"No solution\"; // x = total sum / coeff // of x '-' sign indicates // moving numeric value to // right hand side int ans = -total / coeff; return \"x = \" + ans.ToString(); } // Driver code static void Main() { string equation = \"x+5-3+x=6+x-2\"; Console.Write(solveEquation(equation)); }} // This code is contributed by // Manish Shaw(manishshaw1)",
"e": 9437,
"s": 7071,
"text": null
},
{
"code": "<?php// PHP program to solve// the given equation // Function to solve // the given equationfunction solveEquation($equation){ $n = strlen($equation); $sign = 1; $coeff = 0; $total = 0; $i = 0; // Traverse the equation for ($j = 0; $j < $n; $j++) { if ($equation[$j] == '+' || $equation[$j] == '-') { if ($j > $i) $total += $sign * intval(substr($equation, $i, $j - $i)); $i = $j; } // For cases such // as: x, -x, +x else if ($equation[$j] == 'x') { if (($i == $j) || $equation[$j - 1] == '+') $coeff += $sign; else if ($equation[$j - 1] == '-') $coeff -= $sign; else $coeff += $sign * intval(substr($equation, $i, $j - $i)); $i = $j + 1; } // Flip sign once // '=' is seen else if ($equation[$j] == '=') { if ($j > $i) $total += $sign * intval(substr($equation, $i, $j - $i)); $sign = -1; $i = $j + 1; } } // There may be a number // left in the end if ($i < $n) $total += $sign * intval(substr($equation, $i)); // For infinite solutions if ($coeff == 0 && $total == 0) return \"Infinite solutions\"; // For no solution if ($coeff == 0 && $total) return \"No solution\"; // x = total sum / coeff of x // '-' sign indicates moving // numeric value to right hand side $ans = -$total / $coeff; return \"x = \" . $ans;} // Driver code$equation = \"x+5-3+x=6+x-2\";echo (solveEquation($equation)); // This code is contributed by // Manish Shaw(manishshaw1)?>",
"e": 11404,
"s": 9437,
"text": null
},
{
"code": null,
"e": 11411,
"s": 11404,
"text": "x = 2\n"
},
{
"code": null,
"e": 11499,
"s": 11411,
"text": "Time complexity : O(n), where n is the length of equation string.Auxiliary Space : O(1)"
},
{
"code": null,
"e": 11511,
"s": 11499,
"text": "manishshaw1"
},
{
"code": null,
"e": 11533,
"s": 11511,
"text": "expression-evaluation"
},
{
"code": null,
"e": 11546,
"s": 11533,
"text": "Mathematical"
},
{
"code": null,
"e": 11559,
"s": 11546,
"text": "Mathematical"
},
{
"code": null,
"e": 11657,
"s": 11559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11689,
"s": 11657,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 11735,
"s": 11689,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 11779,
"s": 11735,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 11828,
"s": 11779,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 11870,
"s": 11828,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 11905,
"s": 11870,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 11937,
"s": 11905,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 12008,
"s": 11937,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 12033,
"s": 12008,
"text": "Fizz Buzz Implementation"
}
] |
HLOOKUP Function in Excel With Examples
|
24 May, 2021
Excel has several functions to search data from a table. HLOOKUP() function is one of them. The ‘H’ in the HLOOKUP() function stands for ‘horizontal’. This function generally helps to find a value from a row of an array or table. For this function to work the lookup value must be in the first row of the table or array. HLOOKUP() moves downward searches for the required output. Like VLOOKUP() this function also supports exact and approximate match.
HLOOKUP() function is used when the user tries to find a value in a table by matching a lookup value in the first row of the table. Generally, the user wants an exact match. This function searches for a value horizontally as its name means.
Syntax:
=HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup])
Here [range_lookup] argument is optional.
So, basically HLOOKUP() takes four arguments as input and returns the desired output.
Arguments:
lookup_value (Required): This is the value( maybe a value, a reference, or a text string) that HLOOKUP() function tries to match in the first row of the table. This argument must be provided by the user.
table_array (Required): This is the table or the reference of a table where the HLOOKUP() function tries to match the lookup_value and searches for the output. Also, this argument must be provided by the user.
row_index_num (Required): This is the row number where the HLOOKUP() function searches for the output. This argument should be provided by the user. This value cannot be less than 1 or greater than the number of rows in the table_array. In both cases, this function shows an error(#VALUE! Or #REF!).
[range_lookup] (Optional): This is an optional argument. It contains a logical value(TRUE or FALSE) by which HLOOKUP() can understand if the user wants an approximate or an exact match. This value is TRUE by default(If the user does not provide any value). TRUE denotes an approximate match and FALSE denotes an exact match.
Note: If [range_lookup] value is FALSE and the user wants to match a text partially, then wildcards(‘*’ or ‘?’) can be used. An asterisk matches a sequence and question mark matches a single character. And this function is not case-sensitive.
Return Value: HLOOKUP() first matches the lookup value in the first column of the table and then moves downward to search the output value. After all, it returns that output value.
Example:
The list below is taken for the example:
In the above list HLOOKUP() function is applied:
Here the user wants an exact match for the lookup value “Television”
and wants the output from the 3rd row.
Here the user wants an approximate match for the lookup value 12 and wants
the output from the 2nd row of the table array.
If TRUE is omitted in this function it will return the same result.
Output:
Output Screenshot
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to make a 3 Axis Graph using Excel?
How to Use Solver in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 480,
"s": 28,
"text": "Excel has several functions to search data from a table. HLOOKUP() function is one of them. The ‘H’ in the HLOOKUP() function stands for ‘horizontal’. This function generally helps to find a value from a row of an array or table. For this function to work the lookup value must be in the first row of the table or array. HLOOKUP() moves downward searches for the required output. Like VLOOKUP() this function also supports exact and approximate match."
},
{
"code": null,
"e": 721,
"s": 480,
"text": "HLOOKUP() function is used when the user tries to find a value in a table by matching a lookup value in the first row of the table. Generally, the user wants an exact match. This function searches for a value horizontally as its name means."
},
{
"code": null,
"e": 729,
"s": 721,
"text": "Syntax:"
},
{
"code": null,
"e": 796,
"s": 729,
"text": "=HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup])"
},
{
"code": null,
"e": 838,
"s": 796,
"text": "Here [range_lookup] argument is optional."
},
{
"code": null,
"e": 924,
"s": 838,
"text": "So, basically HLOOKUP() takes four arguments as input and returns the desired output."
},
{
"code": null,
"e": 935,
"s": 924,
"text": "Arguments:"
},
{
"code": null,
"e": 1139,
"s": 935,
"text": "lookup_value (Required): This is the value( maybe a value, a reference, or a text string) that HLOOKUP() function tries to match in the first row of the table. This argument must be provided by the user."
},
{
"code": null,
"e": 1349,
"s": 1139,
"text": "table_array (Required): This is the table or the reference of a table where the HLOOKUP() function tries to match the lookup_value and searches for the output. Also, this argument must be provided by the user."
},
{
"code": null,
"e": 1649,
"s": 1349,
"text": "row_index_num (Required): This is the row number where the HLOOKUP() function searches for the output. This argument should be provided by the user. This value cannot be less than 1 or greater than the number of rows in the table_array. In both cases, this function shows an error(#VALUE! Or #REF!)."
},
{
"code": null,
"e": 1974,
"s": 1649,
"text": "[range_lookup] (Optional): This is an optional argument. It contains a logical value(TRUE or FALSE) by which HLOOKUP() can understand if the user wants an approximate or an exact match. This value is TRUE by default(If the user does not provide any value). TRUE denotes an approximate match and FALSE denotes an exact match."
},
{
"code": null,
"e": 2217,
"s": 1974,
"text": "Note: If [range_lookup] value is FALSE and the user wants to match a text partially, then wildcards(‘*’ or ‘?’) can be used. An asterisk matches a sequence and question mark matches a single character. And this function is not case-sensitive."
},
{
"code": null,
"e": 2398,
"s": 2217,
"text": "Return Value: HLOOKUP() first matches the lookup value in the first column of the table and then moves downward to search the output value. After all, it returns that output value."
},
{
"code": null,
"e": 2407,
"s": 2398,
"text": "Example:"
},
{
"code": null,
"e": 2448,
"s": 2407,
"text": "The list below is taken for the example:"
},
{
"code": null,
"e": 2497,
"s": 2448,
"text": "In the above list HLOOKUP() function is applied:"
},
{
"code": null,
"e": 2567,
"s": 2497,
"text": "Here the user wants an exact match for the lookup value “Television” "
},
{
"code": null,
"e": 2606,
"s": 2567,
"text": "and wants the output from the 3rd row."
},
{
"code": null,
"e": 2681,
"s": 2606,
"text": "Here the user wants an approximate match for the lookup value 12 and wants"
},
{
"code": null,
"e": 2730,
"s": 2681,
"text": " the output from the 2nd row of the table array."
},
{
"code": null,
"e": 2799,
"s": 2730,
"text": " If TRUE is omitted in this function it will return the same result."
},
{
"code": null,
"e": 2807,
"s": 2799,
"text": "Output:"
},
{
"code": null,
"e": 2825,
"s": 2807,
"text": "Output Screenshot"
},
{
"code": null,
"e": 2832,
"s": 2825,
"text": "Picked"
},
{
"code": null,
"e": 2838,
"s": 2832,
"text": "Excel"
},
{
"code": null,
"e": 2936,
"s": 2838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2974,
"s": 2936,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 3006,
"s": 2974,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 3047,
"s": 3006,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 3102,
"s": 3047,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 3142,
"s": 3102,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 3170,
"s": 3142,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 3204,
"s": 3170,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 3220,
"s": 3204,
"text": "Macros in Excel"
},
{
"code": null,
"e": 3278,
"s": 3220,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
}
] |
How to match whitespace but not newlines using Python regular expressions?
|
The following code matches only the whitespaces but not newlines in the given string
import re
print re.findall(r"(\s){1,}","""I find
Tutorialspoint useful""")
This gives the output
[' ', ' ', ' ']
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "The following code matches only the whitespaces but not newlines in the given string"
},
{
"code": null,
"e": 1226,
"s": 1147,
"text": "import re\nprint re.findall(r\"(\\s){1,}\",\"\"\"I find\n Tutorialspoint useful\"\"\")"
},
{
"code": null,
"e": 1248,
"s": 1226,
"text": "This gives the output"
},
{
"code": null,
"e": 1266,
"s": 1248,
"text": "[' ', ' ', ' ']\n\n"
}
] |
Bare Machine and Resident Monitor - GeeksforGeeks
|
22 Jul, 2019
In this article, we are going to talk about two important part of the computer system, that is Bare machine and Resident monitor. So first let’s study about them that how they are important for the operating systems.
The Bare Machine and Resident Monitor are not directly related to the operating system but while we study about memory management these components are really important to study, so let’s study them one by one and then their working.
Bare Machine:So basically Bare machine is logical hardware which is used to execute the program in the processor without using the operating system. as of now, we have studied that we can’t execute any process without the Operating system. But yes with the help of the Bare machine we can do that.
Initially, when the operating systems are not developed, the execution of an instruction is done by directly on hardware without using any interfering hardware, at that time the only drawback was that the Bare machines accepting the instruction in only machine language, due to this those person who has sufficient knowledge about Computer field are able to operate a computer. so after the development of the operating system Bare machine is referred to as inefficient.
Resident Monitor:In this section, if we talk about how the code runs on Bare machines, then this component is used, so basically, the Resident Monitor is a code that runs on Bare Machines.The resident monitor works like an operating system that controls the instructions and performs all necessary functions. It also works like job sequencer because it also sequences the job and sends them to the processor.
After scheduling the job Resident monitors loads the programs one by one into the main memory according to their sequences. One most important factor about the resident monitor is that when the program execution occurred there us no gap between the program execution and the processing is going to be faster.
The Resident monitors are divided into 4 parts as:
1. Control Language Interpreter
2. Loader
3. Device Driver
4. Interrupt Processing
These are explained as following below.
Control Language Interpreter:The first part of the Resident monitor is control language interpreter which is used to read and carry out the instruction from one level to the next level.Loader:The second part of the Resident monitor which is the main part of the Resident Monitor is Loader which Loads all the necessary system and application programs into the main memory.Device Driver:The third part of the Resident monitor is Device Driver which is used to managing the connecting input-output devices to the system. So basically it is the interface between the user and the system. it works as an interface between the request and response. request which user made, Device driver responds that the system produces to fulfill these requests.Interrupt Processing:The fourth part as the name suggests, it processes the all occurred interrupt to the system.
Control Language Interpreter:The first part of the Resident monitor is control language interpreter which is used to read and carry out the instruction from one level to the next level.
Loader:The second part of the Resident monitor which is the main part of the Resident Monitor is Loader which Loads all the necessary system and application programs into the main memory.
Device Driver:The third part of the Resident monitor is Device Driver which is used to managing the connecting input-output devices to the system. So basically it is the interface between the user and the system. it works as an interface between the request and response. request which user made, Device driver responds that the system produces to fulfill these requests.
Interrupt Processing:The fourth part as the name suggests, it processes the all occurred interrupt to the system.
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Direct Access Media (DMA) Controller in Computer Architecture
General purpose registers in 8086 microprocessor
Memory mapped I/O and Isolated I/O
Registers of 8085 microprocessor
8085 program to multiply two 8 bit numbers
8085 program to add two 16 bit numbers
Introduction of Control Unit and its Design
|
[
{
"code": null,
"e": 24724,
"s": 24696,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 24941,
"s": 24724,
"text": "In this article, we are going to talk about two important part of the computer system, that is Bare machine and Resident monitor. So first let’s study about them that how they are important for the operating systems."
},
{
"code": null,
"e": 25174,
"s": 24941,
"text": "The Bare Machine and Resident Monitor are not directly related to the operating system but while we study about memory management these components are really important to study, so let’s study them one by one and then their working."
},
{
"code": null,
"e": 25472,
"s": 25174,
"text": "Bare Machine:So basically Bare machine is logical hardware which is used to execute the program in the processor without using the operating system. as of now, we have studied that we can’t execute any process without the Operating system. But yes with the help of the Bare machine we can do that."
},
{
"code": null,
"e": 25943,
"s": 25472,
"text": "Initially, when the operating systems are not developed, the execution of an instruction is done by directly on hardware without using any interfering hardware, at that time the only drawback was that the Bare machines accepting the instruction in only machine language, due to this those person who has sufficient knowledge about Computer field are able to operate a computer. so after the development of the operating system Bare machine is referred to as inefficient."
},
{
"code": null,
"e": 26352,
"s": 25943,
"text": "Resident Monitor:In this section, if we talk about how the code runs on Bare machines, then this component is used, so basically, the Resident Monitor is a code that runs on Bare Machines.The resident monitor works like an operating system that controls the instructions and performs all necessary functions. It also works like job sequencer because it also sequences the job and sends them to the processor."
},
{
"code": null,
"e": 26661,
"s": 26352,
"text": "After scheduling the job Resident monitors loads the programs one by one into the main memory according to their sequences. One most important factor about the resident monitor is that when the program execution occurred there us no gap between the program execution and the processing is going to be faster."
},
{
"code": null,
"e": 26712,
"s": 26661,
"text": "The Resident monitors are divided into 4 parts as:"
},
{
"code": null,
"e": 26796,
"s": 26712,
"text": "1. Control Language Interpreter\n2. Loader\n3. Device Driver\n4. Interrupt Processing "
},
{
"code": null,
"e": 26836,
"s": 26796,
"text": "These are explained as following below."
},
{
"code": null,
"e": 27693,
"s": 26836,
"text": "Control Language Interpreter:The first part of the Resident monitor is control language interpreter which is used to read and carry out the instruction from one level to the next level.Loader:The second part of the Resident monitor which is the main part of the Resident Monitor is Loader which Loads all the necessary system and application programs into the main memory.Device Driver:The third part of the Resident monitor is Device Driver which is used to managing the connecting input-output devices to the system. So basically it is the interface between the user and the system. it works as an interface between the request and response. request which user made, Device driver responds that the system produces to fulfill these requests.Interrupt Processing:The fourth part as the name suggests, it processes the all occurred interrupt to the system."
},
{
"code": null,
"e": 27879,
"s": 27693,
"text": "Control Language Interpreter:The first part of the Resident monitor is control language interpreter which is used to read and carry out the instruction from one level to the next level."
},
{
"code": null,
"e": 28067,
"s": 27879,
"text": "Loader:The second part of the Resident monitor which is the main part of the Resident Monitor is Loader which Loads all the necessary system and application programs into the main memory."
},
{
"code": null,
"e": 28439,
"s": 28067,
"text": "Device Driver:The third part of the Resident monitor is Device Driver which is used to managing the connecting input-output devices to the system. So basically it is the interface between the user and the system. it works as an interface between the request and response. request which user made, Device driver responds that the system produces to fulfill these requests."
},
{
"code": null,
"e": 28553,
"s": 28439,
"text": "Interrupt Processing:The fourth part as the name suggests, it processes the all occurred interrupt to the system."
},
{
"code": null,
"e": 28590,
"s": 28553,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 28688,
"s": 28590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28697,
"s": 28688,
"text": "Comments"
},
{
"code": null,
"e": 28710,
"s": 28697,
"text": "Old Comments"
},
{
"code": null,
"e": 28746,
"s": 28710,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 28781,
"s": 28746,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 28872,
"s": 28781,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 28934,
"s": 28872,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 28983,
"s": 28934,
"text": "General purpose registers in 8086 microprocessor"
},
{
"code": null,
"e": 29018,
"s": 28983,
"text": "Memory mapped I/O and Isolated I/O"
},
{
"code": null,
"e": 29051,
"s": 29018,
"text": "Registers of 8085 microprocessor"
},
{
"code": null,
"e": 29094,
"s": 29051,
"text": "8085 program to multiply two 8 bit numbers"
},
{
"code": null,
"e": 29133,
"s": 29094,
"text": "8085 program to add two 16 bit numbers"
}
] |
Lodash _.filter() Method - GeeksforGeeks
|
06 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.filter() method iterates over elements of collection, returning an array of all elements predicate returns true.
Note: This method is not similar to the _.remove() method as this method returns a new array.
Syntax:
_.filter( collection, predicate )
Parameters: This method accepts two parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
predicate: This parameter holds the function invoked per iteration.
Return Value: This method returns the new filtered array.
Example 1:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() methodlet filtered_array = _.filter( users, function(o) { return !o.active; }); // Printing the output console.log(filtered_array);
Output:
[ { user: 'kush', salary: 40000, active: false } ]
Example 2:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() method// The `_.matches` iteratee shorthandlet filtered_array = _.filter(users, { 'salary': 36000, 'active': true }); // Printing the output console.log(filtered_array);
Output:
[ { user: 'luv', salary: 36000, active: true } ]
Example 3:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() method// The `_.matchesProperty` iteratee shorthandlet filtered_array = _.filter(users, ['active', false]); // Printing the output console.log(filtered_array);
Output:
[ { user: 'kush', salary: 40000, active: false } ]
Example 4:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() method// The `_.property` iteratee shorthandlet filtered_array = _.filter(users, 'active'); // Printing the output console.log(filtered_array);
Output:
[ { user: 'luv', salary: 36000, active: true } ]
JavaScript-Lodash
JavaScript
Web Technologies
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 calculate the number of days between two dates in javascript?
File uploading in React.js
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": 37045,
"s": 37017,
"text": "\n06 Sep, 2020"
},
{
"code": null,
"e": 37196,
"s": 37045,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc."
},
{
"code": null,
"e": 37315,
"s": 37196,
"text": "The _.filter() method iterates over elements of collection, returning an array of all elements predicate returns true."
},
{
"code": null,
"e": 37409,
"s": 37315,
"text": "Note: This method is not similar to the _.remove() method as this method returns a new array."
},
{
"code": null,
"e": 37417,
"s": 37409,
"text": "Syntax:"
},
{
"code": null,
"e": 37451,
"s": 37417,
"text": "_.filter( collection, predicate )"
},
{
"code": null,
"e": 37538,
"s": 37451,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 37603,
"s": 37538,
"text": "collection: This parameter holds the collection to iterate over."
},
{
"code": null,
"e": 37671,
"s": 37603,
"text": "predicate: This parameter holds the function invoked per iteration."
},
{
"code": null,
"e": 37729,
"s": 37671,
"text": "Return Value: This method returns the new filtered array."
},
{
"code": null,
"e": 37740,
"s": 37729,
"text": "Example 1:"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() methodlet filtered_array = _.filter( users, function(o) { return !o.active; }); // Printing the output console.log(filtered_array);",
"e": 38131,
"s": 37740,
"text": null
},
{
"code": null,
"e": 38139,
"s": 38131,
"text": "Output:"
},
{
"code": null,
"e": 38190,
"s": 38139,
"text": "[ { user: 'kush', salary: 40000, active: false } ]"
},
{
"code": null,
"e": 38201,
"s": 38190,
"text": "Example 2:"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() method// The `_.matches` iteratee shorthandlet filtered_array = _.filter(users, { 'salary': 36000, 'active': true }); // Printing the output console.log(filtered_array);",
"e": 38622,
"s": 38201,
"text": null
},
{
"code": null,
"e": 38630,
"s": 38622,
"text": "Output:"
},
{
"code": null,
"e": 38679,
"s": 38630,
"text": "[ { user: 'luv', salary: 36000, active: true } ]"
},
{
"code": null,
"e": 38690,
"s": 38679,
"text": "Example 3:"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() method// The `_.matchesProperty` iteratee shorthandlet filtered_array = _.filter(users, ['active', false]); // Printing the output console.log(filtered_array);",
"e": 39098,
"s": 38690,
"text": null
},
{
"code": null,
"e": 39106,
"s": 39098,
"text": "Output:"
},
{
"code": null,
"e": 39157,
"s": 39106,
"text": "[ { user: 'kush', salary: 40000, active: false } ]"
},
{
"code": null,
"e": 39168,
"s": 39157,
"text": "Example 4:"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = [ { 'user': 'luv', 'salary': 36000, 'active': true }, { 'user': 'kush', 'salary': 40000, 'active': false }]; // Using the _.filter() method// The `_.property` iteratee shorthandlet filtered_array = _.filter(users, 'active'); // Printing the output console.log(filtered_array);",
"e": 39560,
"s": 39168,
"text": null
},
{
"code": null,
"e": 39568,
"s": 39560,
"text": "Output:"
},
{
"code": null,
"e": 39617,
"s": 39568,
"text": "[ { user: 'luv', salary: 36000, active: true } ]"
},
{
"code": null,
"e": 39635,
"s": 39617,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 39646,
"s": 39635,
"text": "JavaScript"
},
{
"code": null,
"e": 39663,
"s": 39646,
"text": "Web Technologies"
},
{
"code": null,
"e": 39761,
"s": 39663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39770,
"s": 39761,
"text": "Comments"
},
{
"code": null,
"e": 39783,
"s": 39770,
"text": "Old Comments"
},
{
"code": null,
"e": 39844,
"s": 39783,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 39889,
"s": 39844,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 39961,
"s": 39889,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 40030,
"s": 39961,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 40057,
"s": 40030,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 40113,
"s": 40057,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 40146,
"s": 40113,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40208,
"s": 40146,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 40251,
"s": 40208,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Easily Deploy Machine Learning Models Using Flask | by Abhinav Sagar | Towards Data Science
|
Stuck behind the paywall? Click here to read the full story with my Friend Link!
When a data scientist/machine learning engineer develops a machine learning model using Scikit-Learn, TensorFlow, Keras, PyTorch etc, the ultimate goal is to make it available in production. Often times when working on a machine learning project, we focus a lot on Exploratory Data Analysis(EDA), Feature Engineering, tweaking with hyper-parameters etc. But we tend to forget our main goal, which is to extract real value from the model predictions.
Deployment of machine learning models or putting models into production means making your models available to the end users or systems. However, there is complexity in the deployment of machine learning models. This post aims to make you get started with putting your trained machine learning models into production using Flask API.
I will be using linear regression to predict the sales value in the third month using rate of interest and sales of the first two months.
The objective of a linear regression model is to find a relationship between one or more features(independent variables) and a continuous target variable(dependent variable). When there is only feature it is called Uni-variate Linear Regression and if there are multiple features, it is called Multiple Linear Regression.
The linear regression model can be represented by the following equation
Y is the predicted value
θ0 is the bias term.
θ1,...,θn are the model parameters
x1, x2,...,xn are the feature values.
Easy to use.
Built in development server and debugger.
Integrated unit testing support.
RESTful request dispatching.
Extensively documented.
This project has four parts :
model.py — This contains code for the machine learning model to predict sales in the third month based on the sales in the first two months.app.py — This contains Flask APIs that receives sales details through GUI or API calls, computes the predicted value based on our model and returns it.request.py — This uses requests module to call APIs defined in app.py and displays the returned value.HTML/CSS — This contains the HTML template and CSS styling to allow user to enter sales detail and displays the predicted sales in the third month.
model.py — This contains code for the machine learning model to predict sales in the third month based on the sales in the first two months.
app.py — This contains Flask APIs that receives sales details through GUI or API calls, computes the predicted value based on our model and returns it.
request.py — This uses requests module to call APIs defined in app.py and displays the returned value.
HTML/CSS — This contains the HTML template and CSS styling to allow user to enter sales detail and displays the predicted sales in the third month.
scikit-learnpandasnumpyflask
scikit-learn
pandas
numpy
flask
Without much ado, let’s get started with the code. The complete project on github can be found here.
Let’s get started with making the front end using HTML for the user to input the values. There are three fields which need to be filled by the user — rate of interest, sales in first month and sales in second month.
Next I did some styling using CSS for the input button, login buttons and the background.
I created a custom sales dataset for this project which has four columns — rate of interest, sales in first month, sales in second month and sales in third month.
Let’s now make a machine learning model to predict sales in the third month. First let’s deal with missing values using Pandas. Missing Data can occur when no information is provided for one or more items. I filled the rate column with zero and sales in first month with mean of that column if the value was not provided. I used linear regression as the machine learning algorithm.
In simple words serializing is a way to write a python object on the disk that can be transferred anywhere and later de-serialized (read) back by a python script.
I converted the model which is in the form of a python object into a character stream using pickling. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.
The next part was to make an API which receives sales details through GUI and computes the predicted sales value based on our model. For this I de- serialized the pickled model in the form of python object. I set the main page using index.html. On submitting the form values using POST request to /predict, we get the predicted sales value.
The results can be shown by making another POST request to /results. It receives JSON inputs, uses the trained model to make a prediction and returns that prediction in JSON format which can be accessed through the API endpoint.
Finally I used requests module to call APIs defined in app.py. It displays the returned sales value in the third month.
Run the web application using this command.
$ python app.py
Open http://127.0.0.1:5000/ in your web-browser, and the GUI as shown below should appear.
This article demonstrated a very simple way to deploy machine learning models. I used linear regression to predict sales value in the third month using rate of interest and sales in first two months. One can use the knowledge gained in this blog to make some cool models and take them into production so that others can appreciate their work.
towardsdatascience.com
www.coursera.org
towardsdatascience.com
www.kdnuggets.com
The corresponding source code can be found here.
github.com
If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details:
Personal Website
Linkedin
Medium Profile
GitHub
Kaggle
Happy reading, happy learning and happy coding.
|
[
{
"code": null,
"e": 252,
"s": 171,
"text": "Stuck behind the paywall? Click here to read the full story with my Friend Link!"
},
{
"code": null,
"e": 702,
"s": 252,
"text": "When a data scientist/machine learning engineer develops a machine learning model using Scikit-Learn, TensorFlow, Keras, PyTorch etc, the ultimate goal is to make it available in production. Often times when working on a machine learning project, we focus a lot on Exploratory Data Analysis(EDA), Feature Engineering, tweaking with hyper-parameters etc. But we tend to forget our main goal, which is to extract real value from the model predictions."
},
{
"code": null,
"e": 1035,
"s": 702,
"text": "Deployment of machine learning models or putting models into production means making your models available to the end users or systems. However, there is complexity in the deployment of machine learning models. This post aims to make you get started with putting your trained machine learning models into production using Flask API."
},
{
"code": null,
"e": 1173,
"s": 1035,
"text": "I will be using linear regression to predict the sales value in the third month using rate of interest and sales of the first two months."
},
{
"code": null,
"e": 1495,
"s": 1173,
"text": "The objective of a linear regression model is to find a relationship between one or more features(independent variables) and a continuous target variable(dependent variable). When there is only feature it is called Uni-variate Linear Regression and if there are multiple features, it is called Multiple Linear Regression."
},
{
"code": null,
"e": 1568,
"s": 1495,
"text": "The linear regression model can be represented by the following equation"
},
{
"code": null,
"e": 1593,
"s": 1568,
"text": "Y is the predicted value"
},
{
"code": null,
"e": 1614,
"s": 1593,
"text": "θ0 is the bias term."
},
{
"code": null,
"e": 1649,
"s": 1614,
"text": "θ1,...,θn are the model parameters"
},
{
"code": null,
"e": 1687,
"s": 1649,
"text": "x1, x2,...,xn are the feature values."
},
{
"code": null,
"e": 1700,
"s": 1687,
"text": "Easy to use."
},
{
"code": null,
"e": 1742,
"s": 1700,
"text": "Built in development server and debugger."
},
{
"code": null,
"e": 1775,
"s": 1742,
"text": "Integrated unit testing support."
},
{
"code": null,
"e": 1804,
"s": 1775,
"text": "RESTful request dispatching."
},
{
"code": null,
"e": 1828,
"s": 1804,
"text": "Extensively documented."
},
{
"code": null,
"e": 1858,
"s": 1828,
"text": "This project has four parts :"
},
{
"code": null,
"e": 2399,
"s": 1858,
"text": "model.py — This contains code for the machine learning model to predict sales in the third month based on the sales in the first two months.app.py — This contains Flask APIs that receives sales details through GUI or API calls, computes the predicted value based on our model and returns it.request.py — This uses requests module to call APIs defined in app.py and displays the returned value.HTML/CSS — This contains the HTML template and CSS styling to allow user to enter sales detail and displays the predicted sales in the third month."
},
{
"code": null,
"e": 2540,
"s": 2399,
"text": "model.py — This contains code for the machine learning model to predict sales in the third month based on the sales in the first two months."
},
{
"code": null,
"e": 2692,
"s": 2540,
"text": "app.py — This contains Flask APIs that receives sales details through GUI or API calls, computes the predicted value based on our model and returns it."
},
{
"code": null,
"e": 2795,
"s": 2692,
"text": "request.py — This uses requests module to call APIs defined in app.py and displays the returned value."
},
{
"code": null,
"e": 2943,
"s": 2795,
"text": "HTML/CSS — This contains the HTML template and CSS styling to allow user to enter sales detail and displays the predicted sales in the third month."
},
{
"code": null,
"e": 2972,
"s": 2943,
"text": "scikit-learnpandasnumpyflask"
},
{
"code": null,
"e": 2985,
"s": 2972,
"text": "scikit-learn"
},
{
"code": null,
"e": 2992,
"s": 2985,
"text": "pandas"
},
{
"code": null,
"e": 2998,
"s": 2992,
"text": "numpy"
},
{
"code": null,
"e": 3004,
"s": 2998,
"text": "flask"
},
{
"code": null,
"e": 3105,
"s": 3004,
"text": "Without much ado, let’s get started with the code. The complete project on github can be found here."
},
{
"code": null,
"e": 3321,
"s": 3105,
"text": "Let’s get started with making the front end using HTML for the user to input the values. There are three fields which need to be filled by the user — rate of interest, sales in first month and sales in second month."
},
{
"code": null,
"e": 3411,
"s": 3321,
"text": "Next I did some styling using CSS for the input button, login buttons and the background."
},
{
"code": null,
"e": 3574,
"s": 3411,
"text": "I created a custom sales dataset for this project which has four columns — rate of interest, sales in first month, sales in second month and sales in third month."
},
{
"code": null,
"e": 3956,
"s": 3574,
"text": "Let’s now make a machine learning model to predict sales in the third month. First let’s deal with missing values using Pandas. Missing Data can occur when no information is provided for one or more items. I filled the rate column with zero and sales in first month with mean of that column if the value was not provided. I used linear regression as the machine learning algorithm."
},
{
"code": null,
"e": 4119,
"s": 3956,
"text": "In simple words serializing is a way to write a python object on the disk that can be transferred anywhere and later de-serialized (read) back by a python script."
},
{
"code": null,
"e": 4351,
"s": 4119,
"text": "I converted the model which is in the form of a python object into a character stream using pickling. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script."
},
{
"code": null,
"e": 4692,
"s": 4351,
"text": "The next part was to make an API which receives sales details through GUI and computes the predicted sales value based on our model. For this I de- serialized the pickled model in the form of python object. I set the main page using index.html. On submitting the form values using POST request to /predict, we get the predicted sales value."
},
{
"code": null,
"e": 4921,
"s": 4692,
"text": "The results can be shown by making another POST request to /results. It receives JSON inputs, uses the trained model to make a prediction and returns that prediction in JSON format which can be accessed through the API endpoint."
},
{
"code": null,
"e": 5041,
"s": 4921,
"text": "Finally I used requests module to call APIs defined in app.py. It displays the returned sales value in the third month."
},
{
"code": null,
"e": 5085,
"s": 5041,
"text": "Run the web application using this command."
},
{
"code": null,
"e": 5101,
"s": 5085,
"text": "$ python app.py"
},
{
"code": null,
"e": 5192,
"s": 5101,
"text": "Open http://127.0.0.1:5000/ in your web-browser, and the GUI as shown below should appear."
},
{
"code": null,
"e": 5535,
"s": 5192,
"text": "This article demonstrated a very simple way to deploy machine learning models. I used linear regression to predict sales value in the third month using rate of interest and sales in first two months. One can use the knowledge gained in this blog to make some cool models and take them into production so that others can appreciate their work."
},
{
"code": null,
"e": 5558,
"s": 5535,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5575,
"s": 5558,
"text": "www.coursera.org"
},
{
"code": null,
"e": 5598,
"s": 5575,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5616,
"s": 5598,
"text": "www.kdnuggets.com"
},
{
"code": null,
"e": 5665,
"s": 5616,
"text": "The corresponding source code can be found here."
},
{
"code": null,
"e": 5676,
"s": 5665,
"text": "github.com"
},
{
"code": null,
"e": 5801,
"s": 5676,
"text": "If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details:"
},
{
"code": null,
"e": 5818,
"s": 5801,
"text": "Personal Website"
},
{
"code": null,
"e": 5827,
"s": 5818,
"text": "Linkedin"
},
{
"code": null,
"e": 5842,
"s": 5827,
"text": "Medium Profile"
},
{
"code": null,
"e": 5849,
"s": 5842,
"text": "GitHub"
},
{
"code": null,
"e": 5856,
"s": 5849,
"text": "Kaggle"
}
] |
Program to display all alphabets from A to Z in uppercase and lowercase both - GeeksforGeeks
|
05 Sep, 2021
Alphabets in lowercase and uppercase can be printed using two methods, first is using ASCII values and second is to directly print values from ‘A’ to ‘Z’ using loops. Below are the implementation of both methods:
Using ASCII values:ASCII value of uppercase alphabets – 65 to 90.ASCII value of lowercase alphabets – 97 to 122.C++CJavaPython3C#PHPC++// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (int c = 97; c <= 122; ++c) cout << c << " "; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (int c = 65; c <= 90; ++c) cout << c << " "; cout << endl;} // Driver codeint main(){ cout << "Uppercase Alphabets" << endl; uppercaseAlphabets(ch); cout << "Lowercase Alphabets " << endl; lowercaseAlphabets(ch); return 0;}C// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (int c = 97; c <= 122; ++c) printf("%c ", c); printf("\n");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (int c = 65; c <= 90; ++c) // print its ascii values printf("%c ", c); printf("\n");} // Driver programint main(){ printf("Uppercase Alphabets\n"); uppercaseAlphabets(); printf("Lowercase Alphabets\n"); lowercaseAlphabets(); return 0;}Java// JAVA program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) System.out.print(" " + c); System.out.print("\n"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) System.out.print(" " + c); System.out.print("\n"); } // Driver program public static void main(String[] args) { int ch; System.out.println("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println("Lowercase Alphabets "); ob.lowercaseAlphabets(); }}Python3# Python3 program to print alphabets # Function to print the alphabet# in lower casedef lowercaseAlphabets(): # lowercase for c in range(97, 123): print(chr(c), end = " "); print(""); # Function to print the alphabet# in upper casedef uppercaseAlphabets(): # uppercase for c in range(65, 91): print(chr(c), end = " "); print(""); # Driver codeprint("Uppercase Alphabets");uppercaseAlphabets(); print("Lowercase Alphabets ");lowercaseAlphabets(); # This code is contributed by mitsC#// C# program to print alphabet using System;class Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) Console.Write(" " + (char)c); Console.Write("\n"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) Console.Write(" " + (char)c); Console.Write("\n"); } // Driver program public static void Main() { int ch; Console.WriteLine("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine("Lowercase Alphabets "); ob.lowercaseAlphabets(); }}PHP<?php// PHP program to print alphabets // Function to print the alphabet// in lower casefunction lowercaseAlphabets(){ // lowercase for ($c = 97; $c <= 122; ++$c) echo chr($c)." "; echo "\n";} // Function to print the alphabet// in upper casefunction uppercaseAlphabets(){ // uppercase for ($c = 65; $c <= 90; ++$c) echo chr($c)." "; echo "\n";} // Driver code echo "Uppercase Alphabets\n"; uppercaseAlphabets(); echo "Lowercase Alphabets \n"; lowercaseAlphabets(); // This code is contributed by mits?>Output:Uppercase Alphabets
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Lowercase Alphabets
a b c d e f g h i j k l m n o p q r s t u v w x y z
ASCII value of uppercase alphabets – 65 to 90.
ASCII value of lowercase alphabets – 97 to 122.
C++
C
Java
Python3
C#
PHP
// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (int c = 97; c <= 122; ++c) cout << c << " "; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (int c = 65; c <= 90; ++c) cout << c << " "; cout << endl;} // Driver codeint main(){ cout << "Uppercase Alphabets" << endl; uppercaseAlphabets(ch); cout << "Lowercase Alphabets " << endl; lowercaseAlphabets(ch); return 0;}
// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (int c = 97; c <= 122; ++c) printf("%c ", c); printf("\n");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (int c = 65; c <= 90; ++c) // print its ascii values printf("%c ", c); printf("\n");} // Driver programint main(){ printf("Uppercase Alphabets\n"); uppercaseAlphabets(); printf("Lowercase Alphabets\n"); lowercaseAlphabets(); return 0;}
// JAVA program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) System.out.print(" " + c); System.out.print("\n"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) System.out.print(" " + c); System.out.print("\n"); } // Driver program public static void main(String[] args) { int ch; System.out.println("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println("Lowercase Alphabets "); ob.lowercaseAlphabets(); }}
# Python3 program to print alphabets # Function to print the alphabet# in lower casedef lowercaseAlphabets(): # lowercase for c in range(97, 123): print(chr(c), end = " "); print(""); # Function to print the alphabet# in upper casedef uppercaseAlphabets(): # uppercase for c in range(65, 91): print(chr(c), end = " "); print(""); # Driver codeprint("Uppercase Alphabets");uppercaseAlphabets(); print("Lowercase Alphabets ");lowercaseAlphabets(); # This code is contributed by mits
// C# program to print alphabet using System;class Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) Console.Write(" " + (char)c); Console.Write("\n"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) Console.Write(" " + (char)c); Console.Write("\n"); } // Driver program public static void Main() { int ch; Console.WriteLine("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine("Lowercase Alphabets "); ob.lowercaseAlphabets(); }}
<?php// PHP program to print alphabets // Function to print the alphabet// in lower casefunction lowercaseAlphabets(){ // lowercase for ($c = 97; $c <= 122; ++$c) echo chr($c)." "; echo "\n";} // Function to print the alphabet// in upper casefunction uppercaseAlphabets(){ // uppercase for ($c = 65; $c <= 90; ++$c) echo chr($c)." "; echo "\n";} // Driver code echo "Uppercase Alphabets\n"; uppercaseAlphabets(); echo "Lowercase Alphabets \n"; lowercaseAlphabets(); // This code is contributed by mits?>
Uppercase Alphabets
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Lowercase Alphabets
a b c d e f g h i j k l m n o p q r s t u v w x y z
Using alphabets directly i.e.For lowercase alphabets – Run a loop from ‘a’ to ‘z’For uppercase characters – Run a loop from ‘A’ to ‘Z’C++CJavaC#PHPC++// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (char c = 'a'; c <= 'z'; ++c) cout << c << " "; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (char c = 'A'; c <= 'Z'; ++c) cout << c << " "; cout << endl;} // Driver codeint main(){ cout << "Uppercase Alphabets" << endl; uppercaseAlphabets(ch); cout << "Lowercase Alphabets " << endl; lowercaseAlphabets(ch); return 0;}C// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (char c = 'a'; c <= 'z'; ++c) printf("%c ", c); printf("\n");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (char c = 'A'; c <= 'Z'; ++c) // print its ascii values printf("%c ", c); printf("\n");} // Driver programint main(){ printf("Uppercase Alphabets\n"); uppercaseAlphabets(); printf("Lowercase Alphabets\n"); lowercaseAlphabets(); return 0;}Java// Java program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) System.out.print(" " + c); System.out.print("\n"); } void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) System.out.print(" " + c); System.out.print("\n"); } // Driver program public static void main(String[] args) { System.out.println("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println("Lowercase Alphabets "); ob.lowercaseAlphabets(); }}C#// C# program to print alphabetusing System; public class Alpha { private int ch; // Function to print the alphabet // in upper case void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) Console.Write(" " + c); Console.Write("\n"); } // Function to print the alphabet // in lower case void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) Console.Write(" " + c); Console.Write("\n"); } // Driver code public static void Main() { Console.WriteLine("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine("Lowercase Alphabets "); ob.lowercaseAlphabets(); }} // This code is contributed by Rajput-JiPHP<?php// PHP program to print alphabetfunction uppercaseAlphabets(){ // uppercase for ($c = ord('A'); $c <= ord('Z'); ++$c) echo(" ".chr($c)); echo("\n");}function lowercaseAlphabets(){ // lowercase for ($c = ord('a'); $c <= ord('z'); ++$c) echo(" ".chr($c)); echo("\n");} // Driver programecho("Uppercase Alphabets");uppercaseAlphabets(); echo "Lowercase Alphabets ";lowercaseAlphabets(); // This code is contributed by Code_MechOutput:Uppercase Alphabets
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Lowercase Alphabets
a b c d e f g h i j k l m n o p q r s t u v w x y z
For lowercase alphabets – Run a loop from ‘a’ to ‘z’
For uppercase characters – Run a loop from ‘A’ to ‘Z’
C++
C
Java
C#
PHP
// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (char c = 'a'; c <= 'z'; ++c) cout << c << " "; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (char c = 'A'; c <= 'Z'; ++c) cout << c << " "; cout << endl;} // Driver codeint main(){ cout << "Uppercase Alphabets" << endl; uppercaseAlphabets(ch); cout << "Lowercase Alphabets " << endl; lowercaseAlphabets(ch); return 0;}
// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (char c = 'a'; c <= 'z'; ++c) printf("%c ", c); printf("\n");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (char c = 'A'; c <= 'Z'; ++c) // print its ascii values printf("%c ", c); printf("\n");} // Driver programint main(){ printf("Uppercase Alphabets\n"); uppercaseAlphabets(); printf("Lowercase Alphabets\n"); lowercaseAlphabets(); return 0;}
// Java program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) System.out.print(" " + c); System.out.print("\n"); } void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) System.out.print(" " + c); System.out.print("\n"); } // Driver program public static void main(String[] args) { System.out.println("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println("Lowercase Alphabets "); ob.lowercaseAlphabets(); }}
// C# program to print alphabetusing System; public class Alpha { private int ch; // Function to print the alphabet // in upper case void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) Console.Write(" " + c); Console.Write("\n"); } // Function to print the alphabet // in lower case void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) Console.Write(" " + c); Console.Write("\n"); } // Driver code public static void Main() { Console.WriteLine("Uppercase Alphabets"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine("Lowercase Alphabets "); ob.lowercaseAlphabets(); }} // This code is contributed by Rajput-Ji
<?php// PHP program to print alphabetfunction uppercaseAlphabets(){ // uppercase for ($c = ord('A'); $c <= ord('Z'); ++$c) echo(" ".chr($c)); echo("\n");}function lowercaseAlphabets(){ // lowercase for ($c = ord('a'); $c <= ord('z'); ++$c) echo(" ".chr($c)); echo("\n");} // Driver programecho("Uppercase Alphabets");uppercaseAlphabets(); echo "Lowercase Alphabets ";lowercaseAlphabets(); // This code is contributed by Code_Mech
Uppercase Alphabets
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Lowercase Alphabets
a b c d e f g h i j k l m n o p q r s t u v w x y z
These programs print all alphabets in uppercase and lowercase continuously.
ukasp
Rajput-Ji
Mithun Kumar
Code_Mech
simmytarika5
ASCII
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Ternary Operator in Python
Difference between Abstract Class and Interface in Java
Destructors in C++
Inline Functions in C++
Exception Handling in C++
Pure Virtual Functions and Abstract Classes in C++
Python Exception Handling
'this' pointer in C++
|
[
{
"code": null,
"e": 23840,
"s": 23812,
"text": "\n05 Sep, 2021"
},
{
"code": null,
"e": 24053,
"s": 23840,
"text": "Alphabets in lowercase and uppercase can be printed using two methods, first is using ASCII values and second is to directly print values from ‘A’ to ‘Z’ using loops. Below are the implementation of both methods:"
},
{
"code": null,
"e": 28066,
"s": 24053,
"text": "Using ASCII values:ASCII value of uppercase alphabets – 65 to 90.ASCII value of lowercase alphabets – 97 to 122.C++CJavaPython3C#PHPC++// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (int c = 97; c <= 122; ++c) cout << c << \" \"; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (int c = 65; c <= 90; ++c) cout << c << \" \"; cout << endl;} // Driver codeint main(){ cout << \"Uppercase Alphabets\" << endl; uppercaseAlphabets(ch); cout << \"Lowercase Alphabets \" << endl; lowercaseAlphabets(ch); return 0;}C// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (int c = 97; c <= 122; ++c) printf(\"%c \", c); printf(\"\\n\");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (int c = 65; c <= 90; ++c) // print its ascii values printf(\"%c \", c); printf(\"\\n\");} // Driver programint main(){ printf(\"Uppercase Alphabets\\n\"); uppercaseAlphabets(); printf(\"Lowercase Alphabets\\n\"); lowercaseAlphabets(); return 0;}Java// JAVA program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } // Driver program public static void main(String[] args) { int ch; System.out.println(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }}Python3# Python3 program to print alphabets # Function to print the alphabet# in lower casedef lowercaseAlphabets(): # lowercase for c in range(97, 123): print(chr(c), end = \" \"); print(\"\"); # Function to print the alphabet# in upper casedef uppercaseAlphabets(): # uppercase for c in range(65, 91): print(chr(c), end = \" \"); print(\"\"); # Driver codeprint(\"Uppercase Alphabets\");uppercaseAlphabets(); print(\"Lowercase Alphabets \");lowercaseAlphabets(); # This code is contributed by mitsC#// C# program to print alphabet using System;class Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) Console.Write(\" \" + (char)c); Console.Write(\"\\n\"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) Console.Write(\" \" + (char)c); Console.Write(\"\\n\"); } // Driver program public static void Main() { int ch; Console.WriteLine(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }}PHP<?php// PHP program to print alphabets // Function to print the alphabet// in lower casefunction lowercaseAlphabets(){ // lowercase for ($c = 97; $c <= 122; ++$c) echo chr($c).\" \"; echo \"\\n\";} // Function to print the alphabet// in upper casefunction uppercaseAlphabets(){ // uppercase for ($c = 65; $c <= 90; ++$c) echo chr($c).\" \"; echo \"\\n\";} // Driver code echo \"Uppercase Alphabets\\n\"; uppercaseAlphabets(); echo \"Lowercase Alphabets \\n\"; lowercaseAlphabets(); // This code is contributed by mits?>Output:Uppercase Alphabets\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z \nLowercase Alphabets\na b c d e f g h i j k l m n o p q r s t u v w x y z \n"
},
{
"code": null,
"e": 28113,
"s": 28066,
"text": "ASCII value of uppercase alphabets – 65 to 90."
},
{
"code": null,
"e": 28161,
"s": 28113,
"text": "ASCII value of lowercase alphabets – 97 to 122."
},
{
"code": null,
"e": 28165,
"s": 28161,
"text": "C++"
},
{
"code": null,
"e": 28167,
"s": 28165,
"text": "C"
},
{
"code": null,
"e": 28172,
"s": 28167,
"text": "Java"
},
{
"code": null,
"e": 28180,
"s": 28172,
"text": "Python3"
},
{
"code": null,
"e": 28183,
"s": 28180,
"text": "C#"
},
{
"code": null,
"e": 28187,
"s": 28183,
"text": "PHP"
},
{
"code": "// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (int c = 97; c <= 122; ++c) cout << c << \" \"; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (int c = 65; c <= 90; ++c) cout << c << \" \"; cout << endl;} // Driver codeint main(){ cout << \"Uppercase Alphabets\" << endl; uppercaseAlphabets(ch); cout << \"Lowercase Alphabets \" << endl; lowercaseAlphabets(ch); return 0;}",
"e": 28793,
"s": 28187,
"text": null
},
{
"code": "// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (int c = 97; c <= 122; ++c) printf(\"%c \", c); printf(\"\\n\");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (int c = 65; c <= 90; ++c) // print its ascii values printf(\"%c \", c); printf(\"\\n\");} // Driver programint main(){ printf(\"Uppercase Alphabets\\n\"); uppercaseAlphabets(); printf(\"Lowercase Alphabets\\n\"); lowercaseAlphabets(); return 0;}",
"e": 29412,
"s": 28793,
"text": null
},
{
"code": "// JAVA program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } // Driver program public static void main(String[] args) { int ch; System.out.println(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }}",
"e": 30110,
"s": 29412,
"text": null
},
{
"code": "# Python3 program to print alphabets # Function to print the alphabet# in lower casedef lowercaseAlphabets(): # lowercase for c in range(97, 123): print(chr(c), end = \" \"); print(\"\"); # Function to print the alphabet# in upper casedef uppercaseAlphabets(): # uppercase for c in range(65, 91): print(chr(c), end = \" \"); print(\"\"); # Driver codeprint(\"Uppercase Alphabets\");uppercaseAlphabets(); print(\"Lowercase Alphabets \");lowercaseAlphabets(); # This code is contributed by mits",
"e": 30636,
"s": 30110,
"text": null
},
{
"code": "// C# program to print alphabet using System;class Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (int c = 65; c <= 90; ++c) Console.Write(\" \" + (char)c); Console.Write(\"\\n\"); } void lowercaseAlphabets() { // lowercase for (int c = 97; c <= 122; ++c) Console.Write(\" \" + (char)c); Console.Write(\"\\n\"); } // Driver program public static void Main() { int ch; Console.WriteLine(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }}",
"e": 31332,
"s": 30636,
"text": null
},
{
"code": "<?php// PHP program to print alphabets // Function to print the alphabet// in lower casefunction lowercaseAlphabets(){ // lowercase for ($c = 97; $c <= 122; ++$c) echo chr($c).\" \"; echo \"\\n\";} // Function to print the alphabet// in upper casefunction uppercaseAlphabets(){ // uppercase for ($c = 65; $c <= 90; ++$c) echo chr($c).\" \"; echo \"\\n\";} // Driver code echo \"Uppercase Alphabets\\n\"; uppercaseAlphabets(); echo \"Lowercase Alphabets \\n\"; lowercaseAlphabets(); // This code is contributed by mits?>",
"e": 31900,
"s": 31332,
"text": null
},
{
"code": null,
"e": 32047,
"s": 31900,
"text": "Uppercase Alphabets\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z \nLowercase Alphabets\na b c d e f g h i j k l m n o p q r s t u v w x y z \n"
},
{
"code": null,
"e": 35590,
"s": 32047,
"text": "Using alphabets directly i.e.For lowercase alphabets – Run a loop from ‘a’ to ‘z’For uppercase characters – Run a loop from ‘A’ to ‘Z’C++CJavaC#PHPC++// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (char c = 'a'; c <= 'z'; ++c) cout << c << \" \"; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (char c = 'A'; c <= 'Z'; ++c) cout << c << \" \"; cout << endl;} // Driver codeint main(){ cout << \"Uppercase Alphabets\" << endl; uppercaseAlphabets(ch); cout << \"Lowercase Alphabets \" << endl; lowercaseAlphabets(ch); return 0;}C// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (char c = 'a'; c <= 'z'; ++c) printf(\"%c \", c); printf(\"\\n\");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (char c = 'A'; c <= 'Z'; ++c) // print its ascii values printf(\"%c \", c); printf(\"\\n\");} // Driver programint main(){ printf(\"Uppercase Alphabets\\n\"); uppercaseAlphabets(); printf(\"Lowercase Alphabets\\n\"); lowercaseAlphabets(); return 0;}Java// Java program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } // Driver program public static void main(String[] args) { System.out.println(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }}C#// C# program to print alphabetusing System; public class Alpha { private int ch; // Function to print the alphabet // in upper case void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) Console.Write(\" \" + c); Console.Write(\"\\n\"); } // Function to print the alphabet // in lower case void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) Console.Write(\" \" + c); Console.Write(\"\\n\"); } // Driver code public static void Main() { Console.WriteLine(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }} // This code is contributed by Rajput-JiPHP<?php// PHP program to print alphabetfunction uppercaseAlphabets(){ // uppercase for ($c = ord('A'); $c <= ord('Z'); ++$c) echo(\" \".chr($c)); echo(\"\\n\");}function lowercaseAlphabets(){ // lowercase for ($c = ord('a'); $c <= ord('z'); ++$c) echo(\" \".chr($c)); echo(\"\\n\");} // Driver programecho(\"Uppercase Alphabets\");uppercaseAlphabets(); echo \"Lowercase Alphabets \";lowercaseAlphabets(); // This code is contributed by Code_MechOutput:Uppercase Alphabets\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z \nLowercase Alphabets\na b c d e f g h i j k l m n o p q r s t u v w x y z \n"
},
{
"code": null,
"e": 35643,
"s": 35590,
"text": "For lowercase alphabets – Run a loop from ‘a’ to ‘z’"
},
{
"code": null,
"e": 35697,
"s": 35643,
"text": "For uppercase characters – Run a loop from ‘A’ to ‘Z’"
},
{
"code": null,
"e": 35701,
"s": 35697,
"text": "C++"
},
{
"code": null,
"e": 35703,
"s": 35701,
"text": "C"
},
{
"code": null,
"e": 35708,
"s": 35703,
"text": "Java"
},
{
"code": null,
"e": 35711,
"s": 35708,
"text": "C#"
},
{
"code": null,
"e": 35715,
"s": 35711,
"text": "PHP"
},
{
"code": "// C++ program to print alphabets#include <iostream>using namespace std; // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // lowercase for (char c = 'a'; c <= 'z'; ++c) cout << c << \" \"; cout << endl;}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // uppercase for (char c = 'A'; c <= 'Z'; ++c) cout << c << \" \"; cout << endl;} // Driver codeint main(){ cout << \"Uppercase Alphabets\" << endl; uppercaseAlphabets(ch); cout << \"Lowercase Alphabets \" << endl; lowercaseAlphabets(ch); return 0;}",
"e": 36326,
"s": 35715,
"text": null
},
{
"code": "// C program to print alphabets#include <stdio.h> // Function to print the alphabet// in lower casevoid lowercaseAlphabets(){ // for lowercase for (char c = 'a'; c <= 'z'; ++c) printf(\"%c \", c); printf(\"\\n\");}// Function to print the alphabet// in upper casevoid uppercaseAlphabets(){ // Run a loop from 65 to 90 for (char c = 'A'; c <= 'Z'; ++c) // print its ascii values printf(\"%c \", c); printf(\"\\n\");} // Driver programint main(){ printf(\"Uppercase Alphabets\\n\"); uppercaseAlphabets(); printf(\"Lowercase Alphabets\\n\"); lowercaseAlphabets(); return 0;}",
"e": 36950,
"s": 36326,
"text": null
},
{
"code": "// Java program to print alphabetclass Alpha { private int ch; void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) System.out.print(\" \" + c); System.out.print(\"\\n\"); } // Driver program public static void main(String[] args) { System.out.println(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); System.out.println(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }}",
"e": 37640,
"s": 36950,
"text": null
},
{
"code": "// C# program to print alphabetusing System; public class Alpha { private int ch; // Function to print the alphabet // in upper case void uppercaseAlphabets() { // uppercase for (char c = 'A'; c <= 'Z'; ++c) Console.Write(\" \" + c); Console.Write(\"\\n\"); } // Function to print the alphabet // in lower case void lowercaseAlphabets() { // lowercase for (char c = 'a'; c <= 'z'; ++c) Console.Write(\" \" + c); Console.Write(\"\\n\"); } // Driver code public static void Main() { Console.WriteLine(\"Uppercase Alphabets\"); Alpha ob = new Alpha(); ob.uppercaseAlphabets(); Console.WriteLine(\"Lowercase Alphabets \"); ob.lowercaseAlphabets(); }} // This code is contributed by Rajput-Ji",
"e": 38476,
"s": 37640,
"text": null
},
{
"code": "<?php// PHP program to print alphabetfunction uppercaseAlphabets(){ // uppercase for ($c = ord('A'); $c <= ord('Z'); ++$c) echo(\" \".chr($c)); echo(\"\\n\");}function lowercaseAlphabets(){ // lowercase for ($c = ord('a'); $c <= ord('z'); ++$c) echo(\" \".chr($c)); echo(\"\\n\");} // Driver programecho(\"Uppercase Alphabets\");uppercaseAlphabets(); echo \"Lowercase Alphabets \";lowercaseAlphabets(); // This code is contributed by Code_Mech",
"e": 38949,
"s": 38476,
"text": null
},
{
"code": null,
"e": 39096,
"s": 38949,
"text": "Uppercase Alphabets\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z \nLowercase Alphabets\na b c d e f g h i j k l m n o p q r s t u v w x y z \n"
},
{
"code": null,
"e": 39172,
"s": 39096,
"text": "These programs print all alphabets in uppercase and lowercase continuously."
},
{
"code": null,
"e": 39178,
"s": 39172,
"text": "ukasp"
},
{
"code": null,
"e": 39188,
"s": 39178,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39201,
"s": 39188,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 39211,
"s": 39201,
"text": "Code_Mech"
},
{
"code": null,
"e": 39224,
"s": 39211,
"text": "simmytarika5"
},
{
"code": null,
"e": 39230,
"s": 39224,
"text": "ASCII"
},
{
"code": null,
"e": 39249,
"s": 39230,
"text": "School Programming"
},
{
"code": null,
"e": 39347,
"s": 39249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39356,
"s": 39347,
"text": "Comments"
},
{
"code": null,
"e": 39369,
"s": 39356,
"text": "Old Comments"
},
{
"code": null,
"e": 39390,
"s": 39369,
"text": "Constructors in Java"
},
{
"code": null,
"e": 39409,
"s": 39390,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 39436,
"s": 39409,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 39492,
"s": 39436,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 39511,
"s": 39492,
"text": "Destructors in C++"
},
{
"code": null,
"e": 39535,
"s": 39511,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 39561,
"s": 39535,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 39612,
"s": 39561,
"text": "Pure Virtual Functions and Abstract Classes in C++"
},
{
"code": null,
"e": 39638,
"s": 39612,
"text": "Python Exception Handling"
}
] |
uniq Command in LINUX with examples - GeeksforGeeks
|
22 Dec, 2021
The uniq command in Linux is a command-line utility that reports or filters out the repeated lines in a file. In simple words, uniq is the tool that helps to detect the adjacent duplicate lines and also deletes the duplicate lines. uniq filters out the adjacent matching lines from the input file(that is required as an argument) and writes the filtered data to the output file.
Syntax of uniq Command :
//...syntax of uniq...//
$uniq [OPTION] [INPUT[OUTPUT]]
The syntax of this is quite easy to understand. Here, INPUT refers to the input file in which repeated lines need to be filtered out and if INPUT isn’t specified then uniq reads from the standard input. OUTPUT refers to the output file in which you can store the filtered output generated by uniq command and as in the case of INPUT if OUTPUT isn’t specified then uniq writes to the standard output.
Now, let’s understand the use of this with the help of an example. Suppose you have a text file named kt.txt which contains repeated lines that needs to be omitted. This can simply be done with uniq.
//displaying contents of kt.txt//
$cat kt.txt
I love music.
I love music.
I love music.
I love music of Kartik.
I love music of Kartik.
Thanks.
Now, as we can see that the above file contains multiple duplicate lines. Now, lets’ use uniq command to remove them:
//...using uniq command.../
$uniq kt.txt
I love music.
I love music of Kartik.
Thanks.
/* with the use of uniq all
the repeated lines are removed*/
As you can see that we just used the name of the input file in the above uniq example and as we didn’t use any output file to store the produced output, the uniq command displayed the filtered output on the standard output with all the duplicate lines removed.
Note: uniq isn’t able to detect the duplicate lines unless they are adjacent to each other. The content in the file must be therefore sorted before using uniq or you can simply use sort -u instead of uniq command.
Options For uniq Command:
-c – -count : It tells how many times a line was repeated by displaying a number as a prefix with the line.
-d – -repeated : It only prints the repeated lines and not the lines which aren’t repeated.
-D – -all-repeated[=METHOD] : It prints all duplicate lines and METHOD can be any of the following:
none : Do not delimit duplicate lines at all. This is the default.
prepend : Insert a blank line before each set of duplicated lines.
separate : Insert a blank line between each set of duplicated lines.
-f N – -skip-fields(N) : It allows you to skip N fields(a field is a group of characters, delimited by whitespace) of a line before determining the uniqueness of a line.
-i – -ignore case : By default, comparisons done are case sensitive but with this option case insensitive comparisons can be made.
-s N – -skip-chars(N) : It doesn’t compare the first N characters of each line while determining uniqueness. This is like the -f option, but it skips individual characters rather than fields.
-u – -unique : It allows you to print only unique lines.
-z – -zero-terminated : It will make a line end with 0 bytes (NULL), instead of a newline.
-w N – -check-chars(N) : It only compares N characters in a line.
– – help : It displays a help message and exit.
– – version : It displays version information and exit.
-c – -count : It tells how many times a line was repeated by displaying a number as a prefix with the line.
-d – -repeated : It only prints the repeated lines and not the lines which aren’t repeated.
-D – -all-repeated[=METHOD] : It prints all duplicate lines and METHOD can be any of the following:
none : Do not delimit duplicate lines at all. This is the default.
prepend : Insert a blank line before each set of duplicated lines.
separate : Insert a blank line between each set of duplicated lines.
none : Do not delimit duplicate lines at all. This is the default.
prepend : Insert a blank line before each set of duplicated lines.
separate : Insert a blank line between each set of duplicated lines.
-f N – -skip-fields(N) : It allows you to skip N fields(a field is a group of characters, delimited by whitespace) of a line before determining the uniqueness of a line.
-i – -ignore case : By default, comparisons done are case sensitive but with this option case insensitive comparisons can be made.
-s N – -skip-chars(N) : It doesn’t compare the first N characters of each line while determining uniqueness. This is like the -f option, but it skips individual characters rather than fields.
-u – -unique : It allows you to print only unique lines.
-z – -zero-terminated : It will make a line end with 0 bytes (NULL), instead of a newline.
-w N – -check-chars(N) : It only compares N characters in a line.
– – help : It displays a help message and exit.
– – version : It displays version information and exit.
Examples of uniq with Options
1. Using -c option : It tells the number of times a line was repeated.
//using uniq with -c//
$uniq -c kt.txt
3 I love music.
1
2 I love music of Kartik.
1
1 Thanks.
/*at the starting of each
line its repeated number is
displayed*/
2. Using -d option : It only prints the repeated lines.
//using uniq with -d//
$uniq -d kt.txt
I love music.
I love music of Kartik.
/*it only displayed one
duplicate line per group*/
3. Using -D option : It also prints only duplicate lines but not one per group.
//using -D option//
$uniq -D kt.txt
I love music.
I love music.
I love music.
I love music of Kartik.
I love music of Kartik.
/* all the duplicate lines
are displayed*/
4. Using -u option : It prints only the unique lines.
//using -u option//
$uniq -u kt.txt
Thanks.
/*only unique lines are
displayed*/
5. Using -f N option : As told above, this allows the N fields to be skipped while comparing the uniqueness of the lines. This option is helpful when the lines are numbered as shown in the example below:
//displaying contents of f1.txt//
$cat f1.txt
1. I love music.
2. I love music.
3. I love music of Kartik.
4. I love music of Kartik.
//now using uniq with -f N option//
$uniq -f 2 f1.txt
1. I love music.
3. I love music of Kartik.
/*2 is used cause we needed to
compare the lines after the
numbering 1,2.. and after dots*/
6. Using -s N option : This is similar to -f N option but it skips N characters but not N fields.
//displaying content of f2.txt//
$cat f2.txt
#%@I love music.
^&(I love music.
*-!@thanks.
#%@!thanks.
//now using -s N option//
$uniq -s 3 f2.txt
#%@I love music.
*-!@thanks.
#%@!thanks.
/*lines same after skipping
3 characters are filtered*/
7. Using -w option : Similar to the way of skipping characters, we can also ask uniq to limit the comparison to a set number of characters. For this, -w command-line option is used.
//displaying content of f3.txt//
$cat f3.txt
How it is possible?
How it can be done?
How to use it?
//now using -w option//
$uniq -w 3 f3.txt
How
/*as the first 3 characters
of all the 3 lines are same
that's why uniq treated all these
as duplicates and gave output
accordingly*/
8. Using -i option : It is used to make the comparison case-insensitive.
//displaying contents of f4.txt//
$cat f4.txt
I LOVE MUSIC
i love music
THANKS
//using uniq command//
$uniq f4.txt
I LOVE MUSIC
i love music
THANKS
/*the lines aren't treated
as duplicates with simple
use of uniq*/
//now using -i option//
$uniq -i f4.txt
I LOVE MUSIC
THANKS
/*now second line is removed
when -i option is used*/
9. Using -z option : By default, the output uniq produces is newline terminated. However, if you want, you want to have a NULL terminated output instead (useful while dealing with uniq in scripts). This can be made possible using the -z command line option.
Syntax:
//syntax of using uniq
with -z option//
$uniq -z file-name
YouTubeGeeksforGeeks500K subscribersLinux Tutorials | uniq command | 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 / 4:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=k2k1LaKsAWI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L
roshangfg
meetgor
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
tee command in Linux with examples
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
Thread functions in C/C++
|
[
{
"code": null,
"e": 23952,
"s": 23921,
"text": " \n22 Dec, 2021\n"
},
{
"code": null,
"e": 24332,
"s": 23952,
"text": "The uniq command in Linux is a command-line utility that reports or filters out the repeated lines in a file. In simple words, uniq is the tool that helps to detect the adjacent duplicate lines and also deletes the duplicate lines. uniq filters out the adjacent matching lines from the input file(that is required as an argument) and writes the filtered data to the output file. "
},
{
"code": null,
"e": 24359,
"s": 24332,
"text": "Syntax of uniq Command : "
},
{
"code": null,
"e": 24417,
"s": 24359,
"text": " //...syntax of uniq...// \n$uniq [OPTION] [INPUT[OUTPUT]]"
},
{
"code": null,
"e": 24818,
"s": 24417,
"text": "The syntax of this is quite easy to understand. Here, INPUT refers to the input file in which repeated lines need to be filtered out and if INPUT isn’t specified then uniq reads from the standard input. OUTPUT refers to the output file in which you can store the filtered output generated by uniq command and as in the case of INPUT if OUTPUT isn’t specified then uniq writes to the standard output. "
},
{
"code": null,
"e": 25019,
"s": 24818,
"text": "Now, let’s understand the use of this with the help of an example. Suppose you have a text file named kt.txt which contains repeated lines that needs to be omitted. This can simply be done with uniq. "
},
{
"code": null,
"e": 25168,
"s": 25021,
"text": "//displaying contents of kt.txt//\n\n$cat kt.txt\nI love music.\nI love music.\nI love music.\n\nI love music of Kartik.\nI love music of Kartik.\n\nThanks."
},
{
"code": null,
"e": 25288,
"s": 25168,
"text": "Now, as we can see that the above file contains multiple duplicate lines. Now, lets’ use uniq command to remove them: "
},
{
"code": null,
"e": 25440,
"s": 25288,
"text": "//...using uniq command.../\n\n$uniq kt.txt\nI love music.\n\nI love music of Kartik.\n\nThanks.\n\n/* with the use of uniq all\nthe repeated lines are removed*/"
},
{
"code": null,
"e": 25702,
"s": 25440,
"text": "As you can see that we just used the name of the input file in the above uniq example and as we didn’t use any output file to store the produced output, the uniq command displayed the filtered output on the standard output with all the duplicate lines removed. "
},
{
"code": null,
"e": 25917,
"s": 25702,
"text": "Note: uniq isn’t able to detect the duplicate lines unless they are adjacent to each other. The content in the file must be therefore sorted before using uniq or you can simply use sort -u instead of uniq command. "
},
{
"code": null,
"e": 25945,
"s": 25917,
"text": "Options For uniq Command: "
},
{
"code": null,
"e": 27265,
"s": 25945,
"text": "\n-c – -count : It tells how many times a line was repeated by displaying a number as a prefix with the line.\n-d – -repeated : It only prints the repeated lines and not the lines which aren’t repeated.\n-D – -all-repeated[=METHOD] : It prints all duplicate lines and METHOD can be any of the following: \n\nnone : Do not delimit duplicate lines at all. This is the default.\nprepend : Insert a blank line before each set of duplicated lines.\nseparate : Insert a blank line between each set of duplicated lines.\n\n\n-f N – -skip-fields(N) : It allows you to skip N fields(a field is a group of characters, delimited by whitespace) of a line before determining the uniqueness of a line.\n-i – -ignore case : By default, comparisons done are case sensitive but with this option case insensitive comparisons can be made.\n-s N – -skip-chars(N) : It doesn’t compare the first N characters of each line while determining uniqueness. This is like the -f option, but it skips individual characters rather than fields.\n-u – -unique : It allows you to print only unique lines.\n-z – -zero-terminated : It will make a line end with 0 bytes (NULL), instead of a newline.\n-w N – -check-chars(N) : It only compares N characters in a line.\n– – help : It displays a help message and exit.\n– – version : It displays version information and exit.\n"
},
{
"code": null,
"e": 27373,
"s": 27265,
"text": "-c – -count : It tells how many times a line was repeated by displaying a number as a prefix with the line."
},
{
"code": null,
"e": 27465,
"s": 27373,
"text": "-d – -repeated : It only prints the repeated lines and not the lines which aren’t repeated."
},
{
"code": null,
"e": 27772,
"s": 27465,
"text": "-D – -all-repeated[=METHOD] : It prints all duplicate lines and METHOD can be any of the following: \n\nnone : Do not delimit duplicate lines at all. This is the default.\nprepend : Insert a blank line before each set of duplicated lines.\nseparate : Insert a blank line between each set of duplicated lines.\n\n"
},
{
"code": null,
"e": 27839,
"s": 27772,
"text": "none : Do not delimit duplicate lines at all. This is the default."
},
{
"code": null,
"e": 27906,
"s": 27839,
"text": "prepend : Insert a blank line before each set of duplicated lines."
},
{
"code": null,
"e": 27975,
"s": 27906,
"text": "separate : Insert a blank line between each set of duplicated lines."
},
{
"code": null,
"e": 28145,
"s": 27975,
"text": "-f N – -skip-fields(N) : It allows you to skip N fields(a field is a group of characters, delimited by whitespace) of a line before determining the uniqueness of a line."
},
{
"code": null,
"e": 28276,
"s": 28145,
"text": "-i – -ignore case : By default, comparisons done are case sensitive but with this option case insensitive comparisons can be made."
},
{
"code": null,
"e": 28468,
"s": 28276,
"text": "-s N – -skip-chars(N) : It doesn’t compare the first N characters of each line while determining uniqueness. This is like the -f option, but it skips individual characters rather than fields."
},
{
"code": null,
"e": 28525,
"s": 28468,
"text": "-u – -unique : It allows you to print only unique lines."
},
{
"code": null,
"e": 28616,
"s": 28525,
"text": "-z – -zero-terminated : It will make a line end with 0 bytes (NULL), instead of a newline."
},
{
"code": null,
"e": 28682,
"s": 28616,
"text": "-w N – -check-chars(N) : It only compares N characters in a line."
},
{
"code": null,
"e": 28730,
"s": 28682,
"text": "– – help : It displays a help message and exit."
},
{
"code": null,
"e": 28786,
"s": 28730,
"text": "– – version : It displays version information and exit."
},
{
"code": null,
"e": 28818,
"s": 28788,
"text": "Examples of uniq with Options"
},
{
"code": null,
"e": 28890,
"s": 28818,
"text": "1. Using -c option : It tells the number of times a line was repeated. "
},
{
"code": null,
"e": 29056,
"s": 28892,
"text": "//using uniq with -c//\n\n$uniq -c kt.txt\n3 I love music.\n1\n2 I love music of Kartik.\n1\n1 Thanks.\n\n/*at the starting of each \nline its repeated number is\ndisplayed*/"
},
{
"code": null,
"e": 29246,
"s": 29058,
"text": "2. Using -d option : It only prints the repeated lines.\n\n//using uniq with -d//\n\n$uniq -d kt.txt\nI love music.\nI love music of Kartik.\n\n/*it only displayed one\n duplicate line per group*/"
},
{
"code": null,
"e": 29327,
"s": 29246,
"text": "3. Using -D option : It also prints only duplicate lines but not one per group. "
},
{
"code": null,
"e": 29501,
"s": 29329,
"text": "//using -D option//\n\n$uniq -D kt.txt\nI love music.\nI love music.\nI love music.\nI love music of Kartik.\nI love music of Kartik.\n\n/* all the duplicate lines \nare displayed*/"
},
{
"code": null,
"e": 29556,
"s": 29501,
"text": "4. Using -u option : It prints only the unique lines. "
},
{
"code": null,
"e": 29640,
"s": 29558,
"text": "//using -u option//\n\n$uniq -u kt.txt\nThanks.\n\n/*only unique lines are\ndisplayed*/"
},
{
"code": null,
"e": 29845,
"s": 29640,
"text": "5. Using -f N option : As told above, this allows the N fields to be skipped while comparing the uniqueness of the lines. This option is helpful when the lines are numbered as shown in the example below: "
},
{
"code": null,
"e": 30175,
"s": 29847,
"text": "//displaying contents of f1.txt//\n\n$cat f1.txt\n1. I love music.\n2. I love music.\n3. I love music of Kartik.\n4. I love music of Kartik.\n\n//now using uniq with -f N option//\n\n$uniq -f 2 f1.txt\n1. I love music.\n3. I love music of Kartik.\n\n/*2 is used cause we needed to\ncompare the lines after the\nnumbering 1,2.. and after dots*/"
},
{
"code": null,
"e": 30274,
"s": 30175,
"text": "6. Using -s N option : This is similar to -f N option but it skips N characters but not N fields. "
},
{
"code": null,
"e": 30524,
"s": 30276,
"text": "//displaying content of f2.txt//\n\n$cat f2.txt\n#%@I love music.\n^&(I love music.\n*-!@thanks.\n#%@!thanks.\n\n//now using -s N option//\n\n$uniq -s 3 f2.txt\n#%@I love music.\n*-!@thanks.\n#%@!thanks.\n\n/*lines same after skipping\n3 characters are filtered*/"
},
{
"code": null,
"e": 30707,
"s": 30524,
"text": "7. Using -w option : Similar to the way of skipping characters, we can also ask uniq to limit the comparison to a set number of characters. For this, -w command-line option is used. "
},
{
"code": null,
"e": 30994,
"s": 30709,
"text": "//displaying content of f3.txt//\n\n$cat f3.txt\nHow it is possible?\nHow it can be done?\nHow to use it?\n\n//now using -w option//\n\n$uniq -w 3 f3.txt\nHow\n\n/*as the first 3 characters\nof all the 3 lines are same\nthat's why uniq treated all these\nas duplicates and gave output \naccordingly*/"
},
{
"code": null,
"e": 31068,
"s": 30994,
"text": "8. Using -i option : It is used to make the comparison case-insensitive. "
},
{
"code": null,
"e": 31406,
"s": 31070,
"text": "//displaying contents of f4.txt//\n\n$cat f4.txt\nI LOVE MUSIC\ni love music\nTHANKS\n\n//using uniq command//\n$uniq f4.txt\nI LOVE MUSIC\ni love music\nTHANKS\n\n/*the lines aren't treated\nas duplicates with simple \nuse of uniq*/\n\n//now using -i option//\n\n$uniq -i f4.txt\nI LOVE MUSIC\nTHANKS\n\n/*now second line is removed\nwhen -i option is used*/"
},
{
"code": null,
"e": 31665,
"s": 31406,
"text": "9. Using -z option : By default, the output uniq produces is newline terminated. However, if you want, you want to have a NULL terminated output instead (useful while dealing with uniq in scripts). This can be made possible using the -z command line option. "
},
{
"code": null,
"e": 31675,
"s": 31665,
"text": "Syntax: "
},
{
"code": null,
"e": 31735,
"s": 31675,
"text": "//syntax of using uniq\nwith -z option//\n\n$uniq -z file-name"
},
{
"code": null,
"e": 32566,
"s": 31737,
"text": "YouTubeGeeksforGeeks500K subscribersLinux Tutorials | uniq command | 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 / 4:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=k2k1LaKsAWI\" 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": 32608,
"s": 32566,
"text": "?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L "
},
{
"code": null,
"e": 32620,
"s": 32610,
"text": "roshangfg"
},
{
"code": null,
"e": 32628,
"s": 32620,
"text": "meetgor"
},
{
"code": null,
"e": 32644,
"s": 32628,
"text": "\nlinux-command\n"
},
{
"code": null,
"e": 32677,
"s": 32644,
"text": "\nLinux-text-processing-commands\n"
},
{
"code": null,
"e": 32690,
"s": 32677,
"text": "\nLinux-Unix\n"
},
{
"code": null,
"e": 32895,
"s": 32690,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 32930,
"s": 32895,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 32968,
"s": 32930,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 33006,
"s": 32968,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 33041,
"s": 33006,
"text": "tee command in Linux with examples"
},
{
"code": null,
"e": 33076,
"s": 33041,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 33112,
"s": 33076,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 33149,
"s": 33112,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 33185,
"s": 33149,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 33229,
"s": 33185,
"text": "Mutex lock for Linux Thread Synchronization"
}
] |
Online Javascript Minifier
|
Editable Javascript Code
123456789101112131415161718192021222324252627282930$('#input').click(function() { if ( $(this).val() == 'Type (or paste) your input here...' ) { $(this).val(''); }});$('#output').click(function() { if ( $(this).val() == 'Compressed output goes here...' ) { $(this).val(''); }});$("#Minify").click(function(event){ var inputText = $("#input").val(); var charsetText = $("#charset").val(); var formData = {input:"" + inputText + "", charset: "" + charsetText + ""}; $.ajax({ type: "POST", cache: false, url: "javascript_minify.php", data: formData, success: function(data) { $('#output').val( data ); } }); });X
Privacy Policy
Cookies Policy
Terms of Use
|
[
{
"code": null,
"e": 25,
"s": 0,
"text": "Editable Javascript Code"
},
{
"code": null,
"e": 754,
"s": 25,
"text": "123456789101112131415161718192021222324252627282930$('#input').click(function() { if ( $(this).val() == 'Type (or paste) your input here...' ) { $(this).val(''); }});$('#output').click(function() { if ( $(this).val() == 'Compressed output goes here...' ) { $(this).val(''); }});$(\"#Minify\").click(function(event){ var inputText = $(\"#input\").val(); var charsetText = $(\"#charset\").val(); var formData = {input:\"\" + inputText + \"\", charset: \"\" + charsetText + \"\"}; $.ajax({ type: \"POST\", cache: false, url: \"javascript_minify.php\", data: formData, success: function(data) { $('#output').val( data ); } }); });X"
},
{
"code": null,
"e": 769,
"s": 754,
"text": "Privacy Policy"
},
{
"code": null,
"e": 784,
"s": 769,
"text": "Cookies Policy"
}
] |
Python: The Boolean confusion. `if val` and `if val is not None` are... | by Akash Panchal | Towards Data Science
|
if valand if val is not None are not the same!
When you do if val is None, you call the operator is, which checks the identity of x. i.e, if val is value Here, is operator checks whether both the operands refer to the same object or not.
None is a singleton in Python and all None values are also the exact same instance.
when you say if val, python behaves differently. if expects a boolean, and assuming val is not a boolean, Python automatically calls val’s __bool__ a method.
if val is actually executed as if val.__bool__
The confusing thing is, that bool(None) returns False, so if val is None. This works as expected but there are other values that are evaluated as False.
The most important example is of an empty list. bool([]) returns False as well. Usually, an empty list has a different meaning thanNone; None means no value while an empty list means zero values. Semantically, they are different.
Here are some of the example for better understanding.
We will execute the following block of conditions against the different values:
if val: print('if val')if not val: print('if not val')if val is not None: print('if val is not None')if val is None: print('if val is None')
1. None
val = Noneif not valif val is None
2. [] (empty list)
val = []if not valif val is not None
3. [27, 37] (non-empty list)
val = [27, 37]if valif val is not None
4. 0 (number — zero)
val = 0if not valif val is not None
5. 1 (number — one/non-zero)
val = 1if valif val is not None
6. An Object
val = object()if valif val is not None
Interesting, right? Give it a try!
|
[
{
"code": null,
"e": 218,
"s": 171,
"text": "if valand if val is not None are not the same!"
},
{
"code": null,
"e": 409,
"s": 218,
"text": "When you do if val is None, you call the operator is, which checks the identity of x. i.e, if val is value Here, is operator checks whether both the operands refer to the same object or not."
},
{
"code": null,
"e": 493,
"s": 409,
"text": "None is a singleton in Python and all None values are also the exact same instance."
},
{
"code": null,
"e": 651,
"s": 493,
"text": "when you say if val, python behaves differently. if expects a boolean, and assuming val is not a boolean, Python automatically calls val’s __bool__ a method."
},
{
"code": null,
"e": 698,
"s": 651,
"text": "if val is actually executed as if val.__bool__"
},
{
"code": null,
"e": 851,
"s": 698,
"text": "The confusing thing is, that bool(None) returns False, so if val is None. This works as expected but there are other values that are evaluated as False."
},
{
"code": null,
"e": 1081,
"s": 851,
"text": "The most important example is of an empty list. bool([]) returns False as well. Usually, an empty list has a different meaning thanNone; None means no value while an empty list means zero values. Semantically, they are different."
},
{
"code": null,
"e": 1136,
"s": 1081,
"text": "Here are some of the example for better understanding."
},
{
"code": null,
"e": 1216,
"s": 1136,
"text": "We will execute the following block of conditions against the different values:"
},
{
"code": null,
"e": 1369,
"s": 1216,
"text": "if val: print('if val')if not val: print('if not val')if val is not None: print('if val is not None')if val is None: print('if val is None')"
},
{
"code": null,
"e": 1377,
"s": 1369,
"text": "1. None"
},
{
"code": null,
"e": 1412,
"s": 1377,
"text": "val = Noneif not valif val is None"
},
{
"code": null,
"e": 1431,
"s": 1412,
"text": "2. [] (empty list)"
},
{
"code": null,
"e": 1468,
"s": 1431,
"text": "val = []if not valif val is not None"
},
{
"code": null,
"e": 1497,
"s": 1468,
"text": "3. [27, 37] (non-empty list)"
},
{
"code": null,
"e": 1536,
"s": 1497,
"text": "val = [27, 37]if valif val is not None"
},
{
"code": null,
"e": 1557,
"s": 1536,
"text": "4. 0 (number — zero)"
},
{
"code": null,
"e": 1593,
"s": 1557,
"text": "val = 0if not valif val is not None"
},
{
"code": null,
"e": 1622,
"s": 1593,
"text": "5. 1 (number — one/non-zero)"
},
{
"code": null,
"e": 1654,
"s": 1622,
"text": "val = 1if valif val is not None"
},
{
"code": null,
"e": 1667,
"s": 1654,
"text": "6. An Object"
},
{
"code": null,
"e": 1706,
"s": 1667,
"text": "val = object()if valif val is not None"
}
] |
Big Data Analytics - Decision Trees
|
A Decision Tree is an algorithm used for supervised learning problems such as classification or regression. A decision tree or a classification tree is a tree in which each internal (nonleaf) node is labeled with an input feature. The arcs coming from a node labeled with a feature are labeled with each of the possible values of the feature. Each leaf of the tree is labeled with a class or a probability distribution over the classes.
A tree can be "learned" by splitting the source set into subsets based on an attribute value test. This process is repeated on each derived subset in a recursive manner called recursive partitioning. The recursion is completed when the subset at a node has all the same value of the target variable, or when splitting no longer adds value to the predictions. This process of top-down induction of decision trees is an example of a greedy algorithm, and it is the most common strategy for learning decision trees.
Decision trees used in data mining are of two main types −
Classification tree − when the response is a nominal variable, for example if an email is spam or not.
Classification tree − when the response is a nominal variable, for example if an email is spam or not.
Regression tree − when the predicted outcome can be considered a real number (e.g. the salary of a worker).
Regression tree − when the predicted outcome can be considered a real number (e.g. the salary of a worker).
Decision trees are a simple method, and as such has some problems. One of this issues is the high variance in the resulting models that decision trees produce. In order to alleviate this problem, ensemble methods of decision trees were developed. There are two groups of ensemble methods currently used extensively −
Bagging decision trees − These trees are used to build multiple decision trees by repeatedly resampling training data with replacement, and voting the trees for a consensus prediction. This algorithm has been called random forest.
Bagging decision trees − These trees are used to build multiple decision trees by repeatedly resampling training data with replacement, and voting the trees for a consensus prediction. This algorithm has been called random forest.
Boosting decision trees − Gradient boosting combines weak learners; in this case, decision trees into a single strong learner, in an iterative fashion. It fits a weak tree to the data and iteratively keeps fitting weak learners in order to correct the error of the previous model.
Boosting decision trees − Gradient boosting combines weak learners; in this case, decision trees into a single strong learner, in an iterative fashion. It fits a weak tree to the data and iteratively keeps fitting weak learners in order to correct the error of the previous model.
# Install the party package
# install.packages('party')
library(party)
library(ggplot2)
head(diamonds)
# We will predict the cut of diamonds using the features available in the
diamonds dataset.
ct = ctree(cut ~ ., data = diamonds)
# plot(ct, main="Conditional Inference Tree")
# Example output
# Response: cut
# Inputs: carat, color, clarity, depth, table, price, x, y, z
# Number of observations: 53940
#
# 1) table <= 57; criterion = 1, statistic = 10131.878
# 2) depth <= 63; criterion = 1, statistic = 8377.279
# 3) table <= 56.4; criterion = 1, statistic = 226.423
# 4) z <= 2.64; criterion = 1, statistic = 70.393
# 5) clarity <= VS1; criterion = 0.989, statistic = 10.48
# 6) color <= E; criterion = 0.997, statistic = 12.829
# 7)* weights = 82
# 6) color > E
#Table of prediction errors
table(predict(ct), diamonds$cut)
# Fair Good Very Good Premium Ideal
# Fair 1388 171 17 0 14
# Good 102 2912 499 26 27
# Very Good 54 998 3334 249 355
# Premium 44 711 5054 11915 1167
# Ideal 22 114 3178 1601 19988
# Estimated class probabilities
probs = predict(ct, newdata = diamonds, type = "prob")
probs = do.call(rbind, probs)
head(probs)
65 Lectures
6 hours
Arnab Chakraborty
18 Lectures
1.5 hours
Pranjal Srivastava, Harshit Srivastava
23 Lectures
2 hours
John Shea
18 Lectures
1.5 hours
Pranjal Srivastava
46 Lectures
3.5 hours
Pranjal Srivastava
37 Lectures
3.5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2991,
"s": 2554,
"text": "A Decision Tree is an algorithm used for supervised learning problems such as classification or regression. A decision tree or a classification tree is a tree in which each internal (nonleaf) node is labeled with an input feature. The arcs coming from a node labeled with a feature are labeled with each of the possible values of the feature. Each leaf of the tree is labeled with a class or a probability distribution over the classes."
},
{
"code": null,
"e": 3504,
"s": 2991,
"text": "A tree can be \"learned\" by splitting the source set into subsets based on an attribute value test. This process is repeated on each derived subset in a recursive manner called recursive partitioning. The recursion is completed when the subset at a node has all the same value of the target variable, or when splitting no longer adds value to the predictions. This process of top-down induction of decision trees is an example of a greedy algorithm, and it is the most common strategy for learning decision trees."
},
{
"code": null,
"e": 3563,
"s": 3504,
"text": "Decision trees used in data mining are of two main types −"
},
{
"code": null,
"e": 3666,
"s": 3563,
"text": "Classification tree − when the response is a nominal variable, for example if an email is spam or not."
},
{
"code": null,
"e": 3769,
"s": 3666,
"text": "Classification tree − when the response is a nominal variable, for example if an email is spam or not."
},
{
"code": null,
"e": 3877,
"s": 3769,
"text": "Regression tree − when the predicted outcome can be considered a real number (e.g. the salary of a worker)."
},
{
"code": null,
"e": 3985,
"s": 3877,
"text": "Regression tree − when the predicted outcome can be considered a real number (e.g. the salary of a worker)."
},
{
"code": null,
"e": 4302,
"s": 3985,
"text": "Decision trees are a simple method, and as such has some problems. One of this issues is the high variance in the resulting models that decision trees produce. In order to alleviate this problem, ensemble methods of decision trees were developed. There are two groups of ensemble methods currently used extensively −"
},
{
"code": null,
"e": 4533,
"s": 4302,
"text": "Bagging decision trees − These trees are used to build multiple decision trees by repeatedly resampling training data with replacement, and voting the trees for a consensus prediction. This algorithm has been called random forest."
},
{
"code": null,
"e": 4764,
"s": 4533,
"text": "Bagging decision trees − These trees are used to build multiple decision trees by repeatedly resampling training data with replacement, and voting the trees for a consensus prediction. This algorithm has been called random forest."
},
{
"code": null,
"e": 5045,
"s": 4764,
"text": "Boosting decision trees − Gradient boosting combines weak learners; in this case, decision trees into a single strong learner, in an iterative fashion. It fits a weak tree to the data and iteratively keeps fitting weak learners in order to correct the error of the previous model."
},
{
"code": null,
"e": 5326,
"s": 5045,
"text": "Boosting decision trees − Gradient boosting combines weak learners; in this case, decision trees into a single strong learner, in an iterative fashion. It fits a weak tree to the data and iteratively keeps fitting weak learners in order to correct the error of the previous model."
},
{
"code": null,
"e": 6672,
"s": 5326,
"text": "# Install the party package\n# install.packages('party') \nlibrary(party) \nlibrary(ggplot2) \n\nhead(diamonds) \n# We will predict the cut of diamonds using the features available in the \ndiamonds dataset. \nct = ctree(cut ~ ., data = diamonds) \n\n# plot(ct, main=\"Conditional Inference Tree\") \n# Example output \n# Response: cut \n# Inputs: carat, color, clarity, depth, table, price, x, y, z \n\n# Number of observations: 53940 \n# \n# 1) table <= 57; criterion = 1, statistic = 10131.878 \n# 2) depth <= 63; criterion = 1, statistic = 8377.279 \n# 3) table <= 56.4; criterion = 1, statistic = 226.423 \n# 4) z <= 2.64; criterion = 1, statistic = 70.393 \n# 5) clarity <= VS1; criterion = 0.989, statistic = 10.48 \n# 6) color <= E; criterion = 0.997, statistic = 12.829 \n# 7)* weights = 82 \n# 6) color > E \n\n#Table of prediction errors \ntable(predict(ct), diamonds$cut) \n# Fair Good Very Good Premium Ideal \n# Fair 1388 171 17 0 14 \n# Good 102 2912 499 26 27 \n# Very Good 54 998 3334 249 355 \n# Premium 44 711 5054 11915 1167 \n# Ideal 22 114 3178 1601 19988 \n# Estimated class probabilities \nprobs = predict(ct, newdata = diamonds, type = \"prob\") \nprobs = do.call(rbind, probs) \nhead(probs)\n"
},
{
"code": null,
"e": 6705,
"s": 6672,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6724,
"s": 6705,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6759,
"s": 6724,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6799,
"s": 6759,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 6832,
"s": 6799,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6843,
"s": 6832,
"text": " John Shea"
},
{
"code": null,
"e": 6878,
"s": 6843,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6898,
"s": 6878,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6933,
"s": 6898,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6953,
"s": 6933,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6988,
"s": 6953,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7028,
"s": 6988,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 7035,
"s": 7028,
"text": " Print"
},
{
"code": null,
"e": 7046,
"s": 7035,
"text": " Add Notes"
}
] |
Java Program to convert integer to octal
|
To convert integer to octal in Java, use the Integer.toOctalString() method.
Let’s say the following is our integer.
int val = 768;
Convert the above integer to octal.
Integer.toOctalString(val)
The following is the final example.
Live Demo
public class Demo {
public static void main(String[] args) {
int val = 768;
// integer
System.out.println("Integer: "+val);
// octal
System.out.println("Octal String = " + Integer.toOctalString(val));
}
}
Integer: 768
Octal String = 1400
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To convert integer to octal in Java, use the Integer.toOctalString() method."
},
{
"code": null,
"e": 1179,
"s": 1139,
"text": "Let’s say the following is our integer."
},
{
"code": null,
"e": 1194,
"s": 1179,
"text": "int val = 768;"
},
{
"code": null,
"e": 1230,
"s": 1194,
"text": "Convert the above integer to octal."
},
{
"code": null,
"e": 1257,
"s": 1230,
"text": "Integer.toOctalString(val)"
},
{
"code": null,
"e": 1293,
"s": 1257,
"text": "The following is the final example."
},
{
"code": null,
"e": 1304,
"s": 1293,
"text": " Live Demo"
},
{
"code": null,
"e": 1552,
"s": 1304,
"text": "public class Demo {\n public static void main(String[] args) {\n int val = 768;\n // integer\n System.out.println(\"Integer: \"+val);\n // octal\n System.out.println(\"Octal String = \" + Integer.toOctalString(val));\n }\n}"
},
{
"code": null,
"e": 1585,
"s": 1552,
"text": "Integer: 768\nOctal String = 1400"
}
] |
C# Enum Parse Method
|
The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.
The following is our enumeration.
enum Vehicle { Car, Bus, Truck, Motobike };
Now, use the GetNames() method in a loop to get the enum values. Parse them using the Enum.Parse() method as shown below −
Enum.Parse(typeof(Vehicle)
Live Demo
using System;
public class Demo {
enum Vehicle { Car, Bus, Truck, Motobike };
public static void Main() {
Console.WriteLine("The enumeration...");
foreach (string v in Enum.GetNames(typeof(Vehicle))) {
Console.WriteLine("{0} = {1:D}", v, Enum.Parse(typeof(Vehicle), v));
}
Console.WriteLine();
}
}
The enumeration...
Car = 0
Bus = 1
Truck = 2
Motobike = 3
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object."
},
{
"code": null,
"e": 1239,
"s": 1205,
"text": "The following is our enumeration."
},
{
"code": null,
"e": 1283,
"s": 1239,
"text": "enum Vehicle { Car, Bus, Truck, Motobike };"
},
{
"code": null,
"e": 1406,
"s": 1283,
"text": "Now, use the GetNames() method in a loop to get the enum values. Parse them using the Enum.Parse() method as shown below −"
},
{
"code": null,
"e": 1433,
"s": 1406,
"text": "Enum.Parse(typeof(Vehicle)"
},
{
"code": null,
"e": 1444,
"s": 1433,
"text": " Live Demo"
},
{
"code": null,
"e": 1784,
"s": 1444,
"text": "using System;\npublic class Demo {\n enum Vehicle { Car, Bus, Truck, Motobike };\n public static void Main() {\n Console.WriteLine(\"The enumeration...\");\n foreach (string v in Enum.GetNames(typeof(Vehicle))) {\n Console.WriteLine(\"{0} = {1:D}\", v, Enum.Parse(typeof(Vehicle), v));\n }\n Console.WriteLine();\n }\n}"
},
{
"code": null,
"e": 1842,
"s": 1784,
"text": "The enumeration...\nCar = 0\nBus = 1\nTruck = 2\nMotobike = 3"
}
] |
How to compute Average for the Set of Values using C#?
|
Firstly, set an array with values −
int[] myArr = new int[] {
34,
23,
77,
67
};
To get the average, firstly get the sum of array elements.
Divide the sum with the length of the array and that will give you the average of the elements −
int sum = 0;
int average = 0;
for (int i = 0; i < len; i++) {
sum += myArr[i];
}
average = sum / len;
The following is the complete code to get the array in C# −
Live Demo
using System;
public class Program {
public static void Main() {
int[] myArr = new int[] {
34,
23,
77,
67
};
int len = myArr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < len; i++) {
sum += myArr[i];
}
average = sum / len;
Console.WriteLine("Average = " + average);
}
}
Average = 50
|
[
{
"code": null,
"e": 1098,
"s": 1062,
"text": "Firstly, set an array with values −"
},
{
"code": null,
"e": 1154,
"s": 1098,
"text": "int[] myArr = new int[] {\n 34,\n 23,\n 77,\n 67\n};"
},
{
"code": null,
"e": 1213,
"s": 1154,
"text": "To get the average, firstly get the sum of array elements."
},
{
"code": null,
"e": 1310,
"s": 1213,
"text": "Divide the sum with the length of the array and that will give you the average of the elements −"
},
{
"code": null,
"e": 1415,
"s": 1310,
"text": "int sum = 0;\nint average = 0;\nfor (int i = 0; i < len; i++) {\n sum += myArr[i];\n}\naverage = sum / len;"
},
{
"code": null,
"e": 1475,
"s": 1415,
"text": "The following is the complete code to get the array in C# −"
},
{
"code": null,
"e": 1486,
"s": 1475,
"text": " Live Demo"
},
{
"code": null,
"e": 1873,
"s": 1486,
"text": "using System;\npublic class Program {\n public static void Main() {\n int[] myArr = new int[] {\n 34,\n 23,\n 77,\n 67\n };\n int len = myArr.Length;\n int sum = 0;\n int average = 0;\n for (int i = 0; i < len; i++) {\n sum += myArr[i];\n }\n average = sum / len;\n Console.WriteLine(\"Average = \" + average);\n }\n}"
},
{
"code": null,
"e": 1886,
"s": 1873,
"text": "Average = 50"
}
] |
CSS | font-display property - GeeksforGeeks
|
07 May, 2020
While using web fonts, the text will be invisible until either web font is loaded or three seconds are passed, at which point the fallback font is used.
Font-display allows customizing how web fonts are displayed when the page is being rendered.
It is applied using @font-face rule which defines custom fonts in a style sheet.
Syntax:
@font-face {
font-family: Sample;
src: url(samplefont.woff) format('woff'),
url(samplefontbold.woff) format('woff');
font-weight: normal;
font-style: normal;
font-display: optional;
}
Example:
<!DOCTYPE html><html><head> <title>CSS | font-display</title> <meta name='viewport' content="width=device-width, initial-scale=1"> <style> @font-face { font-family: Roboto; src: url(Roboto\Roboto-BoldItalic.ttf) format('truetype'); font-style: italic; font-weight: bold; font-display: block; } div{ font-family: Roboto; font-style: italic; font-weight:bold; }</style></head><body><h1>Usage of font-display</h1><div>Downloaded font</div><p>Normal font</p></body></html>
Output:
The downloaded font appears after a short span. Try running it on IDE to see it.
The font-display property timeline is divided into three periods:
Block
Swap
Failure
Block Period:The text will be invisible till web font hasn’t loaded, rendering is blocked in this period.
Swap Period:Originally the fallback font is used to render text, if web font is successfully loaded during the swap period, the fallback font is swapped with the web font.
Failure Period:At this point it is considered that loading is failed and the fallback font is to be used.
This property accepts the following values:
Auto (Initial value): At this value, the font-display technique is chosen by the browser. This is usually similar to Block value.
Block: It goes for a small block period and then goes into an infinite swap period so the rendering is allowed infinitely. In simpler form, it hides the text until web font is loaded.
Swap: At this value, the font-face is provided with minimal block period and an infinite swap period. It uses fallback font until web font is loaded
Fallback: It gives the font-face a minimal block period(100 ms) and a small swap period(about 3 seconds). It tries to load web font for a short period then goes into failure period and uses fallback font.
Optional: It gives the font-face a minimal block period and no swap period. It hides the text for a short time and then uses fallback font until web font is the custom font is available to use.
CSS-Properties
Picked
CSS
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n07 May, 2020"
},
{
"code": null,
"e": 25529,
"s": 25376,
"text": "While using web fonts, the text will be invisible until either web font is loaded or three seconds are passed, at which point the fallback font is used."
},
{
"code": null,
"e": 25622,
"s": 25529,
"text": "Font-display allows customizing how web fonts are displayed when the page is being rendered."
},
{
"code": null,
"e": 25703,
"s": 25622,
"text": "It is applied using @font-face rule which defines custom fonts in a style sheet."
},
{
"code": null,
"e": 25711,
"s": 25703,
"text": "Syntax:"
},
{
"code": null,
"e": 25912,
"s": 25711,
"text": "@font-face {\n font-family: Sample;\n src: url(samplefont.woff) format('woff'),\n url(samplefontbold.woff) format('woff');\n font-weight: normal;\n font-style: normal;\n font-display: optional;\n}"
},
{
"code": null,
"e": 25921,
"s": 25912,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS | font-display</title> <meta name='viewport' content=\"width=device-width, initial-scale=1\"> <style> @font-face { font-family: Roboto; src: url(Roboto\\Roboto-BoldItalic.ttf) format('truetype'); font-style: italic; font-weight: bold; font-display: block; } div{ font-family: Roboto; font-style: italic; font-weight:bold; }</style></head><body><h1>Usage of font-display</h1><div>Downloaded font</div><p>Normal font</p></body></html>",
"e": 26473,
"s": 25921,
"text": null
},
{
"code": null,
"e": 26481,
"s": 26473,
"text": "Output:"
},
{
"code": null,
"e": 26562,
"s": 26481,
"text": "The downloaded font appears after a short span. Try running it on IDE to see it."
},
{
"code": null,
"e": 26628,
"s": 26562,
"text": "The font-display property timeline is divided into three periods:"
},
{
"code": null,
"e": 26634,
"s": 26628,
"text": "Block"
},
{
"code": null,
"e": 26639,
"s": 26634,
"text": "Swap"
},
{
"code": null,
"e": 26647,
"s": 26639,
"text": "Failure"
},
{
"code": null,
"e": 26753,
"s": 26647,
"text": "Block Period:The text will be invisible till web font hasn’t loaded, rendering is blocked in this period."
},
{
"code": null,
"e": 26925,
"s": 26753,
"text": "Swap Period:Originally the fallback font is used to render text, if web font is successfully loaded during the swap period, the fallback font is swapped with the web font."
},
{
"code": null,
"e": 27031,
"s": 26925,
"text": "Failure Period:At this point it is considered that loading is failed and the fallback font is to be used."
},
{
"code": null,
"e": 27075,
"s": 27031,
"text": "This property accepts the following values:"
},
{
"code": null,
"e": 27205,
"s": 27075,
"text": "Auto (Initial value): At this value, the font-display technique is chosen by the browser. This is usually similar to Block value."
},
{
"code": null,
"e": 27389,
"s": 27205,
"text": "Block: It goes for a small block period and then goes into an infinite swap period so the rendering is allowed infinitely. In simpler form, it hides the text until web font is loaded."
},
{
"code": null,
"e": 27538,
"s": 27389,
"text": "Swap: At this value, the font-face is provided with minimal block period and an infinite swap period. It uses fallback font until web font is loaded"
},
{
"code": null,
"e": 27743,
"s": 27538,
"text": "Fallback: It gives the font-face a minimal block period(100 ms) and a small swap period(about 3 seconds). It tries to load web font for a short period then goes into failure period and uses fallback font."
},
{
"code": null,
"e": 27937,
"s": 27743,
"text": "Optional: It gives the font-face a minimal block period and no swap period. It hides the text for a short time and then uses fallback font until web font is the custom font is available to use."
},
{
"code": null,
"e": 27952,
"s": 27937,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27959,
"s": 27952,
"text": "Picked"
},
{
"code": null,
"e": 27963,
"s": 27959,
"text": "CSS"
},
{
"code": null,
"e": 27980,
"s": 27963,
"text": "Web Technologies"
},
{
"code": null,
"e": 27996,
"s": 27980,
"text": "Write From Home"
},
{
"code": null,
"e": 28094,
"s": 27996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28131,
"s": 28094,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28160,
"s": 28131,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28199,
"s": 28160,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28241,
"s": 28199,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28288,
"s": 28241,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 28330,
"s": 28288,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28363,
"s": 28330,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28406,
"s": 28363,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28451,
"s": 28406,
"text": "Convert a string to an integer in JavaScript"
}
] |
Perl sleep Function
|
This function Pauses the script for EXPR seconds, or forever if EXPR is not specified. Returns the number of seconds actually slept. Can be interrupted by a signal handler, but you should avoid using sleep with alarm, since many systems use alarm for the sleep implementation.
Following is the simple syntax for this function −
sleep EXPR
sleep
This function returns Integer, number of seconds actually slept
Following is the example code showing its basic usage −
#!/usr/bin/perl
$num = 5;
while($num--) {
sleep(1);
}
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2497,
"s": 2220,
"text": "This function Pauses the script for EXPR seconds, or forever if EXPR is not specified. Returns the number of seconds actually slept. Can be interrupted by a signal handler, but you should avoid using sleep with alarm, since many systems use alarm for the sleep implementation."
},
{
"code": null,
"e": 2548,
"s": 2497,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2567,
"s": 2548,
"text": "sleep EXPR\n\nsleep\n"
},
{
"code": null,
"e": 2631,
"s": 2567,
"text": "This function returns Integer, number of seconds actually slept"
},
{
"code": null,
"e": 2687,
"s": 2631,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2745,
"s": 2687,
"text": "#!/usr/bin/perl\n\n$num = 5;\nwhile($num--) {\n sleep(1);\n}"
},
{
"code": null,
"e": 2780,
"s": 2745,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2794,
"s": 2780,
"text": " Devi Killada"
},
{
"code": null,
"e": 2829,
"s": 2794,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2849,
"s": 2829,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 2882,
"s": 2849,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2898,
"s": 2882,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2931,
"s": 2898,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2948,
"s": 2931,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 2981,
"s": 2948,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3004,
"s": 2981,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3039,
"s": 3004,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3062,
"s": 3039,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3069,
"s": 3062,
"text": " Print"
},
{
"code": null,
"e": 3080,
"s": 3069,
"text": " Add Notes"
}
] |
How to convert std::string to LPCSTR in C++?
|
In this section we will see how to convert C++ string (std::string) to LPCSTR. The LPCSTR is the (Long Pointer to Constant STRing). It is basically the string like C. So by converting string to character array we can get LPCSTR. This LPCSTR is Microsoft defined. So to use them we have to include Windows.h header file into our program.
To convert std::string to C like string we can use the function called c_str().
#include<iostream>
#include<Windows.h>
using namespace std;
main() {
string my_str = "Hello World";
LPTSTR long_string = new TCHAR[my_str.size() + 1]; //define
an array with size of my_str + 1
strcpy(long_string, my_str.c_str());
cout << "my_str is : " << my_str <<endl;
cout << "Long String is : " << long_string <<endl;
}
my_str is : Hello World
Long String is : Hello World
|
[
{
"code": null,
"e": 1399,
"s": 1062,
"text": "In this section we will see how to convert C++ string (std::string) to LPCSTR. The LPCSTR is the (Long Pointer to Constant STRing). It is basically the string like C. So by converting string to character array we can get LPCSTR. This LPCSTR is Microsoft defined. So to use them we have to include Windows.h header file into our program."
},
{
"code": null,
"e": 1479,
"s": 1399,
"text": "To convert std::string to C like string we can use the function called c_str()."
},
{
"code": null,
"e": 1821,
"s": 1479,
"text": "#include<iostream>\n#include<Windows.h>\nusing namespace std;\nmain() {\n string my_str = \"Hello World\";\n LPTSTR long_string = new TCHAR[my_str.size() + 1]; //define\n an array with size of my_str + 1\n strcpy(long_string, my_str.c_str());\n cout << \"my_str is : \" << my_str <<endl;\n cout << \"Long String is : \" << long_string <<endl;\n}"
},
{
"code": null,
"e": 1874,
"s": 1821,
"text": "my_str is : Hello World\nLong String is : Hello World"
}
] |
How to add Phone Number Input in React.js ? - GeeksforGeeks
|
28 Dec, 2021
In this article, we are going to learn how we can add phone input in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To add our phone input we are going to use the react-phone-input-2 package. The react-phone-input-2 package helps us to integrate the phone input in our app. So first, we will install the react-phone-input-2 package and then we will add a phone input on our homepage.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the react-phone-input-2 package using the below command:
npm i react-phone-input-2
Project Structure: It will look like this.
Adding the Phone Input: After installing the package we can easily add a phone input on any page in our app. For this example, we are going to add a phone input to our homepage.
Add the below content in the App.js file:
Javascript
import React, { useState } from "react";import PhoneInput from 'react-phone-input-2'import 'react-phone-input-2/lib/style.css' export default class PhoneInputGfg extends React.Component { constructor(props) { super(props); this.state = { phone: "" }; } render(){ return ( <div> <h1>ReactJs Phone Input - GeeksforGeeks</h1> <PhoneInput country={'us'} value={this.state.phone} onChange={phone => this.setState({ phone })} /> </div> ); }};
Explanation: In the above example first, we are importing the PhoneInput component and useState hook from react. Then we are using the useState hook to store the value of the phone number. After that, we are adding our phone input using the installed package.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
React-Questions
JavaScript
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Lodash _.debounce() Method
Angular File Upload
JavaScript | Promises
|
[
{
"code": null,
"e": 25298,
"s": 25270,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 25569,
"s": 25298,
"text": "In this article, we are going to learn how we can add phone input in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies."
},
{
"code": null,
"e": 25847,
"s": 25569,
"text": "Approach: To add our phone input we are going to use the react-phone-input-2 package. The react-phone-input-2 package helps us to integrate the phone input in our app. So first, we will install the react-phone-input-2 package and then we will add a phone input on our homepage."
},
{
"code": null,
"e": 25937,
"s": 25847,
"text": "Create ReactJs Application: You can create a new ReactJs project using the below command:"
},
{
"code": null,
"e": 25962,
"s": 25937,
"text": "npx create-react-app gfg"
},
{
"code": null,
"e": 26069,
"s": 25962,
"text": "Install the required package: Now we will install the react-phone-input-2 package using the below command:"
},
{
"code": null,
"e": 26095,
"s": 26069,
"text": "npm i react-phone-input-2"
},
{
"code": null,
"e": 26138,
"s": 26095,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 26316,
"s": 26138,
"text": "Adding the Phone Input: After installing the package we can easily add a phone input on any page in our app. For this example, we are going to add a phone input to our homepage."
},
{
"code": null,
"e": 26358,
"s": 26316,
"text": "Add the below content in the App.js file:"
},
{
"code": null,
"e": 26369,
"s": 26358,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\";import PhoneInput from 'react-phone-input-2'import 'react-phone-input-2/lib/style.css' export default class PhoneInputGfg extends React.Component { constructor(props) { super(props); this.state = { phone: \"\" }; } render(){ return ( <div> <h1>ReactJs Phone Input - GeeksforGeeks</h1> <PhoneInput country={'us'} value={this.state.phone} onChange={phone => this.setState({ phone })} /> </div> ); }};",
"e": 26881,
"s": 26369,
"text": null
},
{
"code": null,
"e": 27141,
"s": 26881,
"text": "Explanation: In the above example first, we are importing the PhoneInput component and useState hook from react. Then we are using the useState hook to store the value of the phone number. After that, we are adding our phone input using the installed package."
},
{
"code": null,
"e": 27225,
"s": 27141,
"text": "Steps to run the application: Run the below command in the terminal to run the app."
},
{
"code": null,
"e": 27235,
"s": 27225,
"text": "npm start"
},
{
"code": null,
"e": 27251,
"s": 27235,
"text": "React-Questions"
},
{
"code": null,
"e": 27262,
"s": 27251,
"text": "JavaScript"
},
{
"code": null,
"e": 27360,
"s": 27262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27421,
"s": 27360,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27462,
"s": 27421,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27502,
"s": 27462,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27556,
"s": 27502,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27604,
"s": 27556,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27666,
"s": 27604,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27723,
"s": 27666,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27750,
"s": 27723,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 27770,
"s": 27750,
"text": "Angular File Upload"
}
] |
Build Responsive UI with Flutter - GeeksforGeeks
|
21 Sep, 2021
In this article, we’ll go over the different widgets using which we can build responsive applications with Flutter.
Builds a widget tree that can depend on the parent widget’s size. This is useful if we want to change or hide something depending on the parent size.
Dart
LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { // constraints provide us with maxWidth,maxHeight etc, using // which we can show different widgets accordingly if (constraints.maxWidth > 600) { // as the width is greater than 600px, // we'll show wide screen container return _buildWideScreenContainers(); } else { return _buildPortraitContainer(); } },),
Let’s see that in an actual User Interface.
Dart
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); }} class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Geeks for Geeks"), backgroundColor: Colors.green), body: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { // constraints provide us with maxWidth,maxHeight etc, using // which we can show different widgets accordingly if (constraints.maxWidth > 600) { // as the width is greater than 600px, we'll show wide screen container // with two containers in a row return _buildWideScreenContainers(); } else { return _buildPortraitContainer(); } }, ), ); } Widget _buildPortraitContainer() { // here we're returning a single container since the phone// doesn't has the required width (600px) return Center( child: Container( height: 100.0, width: 100.0, color: Colors.red, ), ); } Widget _buildWideScreenContainers() { // here we're returning double containers since the phone// has the required width (600px) return Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( height: 100.0, width: 100.0, color: Colors.red, ), Container( height: 100.0, width: 100.0, color: Colors.yellow, ), ], ), ); }}
When we run the code written above, this is what we get.
Notice how we see a single box when in portrait mode and double boxes when we rotate the phone.
MediaQuery also lets us have the constraints. MediaQuery will not take constraints from the parent widget though, but instead, take it from the whole layout. Let’s see an example using MediaQuery(), where we hide the AppBar() depending on the screen width.
Dart
class MediaQueryExample extends StatelessWidget { @override Widget build(BuildContext context) { final screenW = MediaQuery.of(context).size.width; print(screenW); return Scaffold( // when screen's width is less than 600px, // it shows a appbar, when it's over 600px, // it hides it. appBar: screenW <= 600 ? AppBar( title: Text("Geeks for Geeks"), backgroundColor: Colors.green) : null, body: Center( child: Text("Mediaquery example"), ), ); }}
Using MediaQuery(), we can have the screen size, aspect ratio, and other useful data.
final query = MediaQuery.of(context); // provide us with the query
print(query.size.aspectRatio); //aspect ratio
print(query.size.height);//screen height
print(query.size.width);//screen width
The BreakPoint can also be used for developing responsive UIs in flutter apps.
const kTabletBreakpoint = 768.0; //breakpoint for a tablet (a tablet's width is 768 px)
const kDesktopBreakPoint = 1440.0; //breakpoint for desktop (a desktop screen's width is 1440 px)
const kSideMenuWidth = 300.0; // for sidemenu
const kNavigationRailWidth = 72.0; // for navigation rail
const kMaxWidth = 1180.0; // maximum width
We can use the breakpoints written above to display different UI for different devices. For Example,
Dart
class ResponsiveWidget extends StatelessWidget { const ResponsiveWidget({ Key? key, required this.mobileBody, this.tabletBody, this.desktopBody, }) : super(key: key); final Widget mobileBody; final Widget? tabletBody; final Widget? desktopBody; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, dimens) { // check if the device is a phone if (dimens.maxWidth < kTabletBreakpoint) { return mobileBody; } else if (dimens.maxWidth >= kTabletBreakpoint && dimens.maxWidth < kDesktopBreakPoint) { // returns mobileBody if tabletBody is null return tabletBody ?? mobileBody; } else { // returns mobileBody if desktopBody is null return desktopBody ?? mobileBody; } }, ); }}
Output:
Shows and hides the AppBar depending on the screen’s width using MedaQuery().
Shows and hides the AppBar depending on the parent’s width using LayoutBuilder().
For more information on handling different UI for different devices, kindly read this article. That’s it. This is all we need in order to get started on building responsive apps with flutter.
Blogathon-2021
Flutter UI-components
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 25232,
"s": 25116,
"text": "In this article, we’ll go over the different widgets using which we can build responsive applications with Flutter."
},
{
"code": null,
"e": 25382,
"s": 25232,
"text": "Builds a widget tree that can depend on the parent widget’s size. This is useful if we want to change or hide something depending on the parent size."
},
{
"code": null,
"e": 25387,
"s": 25382,
"text": "Dart"
},
{
"code": "LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { // constraints provide us with maxWidth,maxHeight etc, using // which we can show different widgets accordingly if (constraints.maxWidth > 600) { // as the width is greater than 600px, // we'll show wide screen container return _buildWideScreenContainers(); } else { return _buildPortraitContainer(); } },),",
"e": 25898,
"s": 25387,
"text": null
},
{
"code": null,
"e": 25942,
"s": 25898,
"text": "Let’s see that in an actual User Interface."
},
{
"code": null,
"e": 25947,
"s": 25942,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); }} class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(\"Geeks for Geeks\"), backgroundColor: Colors.green), body: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { // constraints provide us with maxWidth,maxHeight etc, using // which we can show different widgets accordingly if (constraints.maxWidth > 600) { // as the width is greater than 600px, we'll show wide screen container // with two containers in a row return _buildWideScreenContainers(); } else { return _buildPortraitContainer(); } }, ), ); } Widget _buildPortraitContainer() { // here we're returning a single container since the phone// doesn't has the required width (600px) return Center( child: Container( height: 100.0, width: 100.0, color: Colors.red, ), ); } Widget _buildWideScreenContainers() { // here we're returning double containers since the phone// has the required width (600px) return Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( height: 100.0, width: 100.0, color: Colors.red, ), Container( height: 100.0, width: 100.0, color: Colors.yellow, ), ], ), ); }}",
"e": 27776,
"s": 25947,
"text": null
},
{
"code": null,
"e": 27833,
"s": 27776,
"text": "When we run the code written above, this is what we get."
},
{
"code": null,
"e": 27929,
"s": 27833,
"text": "Notice how we see a single box when in portrait mode and double boxes when we rotate the phone."
},
{
"code": null,
"e": 28186,
"s": 27929,
"text": "MediaQuery also lets us have the constraints. MediaQuery will not take constraints from the parent widget though, but instead, take it from the whole layout. Let’s see an example using MediaQuery(), where we hide the AppBar() depending on the screen width."
},
{
"code": null,
"e": 28191,
"s": 28186,
"text": "Dart"
},
{
"code": "class MediaQueryExample extends StatelessWidget { @override Widget build(BuildContext context) { final screenW = MediaQuery.of(context).size.width; print(screenW); return Scaffold( // when screen's width is less than 600px, // it shows a appbar, when it's over 600px, // it hides it. appBar: screenW <= 600 ? AppBar( title: Text(\"Geeks for Geeks\"), backgroundColor: Colors.green) : null, body: Center( child: Text(\"Mediaquery example\"), ), ); }}",
"e": 28731,
"s": 28191,
"text": null
},
{
"code": null,
"e": 28817,
"s": 28731,
"text": "Using MediaQuery(), we can have the screen size, aspect ratio, and other useful data."
},
{
"code": null,
"e": 29022,
"s": 28817,
"text": "final query = MediaQuery.of(context); // provide us with the query\n print(query.size.aspectRatio); //aspect ratio\n print(query.size.height);//screen height\n print(query.size.width);//screen width"
},
{
"code": null,
"e": 29101,
"s": 29022,
"text": "The BreakPoint can also be used for developing responsive UIs in flutter apps."
},
{
"code": null,
"e": 29437,
"s": 29101,
"text": "const kTabletBreakpoint = 768.0; //breakpoint for a tablet (a tablet's width is 768 px)\nconst kDesktopBreakPoint = 1440.0; //breakpoint for desktop (a desktop screen's width is 1440 px)\n\nconst kSideMenuWidth = 300.0; // for sidemenu\nconst kNavigationRailWidth = 72.0; // for navigation rail\n\nconst kMaxWidth = 1180.0; // maximum width"
},
{
"code": null,
"e": 29538,
"s": 29437,
"text": "We can use the breakpoints written above to display different UI for different devices. For Example,"
},
{
"code": null,
"e": 29543,
"s": 29538,
"text": "Dart"
},
{
"code": "class ResponsiveWidget extends StatelessWidget { const ResponsiveWidget({ Key? key, required this.mobileBody, this.tabletBody, this.desktopBody, }) : super(key: key); final Widget mobileBody; final Widget? tabletBody; final Widget? desktopBody; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, dimens) { // check if the device is a phone if (dimens.maxWidth < kTabletBreakpoint) { return mobileBody; } else if (dimens.maxWidth >= kTabletBreakpoint && dimens.maxWidth < kDesktopBreakPoint) { // returns mobileBody if tabletBody is null return tabletBody ?? mobileBody; } else { // returns mobileBody if desktopBody is null return desktopBody ?? mobileBody; } }, ); }}",
"e": 30397,
"s": 29543,
"text": null
},
{
"code": null,
"e": 30406,
"s": 30397,
"text": "Output: "
},
{
"code": null,
"e": 30485,
"s": 30406,
"text": " Shows and hides the AppBar depending on the screen’s width using MedaQuery()."
},
{
"code": null,
"e": 30567,
"s": 30485,
"text": "Shows and hides the AppBar depending on the parent’s width using LayoutBuilder()."
},
{
"code": null,
"e": 30759,
"s": 30567,
"text": "For more information on handling different UI for different devices, kindly read this article. That’s it. This is all we need in order to get started on building responsive apps with flutter."
},
{
"code": null,
"e": 30774,
"s": 30759,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 30796,
"s": 30774,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 30804,
"s": 30796,
"text": "Android"
},
{
"code": null,
"e": 30809,
"s": 30804,
"text": "Dart"
},
{
"code": null,
"e": 30817,
"s": 30809,
"text": "Flutter"
},
{
"code": null,
"e": 30825,
"s": 30817,
"text": "Android"
},
{
"code": null,
"e": 30923,
"s": 30825,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30932,
"s": 30923,
"text": "Comments"
},
{
"code": null,
"e": 30945,
"s": 30932,
"text": "Old Comments"
},
{
"code": null,
"e": 30984,
"s": 30945,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31026,
"s": 30984,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31059,
"s": 31026,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 31097,
"s": 31059,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 31170,
"s": 31097,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 31198,
"s": 31170,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 31230,
"s": 31198,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 31252,
"s": 31230,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 31277,
"s": 31252,
"text": "Splash Screen in Flutter"
}
] |
How can we alter a MySQL stored function?
|
If we have ALTER ROUTINE privileges then we can alter MySQL stored function with the help of ALTER FUNCTION query. Its syntax is as follows −
ALTER FUNCTION function_name [characteristic ...]
characteristic:
{ CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
Here function_name is the name of the function which we want to alter.
The ALTER FUNCTION statement can change the characteristics, defined above in the syntax, of a stored function. We can specify more than one change in an ALTER FUNCTION statement. But we cannot change the parameters or body of the function with this statement. To illustrate it we are adding comments in the function name ‘factorial’ in the following example −
mysql> ALTER FUNCTION factorial COMMENT 'Can accept fraction values';
Query OK, 0 rows affected (0.00 sec)
mysql> Show Create Function factorial\G
*************************** 1. row ***************************
Function: factorial
sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Create Function: CREATE DEFINER=`root`@`localhost` FUNCTION `factorial`(n DECIMAL(3,0)) RETURNS decimal(20,0)
DETERMINISTIC
COMMENT 'Can accept fraction values'
BEGIN
DECLARE factorial DECIMAL(20,0) DEFAULT 1;
DECLARE counter DECIMAL(3,0);
SET counter = n;
factorial_loop: REPEAT
SET factorial = factorial * counter;
SET counter = counter - 1;
UNTIL counter = 1
END REPEAT;
RETURN factorial;
END
character_set_client: cp850
collation_connection: cp850_general_ci
Database Collation: latin1_swedish_ci
1 row in set (0.00 sec)
From the CREAT FUNCTION query, it is clear that Comment has been added to the definition of function ‘factorial’.
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "If we have ALTER ROUTINE privileges then we can alter MySQL stored function with the help of ALTER FUNCTION query. Its syntax is as follows −"
},
{
"code": null,
"e": 1392,
"s": 1204,
"text": "ALTER FUNCTION function_name [characteristic ...]\ncharacteristic:\n { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }\n| SQL SECURITY { DEFINER | INVOKER }\n| COMMENT 'string'"
},
{
"code": null,
"e": 1463,
"s": 1392,
"text": "Here function_name is the name of the function which we want to alter."
},
{
"code": null,
"e": 1824,
"s": 1463,
"text": "The ALTER FUNCTION statement can change the characteristics, defined above in the syntax, of a stored function. We can specify more than one change in an ALTER FUNCTION statement. But we cannot change the parameters or body of the function with this statement. To illustrate it we are adding comments in the function name ‘factorial’ in the following example −"
},
{
"code": null,
"e": 2758,
"s": 1824,
"text": "mysql> ALTER FUNCTION factorial COMMENT 'Can accept fraction values';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Show Create Function factorial\\G\n*************************** 1. row ***************************\n Function: factorial\n sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\nCreate Function: CREATE DEFINER=`root`@`localhost` FUNCTION `factorial`(n DECIMAL(3,0)) RETURNS decimal(20,0)\nDETERMINISTIC\nCOMMENT 'Can accept fraction values'\nBEGIN\nDECLARE factorial DECIMAL(20,0) DEFAULT 1;\nDECLARE counter DECIMAL(3,0);\nSET counter = n;\n factorial_loop: REPEAT\nSET factorial = factorial * counter;\n\nSET counter = counter - 1;\n UNTIL counter = 1\nEND REPEAT;\n RETURN factorial;\nEND\n\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n Database Collation: latin1_swedish_ci\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2872,
"s": 2758,
"text": "From the CREAT FUNCTION query, it is clear that Comment has been added to the definition of function ‘factorial’."
}
] |
Change marker border color in Plotly - Python - GeeksforGeeks
|
17 Dec, 2020
In this article, we are going to discuss how to change marker border color using plotly module in Python.
Plotly is definitely a must-know tool for visualization since it’s incredibly powerful easily used and has the big benefit of interactivity we are able to export visualization, being able to run on browsers, build with DASH which is web-based python interface which removes the need of javascript in this type of analytical web applications, and we can also run these plot offline as well. In this article we will use the module of plotly which is plotly.express, it is the high-level python visualization library, it exposes simple syntax to complex charts it is the wrapper for plotly.py.
Installation:
This module can be installed using the below command:
pip install plotly
In this article, we are going to change the maker border color with the help of plotly.express.scatter.update_traces() and plotly.express.scatter_3d.update_traces()() methods.
Step-by-step Approach:
Import the plotly and pandas library.
First, we have to load the dataset on which we are plotting our graph with the help of the pandas library.
For plotting the graph we will use plotly.scatter() for scatter plot and put it in the variable let name as fig
Then we use fig.update_traces function which is having marker property from which we can change the borders of the marker.
We are going to use the below iris dataset in various examples:
Python3
# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # display datasetdf
Output:
Example 1: Plotting default scatter plot on iris dataset.
Python
# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter plot on sepal_width # and sepal_length and giving color with # respect to speciesfig = px.scatter(df, x='sepal_width', y='sepal_length', color='species') # showing the plot with default settingsfig.show()
Output:
Plotting scatter plot on iris dataset and changing marker border color.
Python
# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter plot on sepal_width# and sepal_length and giving color # with respect to speciesfig = px.scatter(df, x='sepal_width', y='sepal_length', color='species') # setting up marker and in line # Attribute giving the width and color of borderfig.update_traces(marker=dict(size=10, line=dict(width=3, color='blue'))) # showing the plot with default settingsfig.show()
Output:
In the above code, we had used update_traces() function in that we had given marker attribute for creating the borders in that attribute we had passed the dictionary in which we had passes size=10 for giving the size to the circles, whereas in line we had passed the dictionary in which we had passes width and color, width refers to the width of the border and color refers to the color of the border.
Example 3: Plotting default scatter_3d plot on iris dataset.
Python
# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter 3d plot by giving # three axis, petal length, petal width # and sepal length # giving color with respect to speciesfig = px.scatter_3d(df,x='petal_length', y='petal_width', z='sepal_length', color='species') # showing the plot with default settingsfig.show()
Output:
Example 4: Plotting scatter_3d plot on iris dataset with marker border color.
Python
# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter_3d plot by # giving three axis on petal_length, # petal_width and sepal_length # and giving color with respect to speciesfig = px.scatter_3d(df,x='petal_length', y='petal_width', z='sepal_length', color='species') # setting up marker and in line Attribute # giving the width and color of borderfig.update_traces(marker=dict(size=10, line=dict(width=10, color='red'))) # showing the plot fig.show()
Output:
Picked
Python-Plotly
Technical Scripter 2020
Python
Technical Scripter
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
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 24424,
"s": 24318,
"text": "In this article, we are going to discuss how to change marker border color using plotly module in Python."
},
{
"code": null,
"e": 25015,
"s": 24424,
"text": "Plotly is definitely a must-know tool for visualization since it’s incredibly powerful easily used and has the big benefit of interactivity we are able to export visualization, being able to run on browsers, build with DASH which is web-based python interface which removes the need of javascript in this type of analytical web applications, and we can also run these plot offline as well. In this article we will use the module of plotly which is plotly.express, it is the high-level python visualization library, it exposes simple syntax to complex charts it is the wrapper for plotly.py."
},
{
"code": null,
"e": 25029,
"s": 25015,
"text": "Installation:"
},
{
"code": null,
"e": 25083,
"s": 25029,
"text": "This module can be installed using the below command:"
},
{
"code": null,
"e": 25102,
"s": 25083,
"text": "pip install plotly"
},
{
"code": null,
"e": 25278,
"s": 25102,
"text": "In this article, we are going to change the maker border color with the help of plotly.express.scatter.update_traces() and plotly.express.scatter_3d.update_traces()() methods."
},
{
"code": null,
"e": 25301,
"s": 25278,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 25339,
"s": 25301,
"text": "Import the plotly and pandas library."
},
{
"code": null,
"e": 25446,
"s": 25339,
"text": "First, we have to load the dataset on which we are plotting our graph with the help of the pandas library."
},
{
"code": null,
"e": 25558,
"s": 25446,
"text": "For plotting the graph we will use plotly.scatter() for scatter plot and put it in the variable let name as fig"
},
{
"code": null,
"e": 25681,
"s": 25558,
"text": "Then we use fig.update_traces function which is having marker property from which we can change the borders of the marker."
},
{
"code": null,
"e": 25745,
"s": 25681,
"text": "We are going to use the below iris dataset in various examples:"
},
{
"code": null,
"e": 25753,
"s": 25745,
"text": "Python3"
},
{
"code": "# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # display datasetdf",
"e": 25878,
"s": 25753,
"text": null
},
{
"code": null,
"e": 25886,
"s": 25878,
"text": "Output:"
},
{
"code": null,
"e": 25944,
"s": 25886,
"text": "Example 1: Plotting default scatter plot on iris dataset."
},
{
"code": null,
"e": 25951,
"s": 25944,
"text": "Python"
},
{
"code": "# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter plot on sepal_width # and sepal_length and giving color with # respect to speciesfig = px.scatter(df, x='sepal_width', y='sepal_length', color='species') # showing the plot with default settingsfig.show()",
"e": 26319,
"s": 25951,
"text": null
},
{
"code": null,
"e": 26327,
"s": 26319,
"text": "Output:"
},
{
"code": null,
"e": 26399,
"s": 26327,
"text": "Plotting scatter plot on iris dataset and changing marker border color."
},
{
"code": null,
"e": 26406,
"s": 26399,
"text": "Python"
},
{
"code": "# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter plot on sepal_width# and sepal_length and giving color # with respect to speciesfig = px.scatter(df, x='sepal_width', y='sepal_length', color='species') # setting up marker and in line # Attribute giving the width and color of borderfig.update_traces(marker=dict(size=10, line=dict(width=3, color='blue'))) # showing the plot with default settingsfig.show()",
"e": 26997,
"s": 26406,
"text": null
},
{
"code": null,
"e": 27005,
"s": 26997,
"text": "Output:"
},
{
"code": null,
"e": 27408,
"s": 27005,
"text": "In the above code, we had used update_traces() function in that we had given marker attribute for creating the borders in that attribute we had passed the dictionary in which we had passes size=10 for giving the size to the circles, whereas in line we had passed the dictionary in which we had passes width and color, width refers to the width of the border and color refers to the color of the border."
},
{
"code": null,
"e": 27469,
"s": 27408,
"text": "Example 3: Plotting default scatter_3d plot on iris dataset."
},
{
"code": null,
"e": 27476,
"s": 27469,
"text": "Python"
},
{
"code": "# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter 3d plot by giving # three axis, petal length, petal width # and sepal length # giving color with respect to speciesfig = px.scatter_3d(df,x='petal_length', y='petal_width', z='sepal_length', color='species') # showing the plot with default settingsfig.show()",
"e": 27921,
"s": 27476,
"text": null
},
{
"code": null,
"e": 27929,
"s": 27921,
"text": "Output:"
},
{
"code": null,
"e": 28007,
"s": 27929,
"text": "Example 4: Plotting scatter_3d plot on iris dataset with marker border color."
},
{
"code": null,
"e": 28014,
"s": 28007,
"text": "Python"
},
{
"code": "# importing libraryimport plotly.express as px # importing iris dataset from plotlydf = px.data.iris() # plotting the scatter_3d plot by # giving three axis on petal_length, # petal_width and sepal_length # and giving color with respect to speciesfig = px.scatter_3d(df,x='petal_length', y='petal_width', z='sepal_length', color='species') # setting up marker and in line Attribute # giving the width and color of borderfig.update_traces(marker=dict(size=10, line=dict(width=10, color='red'))) # showing the plot fig.show()",
"e": 28668,
"s": 28014,
"text": null
},
{
"code": null,
"e": 28676,
"s": 28668,
"text": "Output:"
},
{
"code": null,
"e": 28683,
"s": 28676,
"text": "Picked"
},
{
"code": null,
"e": 28697,
"s": 28683,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28721,
"s": 28697,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28728,
"s": 28721,
"text": "Python"
},
{
"code": null,
"e": 28747,
"s": 28728,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28845,
"s": 28747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28854,
"s": 28845,
"text": "Comments"
},
{
"code": null,
"e": 28867,
"s": 28854,
"text": "Old Comments"
},
{
"code": null,
"e": 28899,
"s": 28867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28955,
"s": 28899,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29010,
"s": 28955,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29052,
"s": 29010,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29094,
"s": 29052,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29125,
"s": 29094,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29164,
"s": 29125,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29186,
"s": 29164,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29215,
"s": 29186,
"text": "Create a directory in Python"
}
] |
CSS3 - Multi Background
|
CSS Multi background property is used to add one or more images at a time without HTML code, We can add images as per our requirement.A sample syntax of multi background images is as follows −
#multibackground {
background-image: url(/css/images/logo.png), url(/css/images/border.png);
background-position: left top, left top;
background-repeat: no-repeat, repeat;
padding: 75px;
}
The most commonly used values are shown below −
background
Used to setting all the background image properties in one section
background-clip
Used to declare the painting area of the background
background-image
Used to specify the background image
background-origin
Used to specify position of the background images
background-size
Used to specify size of the background images
Following is the example which demonstrate the multi background images.
<html>
<head>
<style>
#multibackground {
background-image: url(/css/images/logo.png), url(/css/images/border.png);
background-position: left top, left top;
background-repeat: no-repeat, repeat;
padding: 75px;
}
</style>
</head>
<body>
<div id = "multibackground">
<h1>www.tutorialspoint.com</h1>
<p>
Tutorials Point originated from the idea that there exists a class of
readers who respond better to online content and prefer to learn new
skills at their own pace from the comforts of their drawing rooms.
The journey commenced with a single tutorial on HTML in 2006 and elated
by the response it generated, we worked our way to adding fresh tutorials
to our repository which now proudly flaunts a wealth of tutorials and
allied articles on topics ranging from programming languages to web designing
to academics and much more..
</p>
</div>
</body>
</html>
It will produce the following result −
Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more..
Multi background property is accepted to add different sizes for different images.A sample syntax is as shown below −
#multibackground {
background: url(/css/imalges/logo.png) left top no-repeat, url(/css/images/boarder.png) right bottom no-repeat, url(/css/images/css.gif) left top repeat;
background-size: 50px, 130px, auto;
}
As shown above an example, each image is having specific sizes as 50px, 130px and auto size.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2819,
"s": 2626,
"text": "CSS Multi background property is used to add one or more images at a time without HTML code, We can add images as per our requirement.A sample syntax of multi background images is as follows −"
},
{
"code": null,
"e": 3020,
"s": 2819,
"text": "#multibackground {\n background-image: url(/css/images/logo.png), url(/css/images/border.png);\n background-position: left top, left top;\n background-repeat: no-repeat, repeat;\n padding: 75px;\n}"
},
{
"code": null,
"e": 3068,
"s": 3020,
"text": "The most commonly used values are shown below −"
},
{
"code": null,
"e": 3079,
"s": 3068,
"text": "background"
},
{
"code": null,
"e": 3146,
"s": 3079,
"text": "Used to setting all the background image properties in one section"
},
{
"code": null,
"e": 3162,
"s": 3146,
"text": "background-clip"
},
{
"code": null,
"e": 3214,
"s": 3162,
"text": "Used to declare the painting area of the background"
},
{
"code": null,
"e": 3231,
"s": 3214,
"text": "background-image"
},
{
"code": null,
"e": 3269,
"s": 3231,
"text": "Used to specify the background image"
},
{
"code": null,
"e": 3287,
"s": 3269,
"text": "background-origin"
},
{
"code": null,
"e": 3337,
"s": 3287,
"text": "Used to specify position of the background images"
},
{
"code": null,
"e": 3353,
"s": 3337,
"text": "background-size"
},
{
"code": null,
"e": 3399,
"s": 3353,
"text": "Used to specify size of the background images"
},
{
"code": null,
"e": 3471,
"s": 3399,
"text": "Following is the example which demonstrate the multi background images."
},
{
"code": null,
"e": 4574,
"s": 3471,
"text": "<html>\n <head>\n <style>\n #multibackground {\n background-image: url(/css/images/logo.png), url(/css/images/border.png);\n background-position: left top, left top;\n background-repeat: no-repeat, repeat;\n padding: 75px;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"multibackground\">\n <h1>www.tutorialspoint.com</h1>\n <p>\n Tutorials Point originated from the idea that there exists a class of \n readers who respond better to online content and prefer to learn new \n skills at their own pace from the comforts of their drawing rooms. \n The journey commenced with a single tutorial on HTML in 2006 and elated \n by the response it generated, we worked our way to adding fresh tutorials \n to our repository which now proudly flaunts a wealth of tutorials and \n allied articles on topics ranging from programming languages to web designing \n to academics and much more..\n </p>\n </div>\n \n </body>\n</html> "
},
{
"code": null,
"e": 4613,
"s": 4574,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5142,
"s": 4613,
"text": "Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.\nThe journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more.."
},
{
"code": null,
"e": 5260,
"s": 5142,
"text": "Multi background property is accepted to add different sizes for different images.A sample syntax is as shown below −"
},
{
"code": null,
"e": 5477,
"s": 5260,
"text": "#multibackground {\n background: url(/css/imalges/logo.png) left top no-repeat, url(/css/images/boarder.png) right bottom no-repeat, url(/css/images/css.gif) left top repeat;\n background-size: 50px, 130px, auto;\n}"
},
{
"code": null,
"e": 5570,
"s": 5477,
"text": "As shown above an example, each image is having specific sizes as 50px, 130px and auto size."
},
{
"code": null,
"e": 5605,
"s": 5570,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5619,
"s": 5605,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5654,
"s": 5619,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5671,
"s": 5654,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5706,
"s": 5671,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5737,
"s": 5706,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5772,
"s": 5737,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5803,
"s": 5772,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5838,
"s": 5803,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5869,
"s": 5838,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5902,
"s": 5869,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5933,
"s": 5902,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5940,
"s": 5933,
"text": " Print"
},
{
"code": null,
"e": 5951,
"s": 5940,
"text": " Add Notes"
}
] |
Count pairs in an array that hold i+j= arr[i]+arr[j] - GeeksforGeeks
|
31 May, 2021
Given an array of integers arr[], the task is to count all the pairs (arr[i], arr[j]) such that i + j = arr[i] + arr[j] for all 0 ≤ i < j < n. Note: Pairs (x, y) and (y, x) are considered a single pair.
Examples:
Input: arr[] = {8, 4, 2, 1, 5, 4, 2, 1, 2, 3} Output: 1 The only possible pair is (arr[4], arr[5]) i.e. (5, 4) i + j = arr[i] + arr[j] => 4 + 5 = 5 + 4
Input: arr[] = {1, 0, 3, 2} Output: 4
Naive Approach: Run two nested loops and check every possible pair for the condition where i + j = arr[i] + arr[j]. If the condition is satisfied, then update the count = count + 1. Print the count at the end.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count all the pairs that// hold the condition i + j = arr[i] + arr[j]#include <iostream>using namespace std; // Function to return the count of pairs that// satisfy the given conditionint CountPairs(int arr[], int n){ int count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count;} // Driver codeint main(){ int arr[] = { 1, 0, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << CountPairs(arr, n); return 0;}
// Java program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] public class GFG { // Function to return the count of pairs that // satisfy the given condition static int CountPairs(int arr[], int n) { int count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count; } // Driver code public static void main(String args[]) { int arr[] = { 1, 0, 3, 2 }; int n = arr.length ; System.out.print(CountPairs(arr, n)); } // This code is contributed by Ryuga.}
# Python 3 program to count all the pairs that# hold the condition i + j = arr[i] + arr[j] # Function to return the count of pairs# that satisfy the given conditiondef CountPairs(arr, n): count = 0; # Generate all possible pairs and increment # the count if the condition is satisfied for i in range(n - 1): for j in range(i + 1, n): if ((i + j) == (arr[i] + arr[j])): count += 1; return count; # Driver codearr = [ 1, 0, 3, 2 ];n = len(arr);print(CountPairs(arr, n)); # This code is contributed# by Akanksha Rai
using System; // C# program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] public class GFG { // Function to return the count of pairs that // satisfy the given condition static int CountPairs(int[] arr, int n) { int count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count; } // Driver code public static void Main() { int[] arr = { 1, 0, 3, 2 }; int n = arr.Length ; Console.Write(CountPairs(arr, n)); } }
<?php// PHP program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] // Function to return the count of pairs// that satisfy the given conditionfunction CountPairs(&$arr, $n){ $count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for ($i = 0; $i < $n - 1; $i++) { for ($j = $i + 1; $j < $n; $j++) { if (($i + $j) == ($arr[$i] + $arr[$j])) $count++; } } return $count;} // Driver code$arr = array(1, 0, 3, 2 );$n = sizeof($arr);echo(CountPairs($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script>// Javascript program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] // Function to return the count of pairs that // satisfy the given condition function CountPairs(arr,n) { let count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count; } // Driver code let arr=[1, 0, 3, 2]; let n = arr.length ; document.write(CountPairs(arr, n)); // This code is contributed by avanitrachhadiya2155</script>
4
Efficient Approach:
Reduce i + j = arr[i] + arr[j] to (arr[i] – i) = -(arr[j] – j). Now, the problem is reduced to finding all the pairs of the form (x, -x).So, update all the elements of the array as arr[i] = arr[i] – i according to the reduction from step 1.In order to count all the pairs of the form (x, -x), save the frequencies of all the negative elements into a HashMap named negMap and of all the positive elements (including 0) into posMap.Now, for every frequency in posMap say x, find the frequency of -x in negMap. So, all the possible pairs between x and -x will be count = count + (frequency(x) * frequency(-x)).Print the count at the end.
Reduce i + j = arr[i] + arr[j] to (arr[i] – i) = -(arr[j] – j). Now, the problem is reduced to finding all the pairs of the form (x, -x).
So, update all the elements of the array as arr[i] = arr[i] – i according to the reduction from step 1.
In order to count all the pairs of the form (x, -x), save the frequencies of all the negative elements into a HashMap named negMap and of all the positive elements (including 0) into posMap.
Now, for every frequency in posMap say x, find the frequency of -x in negMap. So, all the possible pairs between x and -x will be count = count + (frequency(x) * frequency(-x)).
Print the count at the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the count of pairs that// satisfy the given conditionint countValidPairs(int arr[], int n){ int i; // Update all the elements as describde // in the approach for (i = 0; i < n; i++) arr[i] -= i; // HashMap for storing the frequency of // negative elements map<int, int> negMap; // HashMap for storing the frequency of // positive elements (including 0) map<int, int> posMap; for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If HashMap already contains the integer // then increment its frequency by 1 if (negMap.count(arr[i])) negMap.insert({arr[i], negMap.find(arr[i])->second + 1}); else // Else set the frequency to 1 negMap.insert({arr[i], 1}); } // For positive elements (including 0) else { // If HashMap already contains the integer // then increment its frequency by 1 if (posMap.count(arr[i])) posMap.insert({arr[i], posMap.find(arr[i])->second + 1}); else // Else set the frequency to 1 posMap.insert({arr[i], 1}); } } // To store the count of valid pairs int count = 0; for (auto itr = posMap.begin(); itr != posMap.end(); ++itr) { int posVal = itr->second; // If an equivalent -ve element is found for // the current +ve element if (negMap.count(-itr->first)) { int negVal = negMap.find(-itr->first)->second; // Add all possible pairs to the count count += (negVal * posVal); } } // Return the count return count;} // Driver codeint main(){ int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countValidPairs(arr, n); } // This code is contributed by ApurvaRaj
import java.util.HashMap;import java.util.Map;public class GFG { // Function to return the count of pairs that // satisfy the given condition static int countValidPairs(int arr[], int n) { int i; // Update all the elements as describde // in the approach for (i = 0; i < n; i++) arr[i] -= i; // HashMap for storing the frequency of // negative elements Map<Integer, Integer> negMap = new HashMap<>(); // HashMap for storing the frequency of // positive elements (including 0) Map<Integer, Integer> posMap = new HashMap<>(); for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If HashMap already contains the integer // then increment its frequency by 1 if (negMap.containsKey(arr[i])) negMap.put(arr[i], negMap.get(arr[i]) + 1); else // Else set the frequency to 1 negMap.put(arr[i], 1); } // For positive elements (including 0) else { // If HashMap already contains the integer // then increment its frequency by 1 if (posMap.containsKey(arr[i])) posMap.put(arr[i], posMap.get(arr[i]) + 1); else // Else set the frequency to 1 posMap.put(arr[i], 1); } } // To store the count of valid pairs int count = 0; for (int posKey : posMap.keySet()) { int posVal = posMap.get(posKey); // If an equivalent -ve element is found for // the current +ve element if (negMap.containsKey(-posKey)) { int negVal = negMap.get(-posKey); // Add all possible pairs to the count count += (negVal * posVal); } } // Return the count return count; } // Driver code public static void main(String[] args) { int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 }; int n = arr.length; System.out.println(countValidPairs(arr, n)); }}
# Function to return the count of pairs that# satisfy the given conditiondef countValidPairs(arr, n): i = 0 # Update all the elements as described # in the approach for i in range(n): arr[i] -= i # HashMap for storing the frequency # of negative elements negMap = dict() # HashMap for storing the frequency of # positive elements (including 0) posMap = dict() for i in range(n): # For negative elements if (arr[i] < 0): # If HashMap already contains the integer # then increment its frequency by 1 negMap[arr[i]] = negMap.get(arr[i], 0) + 1 # For positive elements (including 0) else: # If HashMap already contains the integer # then increment its frequency by 1 posMap[arr[i]] = posMap.get(arr[i], 0) + 1 # To store the count of valid pairs count = 0 for posKey in posMap: posVal = posMap[posKey] negVal = 0 if -posKey in negMap: negVal = negMap[-posKey] # Add all possible pairs to the count count += (negVal * posVal) # Return the count return count # Driver codearr = [8, 4, 2, 1, 5, 4, 2, 1, 2, 3]n = len(arr)print(countValidPairs(arr, n)) # This code is contributed# by mohit kumar
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count// of pairs that satisfy the given// conditionstatic int countValidPairs(int []arr, int n){ int i; // Update all the elements // as described in the approach for (i = 0; i < n; i++) arr[i] -= i; // Dictionary for storing the // frequency of negative elements Dictionary<int, int> negMap = new Dictionary<int, int>(); // Dictionary for storing the // frequency of positive elements // (including 0) Dictionary<int, int> posMap = new Dictionary<int, int>(); for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If Dictionary already // contains the integer then // increment its frequency by 1 if (negMap.ContainsKey(arr[i])) negMap[arr[i]] = negMap[arr[i]] + 1; else // Else set the frequency to 1 negMap.Add(arr[i], 1); } // For positive elements (including 0) else { // If Dictionary already contains // the integer then increment its // frequency by 1 if (posMap.ContainsKey(arr[i])) posMap.Add(arr[i], posMap[arr[i]] + 1); else // Else set the frequency to 1 posMap.Add(arr[i], 1); } } // To store the count of valid pairs int count = 0; foreach (int posKey in posMap.Keys) { int posVal = posMap[posKey]; // If an equivalent -ve element // is found for the current +ve element if (negMap.ContainsKey(-posKey)) { int negVal = negMap[-posKey]; // Add all possible pairs to // the count count += (negVal * posVal); } } // Return the count return count;} // Driver codepublic static void Main(String[] args){ int []arr = {8, 4, 2, 1, 5, 4, 2, 1, 2, 3}; int n = arr.Length; Console.WriteLine(countValidPairs(arr, n));}} // This code is contributed by Rajput-Ji
<script> // Function to return the count of pairs that// satisfy the given conditionfunction countValidPairs(arr,n){ let i; // Update all the elements as describde // in the approach for (i = 0; i < n; i++) arr[i] -= i; // HashMap for storing the frequency of // negative elements let negMap = new Map(); // HashMap for storing the frequency of // positive elements (including 0) let posMap = new Map(); for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If HashMap already contains the integer // then increment its frequency by 1 if (negMap.has(arr[i])) negMap.set(arr[i], negMap.get(arr[i]) + 1); else // Else set the frequency to 1 negMap.set(arr[i], 1); } // For positive elements (including 0) else { // If HashMap already contains the integer // then increment its frequency by 1 if (posMap.has(arr[i])) posMap.set(arr[i], posMap.get(arr[i]) + 1); else // Else set the frequency to 1 posMap.set(arr[i], 1); } } // To store the count of valid pairs let count = 0; for (let posKey of posMap.keys()) { let posVal = posMap.get(posKey); // If an equivalent -ve element is found for // the current +ve element if (negMap.has(-posKey)) { let negVal = negMap.get(-posKey); // Add all possible pairs to the count count += (negVal * posVal); } } // Return the count return count;} // Driver codelet arr=[8, 4, 2, 1, 5, 4, 2, 1, 2, 3];let n = arr.length;document.write(countValidPairs(arr, n)); // This code is contributed by rag2127</script>
1
ankthon
ukasp
Shivi_Aggarwal
Akanksha_Rai
mohit kumar 29
ApurvaRaj
Rajput-Ji
avanitrachhadiya2155
rag2127
Hash
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 24633,
"s": 24429,
"text": "Given an array of integers arr[], the task is to count all the pairs (arr[i], arr[j]) such that i + j = arr[i] + arr[j] for all 0 ≤ i < j < n. Note: Pairs (x, y) and (y, x) are considered a single pair. "
},
{
"code": null,
"e": 24644,
"s": 24633,
"text": "Examples: "
},
{
"code": null,
"e": 24796,
"s": 24644,
"text": "Input: arr[] = {8, 4, 2, 1, 5, 4, 2, 1, 2, 3} Output: 1 The only possible pair is (arr[4], arr[5]) i.e. (5, 4) i + j = arr[i] + arr[j] => 4 + 5 = 5 + 4"
},
{
"code": null,
"e": 24835,
"s": 24796,
"text": "Input: arr[] = {1, 0, 3, 2} Output: 4 "
},
{
"code": null,
"e": 25096,
"s": 24835,
"text": "Naive Approach: Run two nested loops and check every possible pair for the condition where i + j = arr[i] + arr[j]. If the condition is satisfied, then update the count = count + 1. Print the count at the end.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25100,
"s": 25096,
"text": "C++"
},
{
"code": null,
"e": 25105,
"s": 25100,
"text": "Java"
},
{
"code": null,
"e": 25113,
"s": 25105,
"text": "Python3"
},
{
"code": null,
"e": 25116,
"s": 25113,
"text": "C#"
},
{
"code": null,
"e": 25120,
"s": 25116,
"text": "PHP"
},
{
"code": null,
"e": 25131,
"s": 25120,
"text": "Javascript"
},
{
"code": "// C++ program to count all the pairs that// hold the condition i + j = arr[i] + arr[j]#include <iostream>using namespace std; // Function to return the count of pairs that// satisfy the given conditionint CountPairs(int arr[], int n){ int count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count;} // Driver codeint main(){ int arr[] = { 1, 0, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << CountPairs(arr, n); return 0;}",
"e": 25802,
"s": 25131,
"text": null
},
{
"code": "// Java program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] public class GFG { // Function to return the count of pairs that // satisfy the given condition static int CountPairs(int arr[], int n) { int count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count; } // Driver code public static void main(String args[]) { int arr[] = { 1, 0, 3, 2 }; int n = arr.length ; System.out.print(CountPairs(arr, n)); } // This code is contributed by Ryuga.}",
"e": 26612,
"s": 25802,
"text": null
},
{
"code": "# Python 3 program to count all the pairs that# hold the condition i + j = arr[i] + arr[j] # Function to return the count of pairs# that satisfy the given conditiondef CountPairs(arr, n): count = 0; # Generate all possible pairs and increment # the count if the condition is satisfied for i in range(n - 1): for j in range(i + 1, n): if ((i + j) == (arr[i] + arr[j])): count += 1; return count; # Driver codearr = [ 1, 0, 3, 2 ];n = len(arr);print(CountPairs(arr, n)); # This code is contributed# by Akanksha Rai",
"e": 27175,
"s": 26612,
"text": null
},
{
"code": "using System; // C# program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] public class GFG { // Function to return the count of pairs that // satisfy the given condition static int CountPairs(int[] arr, int n) { int count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count; } // Driver code public static void Main() { int[] arr = { 1, 0, 3, 2 }; int n = arr.Length ; Console.Write(CountPairs(arr, n)); } }",
"e": 27945,
"s": 27175,
"text": null
},
{
"code": "<?php// PHP program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] // Function to return the count of pairs// that satisfy the given conditionfunction CountPairs(&$arr, $n){ $count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for ($i = 0; $i < $n - 1; $i++) { for ($j = $i + 1; $j < $n; $j++) { if (($i + $j) == ($arr[$i] + $arr[$j])) $count++; } } return $count;} // Driver code$arr = array(1, 0, 3, 2 );$n = sizeof($arr);echo(CountPairs($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 28589,
"s": 27945,
"text": null
},
{
"code": "<script>// Javascript program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] // Function to return the count of pairs that // satisfy the given condition function CountPairs(arr,n) { let count = 0; // Generate all possible pairs and increment // the count if the condition is satisfied for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { if ((i + j) == (arr[i] + arr[j])) count++; } } return count; } // Driver code let arr=[1, 0, 3, 2]; let n = arr.length ; document.write(CountPairs(arr, n)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 29329,
"s": 28589,
"text": null
},
{
"code": null,
"e": 29331,
"s": 29329,
"text": "4"
},
{
"code": null,
"e": 29355,
"s": 29333,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 29990,
"s": 29355,
"text": "Reduce i + j = arr[i] + arr[j] to (arr[i] – i) = -(arr[j] – j). Now, the problem is reduced to finding all the pairs of the form (x, -x).So, update all the elements of the array as arr[i] = arr[i] – i according to the reduction from step 1.In order to count all the pairs of the form (x, -x), save the frequencies of all the negative elements into a HashMap named negMap and of all the positive elements (including 0) into posMap.Now, for every frequency in posMap say x, find the frequency of -x in negMap. So, all the possible pairs between x and -x will be count = count + (frequency(x) * frequency(-x)).Print the count at the end."
},
{
"code": null,
"e": 30128,
"s": 29990,
"text": "Reduce i + j = arr[i] + arr[j] to (arr[i] – i) = -(arr[j] – j). Now, the problem is reduced to finding all the pairs of the form (x, -x)."
},
{
"code": null,
"e": 30232,
"s": 30128,
"text": "So, update all the elements of the array as arr[i] = arr[i] – i according to the reduction from step 1."
},
{
"code": null,
"e": 30423,
"s": 30232,
"text": "In order to count all the pairs of the form (x, -x), save the frequencies of all the negative elements into a HashMap named negMap and of all the positive elements (including 0) into posMap."
},
{
"code": null,
"e": 30601,
"s": 30423,
"text": "Now, for every frequency in posMap say x, find the frequency of -x in negMap. So, all the possible pairs between x and -x will be count = count + (frequency(x) * frequency(-x))."
},
{
"code": null,
"e": 30629,
"s": 30601,
"text": "Print the count at the end."
},
{
"code": null,
"e": 30680,
"s": 30629,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30684,
"s": 30680,
"text": "C++"
},
{
"code": null,
"e": 30689,
"s": 30684,
"text": "Java"
},
{
"code": null,
"e": 30697,
"s": 30689,
"text": "Python3"
},
{
"code": null,
"e": 30700,
"s": 30697,
"text": "C#"
},
{
"code": null,
"e": 30711,
"s": 30700,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the count of pairs that// satisfy the given conditionint countValidPairs(int arr[], int n){ int i; // Update all the elements as describde // in the approach for (i = 0; i < n; i++) arr[i] -= i; // HashMap for storing the frequency of // negative elements map<int, int> negMap; // HashMap for storing the frequency of // positive elements (including 0) map<int, int> posMap; for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If HashMap already contains the integer // then increment its frequency by 1 if (negMap.count(arr[i])) negMap.insert({arr[i], negMap.find(arr[i])->second + 1}); else // Else set the frequency to 1 negMap.insert({arr[i], 1}); } // For positive elements (including 0) else { // If HashMap already contains the integer // then increment its frequency by 1 if (posMap.count(arr[i])) posMap.insert({arr[i], posMap.find(arr[i])->second + 1}); else // Else set the frequency to 1 posMap.insert({arr[i], 1}); } } // To store the count of valid pairs int count = 0; for (auto itr = posMap.begin(); itr != posMap.end(); ++itr) { int posVal = itr->second; // If an equivalent -ve element is found for // the current +ve element if (negMap.count(-itr->first)) { int negVal = negMap.find(-itr->first)->second; // Add all possible pairs to the count count += (negVal * posVal); } } // Return the count return count;} // Driver codeint main(){ int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countValidPairs(arr, n); } // This code is contributed by ApurvaRaj",
"e": 32737,
"s": 30711,
"text": null
},
{
"code": "import java.util.HashMap;import java.util.Map;public class GFG { // Function to return the count of pairs that // satisfy the given condition static int countValidPairs(int arr[], int n) { int i; // Update all the elements as describde // in the approach for (i = 0; i < n; i++) arr[i] -= i; // HashMap for storing the frequency of // negative elements Map<Integer, Integer> negMap = new HashMap<>(); // HashMap for storing the frequency of // positive elements (including 0) Map<Integer, Integer> posMap = new HashMap<>(); for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If HashMap already contains the integer // then increment its frequency by 1 if (negMap.containsKey(arr[i])) negMap.put(arr[i], negMap.get(arr[i]) + 1); else // Else set the frequency to 1 negMap.put(arr[i], 1); } // For positive elements (including 0) else { // If HashMap already contains the integer // then increment its frequency by 1 if (posMap.containsKey(arr[i])) posMap.put(arr[i], posMap.get(arr[i]) + 1); else // Else set the frequency to 1 posMap.put(arr[i], 1); } } // To store the count of valid pairs int count = 0; for (int posKey : posMap.keySet()) { int posVal = posMap.get(posKey); // If an equivalent -ve element is found for // the current +ve element if (negMap.containsKey(-posKey)) { int negVal = negMap.get(-posKey); // Add all possible pairs to the count count += (negVal * posVal); } } // Return the count return count; } // Driver code public static void main(String[] args) { int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 }; int n = arr.length; System.out.println(countValidPairs(arr, n)); }}",
"e": 34954,
"s": 32737,
"text": null
},
{
"code": "# Function to return the count of pairs that# satisfy the given conditiondef countValidPairs(arr, n): i = 0 # Update all the elements as described # in the approach for i in range(n): arr[i] -= i # HashMap for storing the frequency # of negative elements negMap = dict() # HashMap for storing the frequency of # positive elements (including 0) posMap = dict() for i in range(n): # For negative elements if (arr[i] < 0): # If HashMap already contains the integer # then increment its frequency by 1 negMap[arr[i]] = negMap.get(arr[i], 0) + 1 # For positive elements (including 0) else: # If HashMap already contains the integer # then increment its frequency by 1 posMap[arr[i]] = posMap.get(arr[i], 0) + 1 # To store the count of valid pairs count = 0 for posKey in posMap: posVal = posMap[posKey] negVal = 0 if -posKey in negMap: negVal = negMap[-posKey] # Add all possible pairs to the count count += (negVal * posVal) # Return the count return count # Driver codearr = [8, 4, 2, 1, 5, 4, 2, 1, 2, 3]n = len(arr)print(countValidPairs(arr, n)) # This code is contributed# by mohit kumar",
"e": 36270,
"s": 34954,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count// of pairs that satisfy the given// conditionstatic int countValidPairs(int []arr, int n){ int i; // Update all the elements // as described in the approach for (i = 0; i < n; i++) arr[i] -= i; // Dictionary for storing the // frequency of negative elements Dictionary<int, int> negMap = new Dictionary<int, int>(); // Dictionary for storing the // frequency of positive elements // (including 0) Dictionary<int, int> posMap = new Dictionary<int, int>(); for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If Dictionary already // contains the integer then // increment its frequency by 1 if (negMap.ContainsKey(arr[i])) negMap[arr[i]] = negMap[arr[i]] + 1; else // Else set the frequency to 1 negMap.Add(arr[i], 1); } // For positive elements (including 0) else { // If Dictionary already contains // the integer then increment its // frequency by 1 if (posMap.ContainsKey(arr[i])) posMap.Add(arr[i], posMap[arr[i]] + 1); else // Else set the frequency to 1 posMap.Add(arr[i], 1); } } // To store the count of valid pairs int count = 0; foreach (int posKey in posMap.Keys) { int posVal = posMap[posKey]; // If an equivalent -ve element // is found for the current +ve element if (negMap.ContainsKey(-posKey)) { int negVal = negMap[-posKey]; // Add all possible pairs to // the count count += (negVal * posVal); } } // Return the count return count;} // Driver codepublic static void Main(String[] args){ int []arr = {8, 4, 2, 1, 5, 4, 2, 1, 2, 3}; int n = arr.Length; Console.WriteLine(countValidPairs(arr, n));}} // This code is contributed by Rajput-Ji",
"e": 38317,
"s": 36270,
"text": null
},
{
"code": "<script> // Function to return the count of pairs that// satisfy the given conditionfunction countValidPairs(arr,n){ let i; // Update all the elements as describde // in the approach for (i = 0; i < n; i++) arr[i] -= i; // HashMap for storing the frequency of // negative elements let negMap = new Map(); // HashMap for storing the frequency of // positive elements (including 0) let posMap = new Map(); for (i = 0; i < n; i++) { // For negative elements if (arr[i] < 0) { // If HashMap already contains the integer // then increment its frequency by 1 if (negMap.has(arr[i])) negMap.set(arr[i], negMap.get(arr[i]) + 1); else // Else set the frequency to 1 negMap.set(arr[i], 1); } // For positive elements (including 0) else { // If HashMap already contains the integer // then increment its frequency by 1 if (posMap.has(arr[i])) posMap.set(arr[i], posMap.get(arr[i]) + 1); else // Else set the frequency to 1 posMap.set(arr[i], 1); } } // To store the count of valid pairs let count = 0; for (let posKey of posMap.keys()) { let posVal = posMap.get(posKey); // If an equivalent -ve element is found for // the current +ve element if (negMap.has(-posKey)) { let negVal = negMap.get(-posKey); // Add all possible pairs to the count count += (negVal * posVal); } } // Return the count return count;} // Driver codelet arr=[8, 4, 2, 1, 5, 4, 2, 1, 2, 3];let n = arr.length;document.write(countValidPairs(arr, n)); // This code is contributed by rag2127</script>",
"e": 40348,
"s": 38317,
"text": null
},
{
"code": null,
"e": 40350,
"s": 40348,
"text": "1"
},
{
"code": null,
"e": 40360,
"s": 40352,
"text": "ankthon"
},
{
"code": null,
"e": 40366,
"s": 40360,
"text": "ukasp"
},
{
"code": null,
"e": 40381,
"s": 40366,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 40394,
"s": 40381,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 40409,
"s": 40394,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 40419,
"s": 40409,
"text": "ApurvaRaj"
},
{
"code": null,
"e": 40429,
"s": 40419,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40450,
"s": 40429,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 40458,
"s": 40450,
"text": "rag2127"
},
{
"code": null,
"e": 40463,
"s": 40458,
"text": "Hash"
},
{
"code": null,
"e": 40470,
"s": 40463,
"text": "Arrays"
},
{
"code": null,
"e": 40475,
"s": 40470,
"text": "Hash"
},
{
"code": null,
"e": 40482,
"s": 40475,
"text": "Arrays"
},
{
"code": null,
"e": 40487,
"s": 40482,
"text": "Hash"
},
{
"code": null,
"e": 40585,
"s": 40487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40594,
"s": 40585,
"text": "Comments"
},
{
"code": null,
"e": 40607,
"s": 40594,
"text": "Old Comments"
},
{
"code": null,
"e": 40628,
"s": 40607,
"text": "Next Greater Element"
},
{
"code": null,
"e": 40653,
"s": 40628,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 40680,
"s": 40653,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 40729,
"s": 40680,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 40767,
"s": 40729,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 40803,
"s": 40767,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 40834,
"s": 40803,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 40861,
"s": 40834,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 40895,
"s": 40861,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
Tryit Editor v3.7
|
Tryit: CSS padding
|
[] |
Open New Browser Tab in Selenuim
|
Answer − We can open a new browser tab in Selenium webdriver. The methods - Keys.chord and sendKeys are required to achieve this task. The Keys.chord method is used to send multiple keys at once.
We shall pass Keys.CONTROL and Keys.ENTER as parameters to this method. The complete string is again passed as a parameter to the sendKeys. Finally, the method sendKeys shall be applied on the link which we want to open in a new tab
Syntax
String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Links']")). sendKeys(l);
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class OpenNewTab{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
// wait of 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// Keys.Chord string
String l = Keys.chord(Keys.CONTROL,Keys.ENTER);
// open new tab
driver.findElement(By.xpath("//*[text()='Terms of Use']")).sendKeys(l);
}
}
|
[
{
"code": null,
"e": 1258,
"s": 1062,
"text": "Answer − We can open a new browser tab in Selenium webdriver. The methods - Keys.chord and sendKeys are required to achieve this task. The Keys.chord method is used to send multiple keys at once."
},
{
"code": null,
"e": 1491,
"s": 1258,
"text": "We shall pass Keys.CONTROL and Keys.ENTER as parameters to this method. The complete string is again passed as a parameter to the sendKeys. Finally, the method sendKeys shall be applied on the link which we want to open in a new tab"
},
{
"code": null,
"e": 1498,
"s": 1491,
"text": "Syntax"
},
{
"code": null,
"e": 1612,
"s": 1498,
"text": "String l = Keys.chord(Keys.CONTROL,Keys.ENTER);\ndriver.findElement(By.xpath(\"//*[text()='Links']\")). sendKeys(l);"
},
{
"code": null,
"e": 1632,
"s": 1612,
"text": "Code Implementation"
},
{
"code": null,
"e": 2468,
"s": 1632,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.Keys;\npublic class OpenNewTab{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n // wait of 5 seconds\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //url launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // Keys.Chord string\n String l = Keys.chord(Keys.CONTROL,Keys.ENTER);\n // open new tab\n driver.findElement(By.xpath(\"//*[text()='Terms of Use']\")).sendKeys(l);\n }\n}"
}
] |
Angular Material - List
|
The md-list, an Angular directive, is a container component that contains the md-list-item elements as children. The md-list-item directive is a container component for row items of md-list container. The CSS classes, md-2-line and md-3-line, can be added to md-list-item to increase the height of row with 22px and 40px respectively.
The following example shows the use of md-list directive and also the uses of lists.
am_lists.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('listController', listController);
function listController ($scope) {
var self = this;
self.allContacts = loadContacts();
self.contacts = [self.allContacts[0]];
function loadContacts() {
var contacts = [
'Roberto Karlos',
'Bob Crestor',
'Nigel Rick',
'Narayana Garner'
];
return contacts.map(function (c, index) {
var cParts = c.split(' ');
var contact = {
name: c,
email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase()
+ '@example.com',
image: 'http://lorempixel.com/50/50/people?' + index
};
contact._lowername = contact.name.toLowerCase();
return contact;
});
}
}
</script>
</head>
<body ng-app = "firstApplication">
<div id = "listContainer" ng-controller = "listController as ctrl"
layout = "column" ng-cloak>
<md-content>
<md-list>
<md-subheader class = "md-no-sticky">Contacts</md-subheader>
<md-list-item class = "md-2-line contact-item"
ng-repeat = "(index, contact) in ctrl.allContacts"
ng-if = "ctrl.contacts.indexOf(contact) < 0">
<img ng-src = "{{contact.image}}" class = "md-avatar"
alt = "{{contact.name}}" />
<div class = "md-list-item-text compact">
<h3>{{contact.name}}</h3>
<p>{{contact.email}}</p>
</div>
<md-divider ng-if = "!$last"></md-divider>
</md-list-item>
</md-list>
<md-list>
<md-subheader class = "md-no-sticky">Contacts (With Insets)</md-subheader>
<md-list-item class = "md-2-line contact-item"
ng-repeat = "(index, contact) in ctrl.allContacts"
ng-if = "ctrl.contacts.indexOf(contact) < 0">
<img ng-src = "{{contact.image}}" class = "md-avatar"
alt = "{{contact.name}}" />
<div class = "md-list-item-text compact">
<h3>{{contact.name}}</h3>
<p>{{contact.email}}</p>
</div>
<md-divider md-inset ng-if = "!$last"></md-divider>
</md-list-item>
</md-list>
</md-content>
</div>
</body>
</html>
Verify the result.
{{contact.email}}
{{contact.email}}
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2525,
"s": 2190,
"text": "The md-list, an Angular directive, is a container component that contains the md-list-item elements as children. The md-list-item directive is a container component for row items of md-list container. The CSS classes, md-2-line and md-3-line, can be added to md-list-item to increase the height of row with 22px and 40px respectively."
},
{
"code": null,
"e": 2610,
"s": 2525,
"text": "The following example shows the use of md-list directive and also the uses of lists."
},
{
"code": null,
"e": 2623,
"s": 2610,
"text": "am_lists.htm"
},
{
"code": null,
"e": 6333,
"s": 2623,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('listController', listController);\n\n function listController ($scope) {\n var self = this; \n self.allContacts = loadContacts();\n self.contacts = [self.allContacts[0]];\n \n function loadContacts() {\n var contacts = [\n 'Roberto Karlos',\n 'Bob Crestor',\n 'Nigel Rick',\n 'Narayana Garner' \n ];\n \n return contacts.map(function (c, index) {\n var cParts = c.split(' ');\n var contact = {\n name: c,\n email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase()\n + '@example.com',\n image: 'http://lorempixel.com/50/50/people?' + index\n };\n contact._lowername = contact.name.toLowerCase();\n return contact;\n });\n }\n } \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"listContainer\" ng-controller = \"listController as ctrl\"\n layout = \"column\" ng-cloak>\n <md-content>\n <md-list>\n <md-subheader class = \"md-no-sticky\">Contacts</md-subheader>\n <md-list-item class = \"md-2-line contact-item\"\n ng-repeat = \"(index, contact) in ctrl.allContacts\"\n ng-if = \"ctrl.contacts.indexOf(contact) < 0\">\n <img ng-src = \"{{contact.image}}\" class = \"md-avatar\"\n alt = \"{{contact.name}}\" />\n \n <div class = \"md-list-item-text compact\">\n <h3>{{contact.name}}</h3>\n <p>{{contact.email}}</p>\n </div>\n \n <md-divider ng-if = \"!$last\"></md-divider>\n </md-list-item>\n </md-list>\n \n <md-list>\n <md-subheader class = \"md-no-sticky\">Contacts (With Insets)</md-subheader>\n <md-list-item class = \"md-2-line contact-item\"\n ng-repeat = \"(index, contact) in ctrl.allContacts\"\n ng-if = \"ctrl.contacts.indexOf(contact) < 0\">\n <img ng-src = \"{{contact.image}}\" class = \"md-avatar\"\n alt = \"{{contact.name}}\" />\n \n <div class = \"md-list-item-text compact\">\n <h3>{{contact.name}}</h3>\n <p>{{contact.email}}</p>\n </div>\n \n <md-divider md-inset ng-if = \"!$last\"></md-divider>\n </md-list-item>\n </md-list>\n \n </md-content>\t \n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 6352,
"s": 6333,
"text": "Verify the result."
},
{
"code": null,
"e": 6370,
"s": 6352,
"text": "{{contact.email}}"
},
{
"code": null,
"e": 6388,
"s": 6370,
"text": "{{contact.email}}"
},
{
"code": null,
"e": 6423,
"s": 6388,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6437,
"s": 6423,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6472,
"s": 6437,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6486,
"s": 6472,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6521,
"s": 6486,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6541,
"s": 6521,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6576,
"s": 6541,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6593,
"s": 6576,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6626,
"s": 6593,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6638,
"s": 6626,
"text": " Senol Atac"
},
{
"code": null,
"e": 6673,
"s": 6638,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6685,
"s": 6673,
"text": " Senol Atac"
},
{
"code": null,
"e": 6692,
"s": 6685,
"text": " Print"
},
{
"code": null,
"e": 6703,
"s": 6692,
"text": " Add Notes"
}
] |
Rexx - If statement
|
The first decision-making statement is the if statement. An if statement consists of a Boolean expression followed by one or more statements.
The general form of this statement in Rexx is as follows −
if (condition) then
do
#statement1
#statement2
end
In Rexx, the condition is an expression which evaluates to either true or false. If the condition is true, then the subsequent statements in the loop are executed.
The following diagram shows the diagrammatic explanation of this loop.
In the above diagram, you can see that only if the condition is evaluated to true does the conditional code gets executed.
The following program is an example of the simple if expression in Rexx.
/* Main program */
i = 5
if (i < 10) then
do
say "i is less than 10"
end
The following key things need to be noted about the above program −
The if statement is used to first evaluate if the value of i is less than 10.
The if statement is used to first evaluate if the value of i is less than 10.
If yes, then the statement inside the do loop is evaluated.
If yes, then the statement inside the do loop is evaluated.
The output of the above program will be −
i is less than 10
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2481,
"s": 2339,
"text": "The first decision-making statement is the if statement. An if statement consists of a Boolean expression followed by one or more statements."
},
{
"code": null,
"e": 2540,
"s": 2481,
"text": "The general form of this statement in Rexx is as follows −"
},
{
"code": null,
"e": 2614,
"s": 2540,
"text": "if (condition) then \n do \n #statement1 \n #statement2 \n end\n"
},
{
"code": null,
"e": 2778,
"s": 2614,
"text": "In Rexx, the condition is an expression which evaluates to either true or false. If the condition is true, then the subsequent statements in the loop are executed."
},
{
"code": null,
"e": 2849,
"s": 2778,
"text": "The following diagram shows the diagrammatic explanation of this loop."
},
{
"code": null,
"e": 2972,
"s": 2849,
"text": "In the above diagram, you can see that only if the condition is evaluated to true does the conditional code gets executed."
},
{
"code": null,
"e": 3045,
"s": 2972,
"text": "The following program is an example of the simple if expression in Rexx."
},
{
"code": null,
"e": 3136,
"s": 3045,
"text": "/* Main program */ \ni = 5 \n\nif (i < 10) then \n do \n say \"i is less than 10\" \n end"
},
{
"code": null,
"e": 3204,
"s": 3136,
"text": "The following key things need to be noted about the above program −"
},
{
"code": null,
"e": 3282,
"s": 3204,
"text": "The if statement is used to first evaluate if the value of i is less than 10."
},
{
"code": null,
"e": 3360,
"s": 3282,
"text": "The if statement is used to first evaluate if the value of i is less than 10."
},
{
"code": null,
"e": 3420,
"s": 3360,
"text": "If yes, then the statement inside the do loop is evaluated."
},
{
"code": null,
"e": 3480,
"s": 3420,
"text": "If yes, then the statement inside the do loop is evaluated."
},
{
"code": null,
"e": 3522,
"s": 3480,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 3542,
"s": 3522,
"text": "i is less than 10 \n"
},
{
"code": null,
"e": 3549,
"s": 3542,
"text": " Print"
},
{
"code": null,
"e": 3560,
"s": 3549,
"text": " Add Notes"
}
] |
Ear Biometrics — Machine Learning a little further... | by Hitesh Valecha | Towards Data Science
|
Like other biometric using face, iris, and finger, the ear as a biometric contains a large amount of specific and unique features that allow for human identification. The ear morphology changes slightly after the age of 10 years and medical studies have shown that significant changes in the shape of the ear happen only before the age of 8 years and after the age of 70 years. It does grow symmetrically in size and begins to bulge downwards as the person ages, but that is a measurable effect. Studies suggest that ear changes only 1.22 mm per year. Also, the color distribution of ear, unlike face, is almost uniform. The position of the ear is almost in the middle of the profile face. Ear data can be captured even without the awareness of the subject from a distance. Ear biometrics can stand as an excellent example for passive biometrics and does not need much cooperation from the subject, which meets the demand of the secrecy of the authentication system present in the environment.
A digital camera takes the profile face images of the subjects in the environment from different angles, from which the section of the ear is segmented, preprocessed. The feature vectors are then analyzed in different test cases which consist of the rotation of the face in the same plane, different plane, different light conditions, etc. will be given to the machine learning model as input which would be trained to recognize a person in the environment. The process, though complicated, would develop a system which would provide an authenticated ear-based biometric identification system.
Controlled Environment
The purpose of CAMERA A is to get a clear shot of the profile face without expecting much tilt or rotation of the ear. Meanwhile, CAMERA B and CAMERA C are used for capturing more profile photos for multiple images of the same person to form the feature matrices.
Segmentation of ear from profile face —
Image (a) is the profile face captured from camera. In image (b) topographical labeling is done. Topographical labeling is used to find curved surfaces and edges. Image (c)is the difference of erosion & dilation i.e. applying morphological operations on the profile face to sharpen the features. Image (d) is the simple dot product of (b) & (c). Image (e) is obtained by blurring (d) 10 times so that connected component analysis can be applied. The complexity of each connected component is found and shaded with differentcolors in image (f). As the highest complexity region is found out to be ear, it is segmented and converted into grayscale in image (g) for faster computation.
Dataset and Preprocessing
Dataset preparation is the first step towards any machine learning model. In this system, a deep neural network is used to obtain the features and characteristics of the subjects in the environment. A large dataset is required to feed as an input to the Neural Network. At least 500 images per subject to train the network properly because all the classes are the images of ears machine can be easily confused with the features and characteristics, the more samples per subject, the easier it is to find the distinct features. The dataset should cover a wide range of variety of images e.g images with different light conditions, different angles, Gaussian filter, blur, etc.
There are small occlusions to be covered also while training the CNN network like ear covered with hair or earphones or jewels. Image augmentation is useful to generate multiple copies of images with slight variations to increase the dataset. For example, the data generator of Keras can be used.
DATADIR = "./dataset"CATEGORIES = ["Subject1", "Subject2", "Subject3", "Subject4"]for category in CATEGORIES: path = os.path.join(DATADIR, category) for img in os.listdir(path): img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) break breakIMG_WIDTH = 60IMG_HEIGHT = 100new_array = cv2.resize(img_array, (IMG_WIDTH, IMG_HEIGHT))training_data = []def create_training_data(): for category in CATEGORIES: path = os.path.join(DATADIR, category) class_num = CATEGORIES.index(category) for img in os.listdir(path): try: img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(img_array, (IMG_WIDTH, IMG_HEIGHT)) training_data.append([new_array, class_num]) except Exception as e: passcreate_training_data()print(len(training_data))random.shuffle(training_data)
Convolutional Neural Network
As we are working with an image dataset (instead of .csv files or numeric data), CNN is used after the data preprocessing is done. The preprocessed data is passed to the architecture of the neural network. As the ear has less surface area than the face the computation time required for the ear is less. The grayscale images are taken by the input layer of the network.
Stride convolution and max-pooling is used to increase the depth (features) in each hidden layer.
Convolution filter reduces 9 image pixels to generate a single pixel without affecting the features.
a = [] #feature setb = [] #labelsfor features, labels in training_data: a.append(features) b.append(labels)a = np.array(a).reshape(-1, IMG_WIDTH, IMG_HEIGHT, 1)
# Create the modelmodel = Sequential()model.add(Conv2D(32, kernel_size=4, strides=1,activation='relu', input_shape=(IMG_WIDTH, IMG_HEIGHT, 1)))model.add(Conv2D(32, kernel_size=4, strides=2,activation='relu'))model.add(MaxPooling2D(pool_size=2))model.add(Conv2D(64, kernel_size=4, strides=1,activation='relu'))model.add(MaxPooling2D(pool_size=2))# model.add(Conv2D(64, kernel_size=4, strides=2,activation='relu'))# model.add(Dropout(0.5))# model.add(Conv2D(64, kernel_size=4, strides=1,activation='relu'))# model.add(Conv2D(64, kernel_size=4, strides=2,activation='relu'))model.summary()model.add(Flatten())model.add(Dense(32, activation='relu'))model.add(Dropout(0.5))model.add(Dense(4, activation='softmax'))model.summary()# Compile the modelmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])# Train the modelmodel.fit(X_train, to_categorical(Y_train), batch_size=32, epochs=5)# Evaluate the modelscores = model.evaluate(X_test, to_categorical(Y_test))print('Loss: %.3f' % scores[0])print('Accuracy: %.3f' % scores[1])model.save('model_opt.h5')
In the final dense layer, Feature classification (FC) is done based on which the subjects are classified to a corresponding class of the network.
Graph shows the accuracy by the overlapping curves of the same class and distinct curves of different classes of the deep neural network.
Limitations
There would be cases of occlusions of different types like hair, earphones, or ear is injured or covered with cloth. The chances of an individual getting authenticated would become less. As the percent of pure ear taken for feature extraction is less so the accuracy would be affected. The system aims to concern small environment rooms like security rooms, board meetings, medical labs, etc.
Future Scope
The ear houses the smallest bones in the human body. That would be quite difficult for cybercriminals to duplicate. In addition, it can be used to measure temperature, blood flow, heart rate, and glucose levels. Ear biometric system will have diverse uses in the fields — authentication, access and attendance control, travel control, financial and other transactions requiring authorizations, remote voting, use of automated working devices, action control. e.g., nowadays airports use a combination of face & iris biometrics to authenticate a person, instead, a single ear biometric system can be used to achieve the authenticity of a person with the same accuracy. Every single feature of the body has an impact on how a person’s general personality is going to be like — face, eyes, palms & even handwriting. Personality analysis through handwriting is used to detect if the person is lying, etc. Similarly, the ear can be used for the personality analysis of a Person. Ear lobe has many features that can be used for Personality analysis — attached lobe, broad lobe, narrow ear, pointed ear, round lobe, square ear, ear sticking out, etc.
Summary
The most significant advantage of the Ear Biometric System is to identify the person without their knowledge/awareness. This feature will change the dynamics of passive biometrics and can bring complete automatism in the biometric field. Points to focus —
Large dataset (500 samples per subject) with a variety of images to train the learning model properly.
Preprocessing of images to reduce the computation time.
Good network architecture (without much loss or dropout).
Run enough epochs to train the network efficiently (with GPU, suggested).
Use the trained model to predict the person precisely.
Well, congratulations you made it to the end. Awesome. Click here to get the source code at my GitHub account.
Feel free to ask doubts because we are learning the same as the machines Hitesh Valecha..
References —
Ping Yan and Kevin W. Bowyer, Fellow, IEEE, “Biometric Recognition Using 3D Ear Shape,” IEEE Transactions on Pattern Analysis and Machine Intelligence, VOL. 29, NO. 8, AUGUST 2007John D. Bustard, Student Member, IEEE, and Mark S. Nixon, Associate Member, IEEE, “Toward Unconstrained Ear Recognition From Two-Dimensional Images,” IEEE Transactions on Systems, Man, and Cybernetics — Part A: Systems and Humans, VOL. 40, NO. 3, MAY 2010Bir Bhanu and Hui Chen, Center for Research in Intelligent Systems. Human Ear Recognition by Computer. California: University of California at Riverside [Online]. doi: 10.1007/978–1–84800–129–9.Eyad Haj Said,North Carolina Agricultural & Technical State University, Greensboro, NC, Ayman Abaza and Hany Ammar, Computer Science and Electrical Engineering Dep., West Virginia University, Morgantown, WV, “Ear Segmentation in Color Facial Images using Mathematical Morphology,” IEEE 2008.
Ping Yan and Kevin W. Bowyer, Fellow, IEEE, “Biometric Recognition Using 3D Ear Shape,” IEEE Transactions on Pattern Analysis and Machine Intelligence, VOL. 29, NO. 8, AUGUST 2007
John D. Bustard, Student Member, IEEE, and Mark S. Nixon, Associate Member, IEEE, “Toward Unconstrained Ear Recognition From Two-Dimensional Images,” IEEE Transactions on Systems, Man, and Cybernetics — Part A: Systems and Humans, VOL. 40, NO. 3, MAY 2010
Bir Bhanu and Hui Chen, Center for Research in Intelligent Systems. Human Ear Recognition by Computer. California: University of California at Riverside [Online]. doi: 10.1007/978–1–84800–129–9.
Eyad Haj Said,North Carolina Agricultural & Technical State University, Greensboro, NC, Ayman Abaza and Hany Ammar, Computer Science and Electrical Engineering Dep., West Virginia University, Morgantown, WV, “Ear Segmentation in Color Facial Images using Mathematical Morphology,” IEEE 2008.
|
[
{
"code": null,
"e": 1166,
"s": 172,
"text": "Like other biometric using face, iris, and finger, the ear as a biometric contains a large amount of specific and unique features that allow for human identification. The ear morphology changes slightly after the age of 10 years and medical studies have shown that significant changes in the shape of the ear happen only before the age of 8 years and after the age of 70 years. It does grow symmetrically in size and begins to bulge downwards as the person ages, but that is a measurable effect. Studies suggest that ear changes only 1.22 mm per year. Also, the color distribution of ear, unlike face, is almost uniform. The position of the ear is almost in the middle of the profile face. Ear data can be captured even without the awareness of the subject from a distance. Ear biometrics can stand as an excellent example for passive biometrics and does not need much cooperation from the subject, which meets the demand of the secrecy of the authentication system present in the environment."
},
{
"code": null,
"e": 1760,
"s": 1166,
"text": "A digital camera takes the profile face images of the subjects in the environment from different angles, from which the section of the ear is segmented, preprocessed. The feature vectors are then analyzed in different test cases which consist of the rotation of the face in the same plane, different plane, different light conditions, etc. will be given to the machine learning model as input which would be trained to recognize a person in the environment. The process, though complicated, would develop a system which would provide an authenticated ear-based biometric identification system."
},
{
"code": null,
"e": 1783,
"s": 1760,
"text": "Controlled Environment"
},
{
"code": null,
"e": 2047,
"s": 1783,
"text": "The purpose of CAMERA A is to get a clear shot of the profile face without expecting much tilt or rotation of the ear. Meanwhile, CAMERA B and CAMERA C are used for capturing more profile photos for multiple images of the same person to form the feature matrices."
},
{
"code": null,
"e": 2087,
"s": 2047,
"text": "Segmentation of ear from profile face —"
},
{
"code": null,
"e": 2770,
"s": 2087,
"text": "Image (a) is the profile face captured from camera. In image (b) topographical labeling is done. Topographical labeling is used to find curved surfaces and edges. Image (c)is the difference of erosion & dilation i.e. applying morphological operations on the profile face to sharpen the features. Image (d) is the simple dot product of (b) & (c). Image (e) is obtained by blurring (d) 10 times so that connected component analysis can be applied. The complexity of each connected component is found and shaded with differentcolors in image (f). As the highest complexity region is found out to be ear, it is segmented and converted into grayscale in image (g) for faster computation."
},
{
"code": null,
"e": 2796,
"s": 2770,
"text": "Dataset and Preprocessing"
},
{
"code": null,
"e": 3472,
"s": 2796,
"text": "Dataset preparation is the first step towards any machine learning model. In this system, a deep neural network is used to obtain the features and characteristics of the subjects in the environment. A large dataset is required to feed as an input to the Neural Network. At least 500 images per subject to train the network properly because all the classes are the images of ears machine can be easily confused with the features and characteristics, the more samples per subject, the easier it is to find the distinct features. The dataset should cover a wide range of variety of images e.g images with different light conditions, different angles, Gaussian filter, blur, etc."
},
{
"code": null,
"e": 3769,
"s": 3472,
"text": "There are small occlusions to be covered also while training the CNN network like ear covered with hair or earphones or jewels. Image augmentation is useful to generate multiple copies of images with slight variations to increase the dataset. For example, the data generator of Keras can be used."
},
{
"code": null,
"e": 4713,
"s": 3769,
"text": "DATADIR = \"./dataset\"CATEGORIES = [\"Subject1\", \"Subject2\", \"Subject3\", \"Subject4\"]for category in CATEGORIES: path = os.path.join(DATADIR, category) for img in os.listdir(path): img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) break breakIMG_WIDTH = 60IMG_HEIGHT = 100new_array = cv2.resize(img_array, (IMG_WIDTH, IMG_HEIGHT))training_data = []def create_training_data(): for category in CATEGORIES: path = os.path.join(DATADIR, category) class_num = CATEGORIES.index(category) for img in os.listdir(path): try: img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(img_array, (IMG_WIDTH, IMG_HEIGHT)) training_data.append([new_array, class_num]) except Exception as e: passcreate_training_data()print(len(training_data))random.shuffle(training_data)"
},
{
"code": null,
"e": 4742,
"s": 4713,
"text": "Convolutional Neural Network"
},
{
"code": null,
"e": 5112,
"s": 4742,
"text": "As we are working with an image dataset (instead of .csv files or numeric data), CNN is used after the data preprocessing is done. The preprocessed data is passed to the architecture of the neural network. As the ear has less surface area than the face the computation time required for the ear is less. The grayscale images are taken by the input layer of the network."
},
{
"code": null,
"e": 5210,
"s": 5112,
"text": "Stride convolution and max-pooling is used to increase the depth (features) in each hidden layer."
},
{
"code": null,
"e": 5311,
"s": 5210,
"text": "Convolution filter reduces 9 image pixels to generate a single pixel without affecting the features."
},
{
"code": null,
"e": 5488,
"s": 5311,
"text": "a = [] #feature setb = [] #labelsfor features, labels in training_data: a.append(features) b.append(labels)a = np.array(a).reshape(-1, IMG_WIDTH, IMG_HEIGHT, 1)"
},
{
"code": null,
"e": 6570,
"s": 5488,
"text": "# Create the modelmodel = Sequential()model.add(Conv2D(32, kernel_size=4, strides=1,activation='relu', input_shape=(IMG_WIDTH, IMG_HEIGHT, 1)))model.add(Conv2D(32, kernel_size=4, strides=2,activation='relu'))model.add(MaxPooling2D(pool_size=2))model.add(Conv2D(64, kernel_size=4, strides=1,activation='relu'))model.add(MaxPooling2D(pool_size=2))# model.add(Conv2D(64, kernel_size=4, strides=2,activation='relu'))# model.add(Dropout(0.5))# model.add(Conv2D(64, kernel_size=4, strides=1,activation='relu'))# model.add(Conv2D(64, kernel_size=4, strides=2,activation='relu'))model.summary()model.add(Flatten())model.add(Dense(32, activation='relu'))model.add(Dropout(0.5))model.add(Dense(4, activation='softmax'))model.summary()# Compile the modelmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])# Train the modelmodel.fit(X_train, to_categorical(Y_train), batch_size=32, epochs=5)# Evaluate the modelscores = model.evaluate(X_test, to_categorical(Y_test))print('Loss: %.3f' % scores[0])print('Accuracy: %.3f' % scores[1])model.save('model_opt.h5')"
},
{
"code": null,
"e": 6716,
"s": 6570,
"text": "In the final dense layer, Feature classification (FC) is done based on which the subjects are classified to a corresponding class of the network."
},
{
"code": null,
"e": 6854,
"s": 6716,
"text": "Graph shows the accuracy by the overlapping curves of the same class and distinct curves of different classes of the deep neural network."
},
{
"code": null,
"e": 6866,
"s": 6854,
"text": "Limitations"
},
{
"code": null,
"e": 7259,
"s": 6866,
"text": "There would be cases of occlusions of different types like hair, earphones, or ear is injured or covered with cloth. The chances of an individual getting authenticated would become less. As the percent of pure ear taken for feature extraction is less so the accuracy would be affected. The system aims to concern small environment rooms like security rooms, board meetings, medical labs, etc."
},
{
"code": null,
"e": 7272,
"s": 7259,
"text": "Future Scope"
},
{
"code": null,
"e": 8416,
"s": 7272,
"text": "The ear houses the smallest bones in the human body. That would be quite difficult for cybercriminals to duplicate. In addition, it can be used to measure temperature, blood flow, heart rate, and glucose levels. Ear biometric system will have diverse uses in the fields — authentication, access and attendance control, travel control, financial and other transactions requiring authorizations, remote voting, use of automated working devices, action control. e.g., nowadays airports use a combination of face & iris biometrics to authenticate a person, instead, a single ear biometric system can be used to achieve the authenticity of a person with the same accuracy. Every single feature of the body has an impact on how a person’s general personality is going to be like — face, eyes, palms & even handwriting. Personality analysis through handwriting is used to detect if the person is lying, etc. Similarly, the ear can be used for the personality analysis of a Person. Ear lobe has many features that can be used for Personality analysis — attached lobe, broad lobe, narrow ear, pointed ear, round lobe, square ear, ear sticking out, etc."
},
{
"code": null,
"e": 8424,
"s": 8416,
"text": "Summary"
},
{
"code": null,
"e": 8680,
"s": 8424,
"text": "The most significant advantage of the Ear Biometric System is to identify the person without their knowledge/awareness. This feature will change the dynamics of passive biometrics and can bring complete automatism in the biometric field. Points to focus —"
},
{
"code": null,
"e": 8783,
"s": 8680,
"text": "Large dataset (500 samples per subject) with a variety of images to train the learning model properly."
},
{
"code": null,
"e": 8839,
"s": 8783,
"text": "Preprocessing of images to reduce the computation time."
},
{
"code": null,
"e": 8897,
"s": 8839,
"text": "Good network architecture (without much loss or dropout)."
},
{
"code": null,
"e": 8971,
"s": 8897,
"text": "Run enough epochs to train the network efficiently (with GPU, suggested)."
},
{
"code": null,
"e": 9026,
"s": 8971,
"text": "Use the trained model to predict the person precisely."
},
{
"code": null,
"e": 9137,
"s": 9026,
"text": "Well, congratulations you made it to the end. Awesome. Click here to get the source code at my GitHub account."
},
{
"code": null,
"e": 9227,
"s": 9137,
"text": "Feel free to ask doubts because we are learning the same as the machines Hitesh Valecha.."
},
{
"code": null,
"e": 9240,
"s": 9227,
"text": "References —"
},
{
"code": null,
"e": 10160,
"s": 9240,
"text": "Ping Yan and Kevin W. Bowyer, Fellow, IEEE, “Biometric Recognition Using 3D Ear Shape,” IEEE Transactions on Pattern Analysis and Machine Intelligence, VOL. 29, NO. 8, AUGUST 2007John D. Bustard, Student Member, IEEE, and Mark S. Nixon, Associate Member, IEEE, “Toward Unconstrained Ear Recognition From Two-Dimensional Images,” IEEE Transactions on Systems, Man, and Cybernetics — Part A: Systems and Humans, VOL. 40, NO. 3, MAY 2010Bir Bhanu and Hui Chen, Center for Research in Intelligent Systems. Human Ear Recognition by Computer. California: University of California at Riverside [Online]. doi: 10.1007/978–1–84800–129–9.Eyad Haj Said,North Carolina Agricultural & Technical State University, Greensboro, NC, Ayman Abaza and Hany Ammar, Computer Science and Electrical Engineering Dep., West Virginia University, Morgantown, WV, “Ear Segmentation in Color Facial Images using Mathematical Morphology,” IEEE 2008."
},
{
"code": null,
"e": 10340,
"s": 10160,
"text": "Ping Yan and Kevin W. Bowyer, Fellow, IEEE, “Biometric Recognition Using 3D Ear Shape,” IEEE Transactions on Pattern Analysis and Machine Intelligence, VOL. 29, NO. 8, AUGUST 2007"
},
{
"code": null,
"e": 10596,
"s": 10340,
"text": "John D. Bustard, Student Member, IEEE, and Mark S. Nixon, Associate Member, IEEE, “Toward Unconstrained Ear Recognition From Two-Dimensional Images,” IEEE Transactions on Systems, Man, and Cybernetics — Part A: Systems and Humans, VOL. 40, NO. 3, MAY 2010"
},
{
"code": null,
"e": 10791,
"s": 10596,
"text": "Bir Bhanu and Hui Chen, Center for Research in Intelligent Systems. Human Ear Recognition by Computer. California: University of California at Riverside [Online]. doi: 10.1007/978–1–84800–129–9."
}
] |
Sort even and odd placed elements in increasing order - GeeksforGeeks
|
16 Feb, 2022
Given a list N, the task is to sort all the elements in odd and even positions in increasing order. After sorting, we need to put all the odd positioned elements together, then all the even positioned elements.
Examples:
Input : [3, 2, 7, 6, 8]
Output : 3 7 8 2 6
Explanation:
Odd position elements in sorted order are 3, 7, 8.
Even position elements in sorted order are 2, 6.
Input : 1 0 2 7 0 0
Output : 0 1 2 0 0 7
Odd {1, 2, 0}
Even {0, 7, 0}
Approach:
Initialize two lists to store the odd and even indexed digits.
Traverse through all the digits and store the odd indexed digits at odd_indexes list and the even indexed digits at even_indexes list.
Print the elements in the odd_indexes list in sorted order.
Print the elements in the even_indexes list in the sorted order.
Below is the implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; // function to print the odd and even indexed digitsvoid odd_even(int arr[], int n){ // lists to store the odd and // even positioned digits vector<int> odd_indexes; vector<int>even_indexes; // traverse through all the indexes // in the integer for (int i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.push_back(arr[i]); // else append it to the even_position list else even_indexes.push_back(arr[i]); } // print the elements in the list in sorted order sort(odd_indexes.begin(), odd_indexes.end()); sort(even_indexes.begin(), even_indexes.end()); for(int i = 0; i < odd_indexes.size();i++) cout << odd_indexes[i] << " "; for(int i = 0; i < even_indexes.size(); i++) cout << even_indexes[i] << " "; } // Driver codeint main(){ int arr[] = {3, 2, 7, 6, 8}; int n = sizeof(arr)/sizeof(arr[0]); odd_even(arr, n);} // This code is contributed by// Surendra_Gangwar
// Java implementation of the approachimport java.util.*; class GFG{ // function to print the odd and even indexed digitsstatic void odd_even(int arr[], int n){ // lists to store the odd and // even positioned digits Vector<Integer> odd_indexes = new Vector<Integer>(); Vector<Integer> even_indexes = new Vector<Integer>(); // traverse through all the indexes // in the integer for (int i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.add(arr[i]); // else append it to the even_position list else even_indexes.add(arr[i]); } // print the elements in the list in sorted order Collections.sort(odd_indexes); Collections.sort(even_indexes); for(int i = 0; i < odd_indexes.size(); i++) System.out.print(odd_indexes.get(i) + " "); for(int i = 0; i < even_indexes.size(); i++) System.out.print(even_indexes.get(i) + " "); } // Driver codepublic static void main(String[] args){ int arr[] = {3, 2, 7, 6, 8}; int n = arr.length; odd_even(arr, n);}} // This code is contributed by Rajput-Ji
# function to print the odd and even indexed digitsdef odd_even(n): # lists to store the odd and # even positioned digits odd_indexes = [] even_indexes = [] # traverse through all the indexes # in the integer for i in range(len(n)): # if the digit is in odd_index position # append it to odd_position list if i % 2 == 0: odd_indexes.append(n[i]) # else append it to the even_position list else: even_indexes.append(n[i]) # print the elements in the list in sorted order for i in sorted(odd_indexes): print(i, end =" ") for i in sorted(even_indexes): print(i, end =" ") # Driver Coden = [3, 2, 7, 6, 8]odd_even(n)
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // function to print the odd and even indexed digitsstatic void odd_even(int []arr, int n){ // lists to store the odd and // even positioned digits List<int> odd_indexes = new List<int>(); List<int> even_indexes = new List<int>(); // traverse through all the indexes // in the integer for (int i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.Add(arr[i]); // else append it to the even_position list else even_indexes.Add(arr[i]); } // print the elements in the list in sorted order odd_indexes.Sort(); even_indexes.Sort(); for(int i = 0; i < odd_indexes.Count; i++) Console.Write(odd_indexes[i] + " "); for(int i = 0; i < even_indexes.Count; i++) Console.Write(even_indexes[i] + " "); } // Driver codepublic static void Main(String[] args){ int []arr = {3, 2, 7, 6, 8}; int n = arr.Length; odd_even(arr, n);}} // This code is contributed by PrinciRaj1992
<?php// PHP implementation of above approach // function to print the odd and even// indexed digitsfunction odd_even($n){ // lists to store the odd and // even positioned digits $odd_indexes = array(); $even_indexes = array(); // traverse through all the indexes // in the integer for ($i = 0; $i < sizeof($n); $i++) { // if the digit is in odd_index position // append it to odd_position list if ($i % 2 == 0) array_push($odd_indexes, $n[$i]); // else append it to the even_position list else array_push($even_indexes, $n[$i]); } // print the elements in the list in sorted order sort($odd_indexes); for ($i = 0; $i < sizeof($odd_indexes); $i++) echo $odd_indexes[$i], " "; sort($even_indexes) ; for ($i = 0; $i < sizeof($even_indexes); $i++) echo $even_indexes[$i], " ";} // Driver Code$n = array(3, 2, 7, 6, 8);odd_even($n); // This code is contributed by Ryuga?>
<script> // Javascript implementation of above approach// function to print the odd and even indexed digitsfunction odd_even(arr, n){ // lists to store the odd and // even positioned digits var odd_indexes = []; var even_indexes = []; // traverse through all the indexes // in the integer for (var i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.push(arr[i]); // else append it to the even_position list else even_indexes.push(arr[i]); } // print the elements in the list in sorted order odd_indexes.sort(); even_indexes.sort(); for(var i = 0; i < odd_indexes.length;i++) document.write( odd_indexes[i] + " "); for(var i = 0; i < even_indexes.length; i++) document.write( even_indexes[i] + " "); } // Driver codevar arr = [3, 2, 7, 6, 8];var n = arr.length;odd_even(arr, n); </script>
3 7 8 2 6
Time Complexity : O(nlogn)
ankthon
SURENDRA_GANGWAR
VishalBachchas
Rajput-Ji
princiraj1992
sweetyty
importantly
surinderdawra388
python-list
Python Programs
Sorting
python-list
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
Python Program for QuickSort
How to inverse a matrix using NumPy
Python | Find most frequent element in a list
|
[
{
"code": null,
"e": 24557,
"s": 24529,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 24768,
"s": 24557,
"text": "Given a list N, the task is to sort all the elements in odd and even positions in increasing order. After sorting, we need to put all the odd positioned elements together, then all the even positioned elements."
},
{
"code": null,
"e": 24779,
"s": 24768,
"text": "Examples: "
},
{
"code": null,
"e": 25008,
"s": 24779,
"text": "Input : [3, 2, 7, 6, 8]\nOutput : 3 7 8 2 6\nExplanation: \nOdd position elements in sorted order are 3, 7, 8.\nEven position elements in sorted order are 2, 6.\n\nInput : 1 0 2 7 0 0\nOutput : 0 1 2 0 0 7\nOdd {1, 2, 0}\nEven {0, 7, 0} "
},
{
"code": null,
"e": 25020,
"s": 25008,
"text": "Approach: "
},
{
"code": null,
"e": 25083,
"s": 25020,
"text": "Initialize two lists to store the odd and even indexed digits."
},
{
"code": null,
"e": 25218,
"s": 25083,
"text": "Traverse through all the digits and store the odd indexed digits at odd_indexes list and the even indexed digits at even_indexes list."
},
{
"code": null,
"e": 25278,
"s": 25218,
"text": "Print the elements in the odd_indexes list in sorted order."
},
{
"code": null,
"e": 25343,
"s": 25278,
"text": "Print the elements in the even_indexes list in the sorted order."
},
{
"code": null,
"e": 25373,
"s": 25343,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 25377,
"s": 25373,
"text": "C++"
},
{
"code": null,
"e": 25382,
"s": 25377,
"text": "Java"
},
{
"code": null,
"e": 25390,
"s": 25382,
"text": "Python3"
},
{
"code": null,
"e": 25393,
"s": 25390,
"text": "C#"
},
{
"code": null,
"e": 25397,
"s": 25393,
"text": "PHP"
},
{
"code": null,
"e": 25408,
"s": 25397,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; // function to print the odd and even indexed digitsvoid odd_even(int arr[], int n){ // lists to store the odd and // even positioned digits vector<int> odd_indexes; vector<int>even_indexes; // traverse through all the indexes // in the integer for (int i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.push_back(arr[i]); // else append it to the even_position list else even_indexes.push_back(arr[i]); } // print the elements in the list in sorted order sort(odd_indexes.begin(), odd_indexes.end()); sort(even_indexes.begin(), even_indexes.end()); for(int i = 0; i < odd_indexes.size();i++) cout << odd_indexes[i] << \" \"; for(int i = 0; i < even_indexes.size(); i++) cout << even_indexes[i] << \" \"; } // Driver codeint main(){ int arr[] = {3, 2, 7, 6, 8}; int n = sizeof(arr)/sizeof(arr[0]); odd_even(arr, n);} // This code is contributed by// Surendra_Gangwar",
"e": 26581,
"s": 25408,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // function to print the odd and even indexed digitsstatic void odd_even(int arr[], int n){ // lists to store the odd and // even positioned digits Vector<Integer> odd_indexes = new Vector<Integer>(); Vector<Integer> even_indexes = new Vector<Integer>(); // traverse through all the indexes // in the integer for (int i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.add(arr[i]); // else append it to the even_position list else even_indexes.add(arr[i]); } // print the elements in the list in sorted order Collections.sort(odd_indexes); Collections.sort(even_indexes); for(int i = 0; i < odd_indexes.size(); i++) System.out.print(odd_indexes.get(i) + \" \"); for(int i = 0; i < even_indexes.size(); i++) System.out.print(even_indexes.get(i) + \" \"); } // Driver codepublic static void main(String[] args){ int arr[] = {3, 2, 7, 6, 8}; int n = arr.length; odd_even(arr, n);}} // This code is contributed by Rajput-Ji",
"e": 27800,
"s": 26581,
"text": null
},
{
"code": "# function to print the odd and even indexed digitsdef odd_even(n): # lists to store the odd and # even positioned digits odd_indexes = [] even_indexes = [] # traverse through all the indexes # in the integer for i in range(len(n)): # if the digit is in odd_index position # append it to odd_position list if i % 2 == 0: odd_indexes.append(n[i]) # else append it to the even_position list else: even_indexes.append(n[i]) # print the elements in the list in sorted order for i in sorted(odd_indexes): print(i, end =\" \") for i in sorted(even_indexes): print(i, end =\" \") # Driver Coden = [3, 2, 7, 6, 8]odd_even(n)",
"e": 28516,
"s": 27800,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // function to print the odd and even indexed digitsstatic void odd_even(int []arr, int n){ // lists to store the odd and // even positioned digits List<int> odd_indexes = new List<int>(); List<int> even_indexes = new List<int>(); // traverse through all the indexes // in the integer for (int i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.Add(arr[i]); // else append it to the even_position list else even_indexes.Add(arr[i]); } // print the elements in the list in sorted order odd_indexes.Sort(); even_indexes.Sort(); for(int i = 0; i < odd_indexes.Count; i++) Console.Write(odd_indexes[i] + \" \"); for(int i = 0; i < even_indexes.Count; i++) Console.Write(even_indexes[i] + \" \"); } // Driver codepublic static void Main(String[] args){ int []arr = {3, 2, 7, 6, 8}; int n = arr.Length; odd_even(arr, n);}} // This code is contributed by PrinciRaj1992",
"e": 29702,
"s": 28516,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // function to print the odd and even// indexed digitsfunction odd_even($n){ // lists to store the odd and // even positioned digits $odd_indexes = array(); $even_indexes = array(); // traverse through all the indexes // in the integer for ($i = 0; $i < sizeof($n); $i++) { // if the digit is in odd_index position // append it to odd_position list if ($i % 2 == 0) array_push($odd_indexes, $n[$i]); // else append it to the even_position list else array_push($even_indexes, $n[$i]); } // print the elements in the list in sorted order sort($odd_indexes); for ($i = 0; $i < sizeof($odd_indexes); $i++) echo $odd_indexes[$i], \" \"; sort($even_indexes) ; for ($i = 0; $i < sizeof($even_indexes); $i++) echo $even_indexes[$i], \" \";} // Driver Code$n = array(3, 2, 7, 6, 8);odd_even($n); // This code is contributed by Ryuga?>",
"e": 30733,
"s": 29702,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach// function to print the odd and even indexed digitsfunction odd_even(arr, n){ // lists to store the odd and // even positioned digits var odd_indexes = []; var even_indexes = []; // traverse through all the indexes // in the integer for (var i = 0; i < n;i++) { // if the digit is in odd_index position // append it to odd_position list if (i % 2 == 0) odd_indexes.push(arr[i]); // else append it to the even_position list else even_indexes.push(arr[i]); } // print the elements in the list in sorted order odd_indexes.sort(); even_indexes.sort(); for(var i = 0; i < odd_indexes.length;i++) document.write( odd_indexes[i] + \" \"); for(var i = 0; i < even_indexes.length; i++) document.write( even_indexes[i] + \" \"); } // Driver codevar arr = [3, 2, 7, 6, 8];var n = arr.length;odd_even(arr, n); </script>",
"e": 31747,
"s": 30733,
"text": null
},
{
"code": null,
"e": 31757,
"s": 31747,
"text": "3 7 8 2 6"
},
{
"code": null,
"e": 31787,
"s": 31759,
"text": "Time Complexity : O(nlogn) "
},
{
"code": null,
"e": 31795,
"s": 31787,
"text": "ankthon"
},
{
"code": null,
"e": 31812,
"s": 31795,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31827,
"s": 31812,
"text": "VishalBachchas"
},
{
"code": null,
"e": 31837,
"s": 31827,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31851,
"s": 31837,
"text": "princiraj1992"
},
{
"code": null,
"e": 31860,
"s": 31851,
"text": "sweetyty"
},
{
"code": null,
"e": 31872,
"s": 31860,
"text": "importantly"
},
{
"code": null,
"e": 31889,
"s": 31872,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31901,
"s": 31889,
"text": "python-list"
},
{
"code": null,
"e": 31917,
"s": 31901,
"text": "Python Programs"
},
{
"code": null,
"e": 31925,
"s": 31917,
"text": "Sorting"
},
{
"code": null,
"e": 31937,
"s": 31925,
"text": "python-list"
},
{
"code": null,
"e": 31945,
"s": 31937,
"text": "Sorting"
},
{
"code": null,
"e": 32043,
"s": 31945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32052,
"s": 32043,
"text": "Comments"
},
{
"code": null,
"e": 32065,
"s": 32052,
"text": "Old Comments"
},
{
"code": null,
"e": 32104,
"s": 32065,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 32168,
"s": 32104,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 32197,
"s": 32168,
"text": "Python Program for QuickSort"
},
{
"code": null,
"e": 32233,
"s": 32197,
"text": "How to inverse a matrix using NumPy"
}
] |
Gamma Distribution — Intuition, Derivation, and Examples | by Aerin Kim | Towards Data Science
|
Before setting Gamma’s two parameters α, β and plugging them into the formula, let’s pause for a moment and ask a few questions...
Why did we have to invent the Gamma distribution? (i.e., why does this distribution exist?)
When should Gamma distribution be used for modeling?
Answer: To predict the wait time until future events.
Hmmm ok, but I thought that’s what the exponential distribution is for. Then, what’s the difference between exponential distribution and gamma distribution?
The exponential distribution predicts the wait time until the *very first* event. The gamma distribution, on the other hand, predicts the wait time until the *k-th* event occurs.
In our previous post, we derived the PDF of exponential distribution from the Poisson process. I highly recommend learning Poisson & Exponential distribution if you haven’t already done so. Understanding them well is absolutely required for understanding the Gamma well. The order of your reading should be 1. Poisson, 2. Exponential, 3. Gamma.
The derivation of the PDF of Gamma distribution is very similar to that of the exponential distribution PDF, except for one thing — it’s the wait time until the k-th event, instead of the first event.
< Notation! >* T : the random variable for wait time until the k-th event (This is the random variable of interest!)* Event arrivals are modeled by a Poisson process with rate λ.* k : the 1st parameter of Gamma. The # of events for which you are waiting.* λ : the 2nd parameter of Gamma. The rate of events happening which follows the Poisson process.* P(T > t) : The probability that the waiting time until the k-th event is greater than t time units* P(X = k in t time units) : The Poisson probability of k events occuring during t time units
As usual, in order to get the PDF, we will first find the CDF and then differentiate it.
Now, let’s differentiate it.
For easier differentiation, we take out the term (e^(-λt)) when x = 0 from the summation.
We got the PDF of gamma distribution!
The derivation looks complicated but we are merely rearranging the variables, applying the product rule of differentiation, expanding the summation, and crossing some out.
If you look at the final output of the derivation, you will notice that it is the same as the PDF of Exponential distribution, when k=1.
Since k is a positive integer (number of k events), Γ(k) = (k−1)! where Γ denotes the gamma function. The final product can be rewritten as:
If arrivals of events follow a Poisson process with a rate λ, the wait time until k arrivals follows Γ(k, λ).
There are two aspects of Gamma’s parameterization that confuse us!
One is that it has two different parameterization sets — (k, θ) &(α, β) — and different forms of PDF. The other is that there is no universal consensus of what the “scale” parameter should be.
Let’s clarify this.
The first issue is pretty straightforward to clear up.
For (α, β) parameterization: Using our notation k (the # of events) & λ (the rate of events), simply substitute α with k, β with λ. The PDF stays the same format as what we’ve derived.For (k, θ) parameterization: θ is a reciprocal of the event rate λ, which is the mean wait time (the average time between event arrivals).
Even though the PDFs have different formats, both parametrizations generate the same model. Just like in order to define a straight line, some use a slope and a y-intercept, while others use an x-intercept and a y-intercept, choosing one parameterization over another is a matter of taste. In my opinion, using λ as a rate parameter makes more sense, given how we derive both exponential and gamma using the Poisson rate λ. I also found (α, β) parameterization is easier to integrate.
Second, some authors call λ a scale parameter while others call θ=1/λ the scale parameter instead. IMHO, a “shape” or a “scale” parameter is really more of a misnomer. I plotted multiple Gamma PDFs with different k & λ sets (there are infinite parameter choices of k and λ, thus, there is an infinite number of possible Gamma distributions) and realized both k (and λ) change both “shape” AND “scale”. Whoever named them seriously could have given more intuitive names such as — the number of events and the Poisson rate!
Seeing is believing! Let’s visualize 🌈
Recap:k : The number of events for which you are waiting to occur.λ : The rate of events happening which follows the Poisson process.
For a fixed rate λ, if we wait for more events (k) to happen, the wait time (T) will be longer.
For a fixed number of events k, when the event rate λ is higher, we wait for a shorter amount of time T.
Here is Python code to generate the beautiful plots above. (Plot them yourself and see how the two parameters change the “scale” and “shape”!)
import numpy as npfrom scipy.stats import gammaimport matplotlib.pyplot as pltdef plot_gamma_k(): """ k : the number of events for which you are waiting to occur. λ : the rate of events happening following Poisson dist. """ x = np.linspace(0, 50, 1000) a = 1 # k = 1 mean, var, skew, kurt = gamma.stats(a, moments='mvsk') y1 = gamma.pdf(x, a) a = 5 # k = 5 mean, var, skew, kurt = gamma.stats(a, moments='mvsk') y2 = gamma.pdf(x, a) a = 10 # k = 15 mean, var, skew, kurt = gamma.stats(a, moments='mvsk') y3 = gamma.pdf(x, a)plt.title("PDF of Gamma Distribution") plt.xlabel("T") plt.ylabel("Probability Density") plt.plot(x, y1, label="k = 1", color='palegreen') plt.plot(x, y2, label="k = 5", color='yellowgreen') plt.plot(x, y3, label="k = 10", color='olivedrab') plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=1, fontsize=12) plt.ylim([0, 0.40]) plt.xlim([0, 20]) plt.savefig('gamma_k.png') plt.clf()def plot_gamma_lambda(): """ k : the number of events for which you are waiting to occur. λ : the rate of events happening following Poisson dist. """ a = 10 # k = 10 x = np.linspace(0, 50, 1000) lambda_ = 1 mean, var, skew, kurt = gamma.stats(a, scale=1/lambda_, moments='mvsk') y1 = gamma.pdf(x, a, scale=1/lambda_) lambda_ = 2 mean, var, skew, kurt = gamma.stats(a, scale=1/lambda_, moments='mvsk') y2 = gamma.pdf(x, a, scale=1/lambda_) lambda_ = 3 mean, var, skew, kurt = gamma.stats(a, scale=1/lambda_, moments='mvsk') y3 = gamma.pdf(x, a, scale=1/lambda_)plt.title("PDF of Gamma Distribution (k = 10)") plt.xlabel("T") plt.ylabel("Probability Density") plt.plot(x, y1, label="λ = 1", color='gold') plt.plot(x, y2, label="λ = 2", color='burlywood') plt.plot(x, y3, label="λ = 3", color='darkorange') plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=1, fontsize=12) plt.ylim([0, 0.40]) plt.xlim([0, 20]) plt.savefig('gamma_lambda.png') plt.clf()
Code in ipynb: https://github.com/aerinkim/TowardsDataScience/blob/master/Gamma%20Distribution.ipynb
We can use the Gamma distribution for every application where the exponential distribution is used — Wait time modeling, Reliability (failure) modeling, Service time modeling (Queuing Theory), etc. — because exponential distribution is a special case of Gamma distribution (just plug 1 into k).
[Queuing Theory Example] You went to Chipotle and joined a line with two people ahead of you. One is being served and the other is waiting. Their service times S1 and S2 are independent, exponential random variables with a mean of 2 minutes. (Thus the mean service rate is .5/minute. If this “rate vs. time” concept confuses you, read this to clarify.)
What is the probability that you wait more than 5 minutes in the queue?
All we did was to plug t = 5 and λ = 0.5 into the CDF of the Gamma distribution that we have already derived. This is the same example that we covered in The Sum of Exponential Random Variables. As you see, we can solve this using Gamma’s CDF as well.
A less-than-30% chance that I’ll wait for more than 5 minutes at Chipotle? I’ll take that!
A few things to note:
Poisson, Exponential, and Gamma distribution model different aspects of the same process — the Poisson process. Poisson distribution is used to model the # of events in the future, Exponential distribution is used to predict the wait time until the very first event, and Gamma distribution is used to predict the wait time until the k-th event.Gamma’s two parameters are both strictly positive, because one is the number of events and the other is the rate of events. They can’t be negative.Special cases of a Gamma distribution
Poisson, Exponential, and Gamma distribution model different aspects of the same process — the Poisson process. Poisson distribution is used to model the # of events in the future, Exponential distribution is used to predict the wait time until the very first event, and Gamma distribution is used to predict the wait time until the k-th event.
Gamma’s two parameters are both strictly positive, because one is the number of events and the other is the rate of events. They can’t be negative.
Special cases of a Gamma distribution
╔═════════════╦══════════════════════╦══════════════════════╗║ Dist. ║ k ║ λ ║╠═════════════╬══════════════════════╬══════════════════════╣║ Gamma ║ positive real number ║ positive real number ║║ Exponential ║ 1 ║ " ║║ Erlang ║ positive integer ║ " ║╚═════════════╩══════════════════════╩══════════════════════╝
The difference between Erlang and Gamma is that in a Gamma distribution, k can be a non-integer (positive real number) and in Erlang, k is positive integer only.
... The difference between the Binomial and the Beta is the former models the number of successes, while the latter models the probability of success ...
|
[
{
"code": null,
"e": 303,
"s": 172,
"text": "Before setting Gamma’s two parameters α, β and plugging them into the formula, let’s pause for a moment and ask a few questions..."
},
{
"code": null,
"e": 395,
"s": 303,
"text": "Why did we have to invent the Gamma distribution? (i.e., why does this distribution exist?)"
},
{
"code": null,
"e": 448,
"s": 395,
"text": "When should Gamma distribution be used for modeling?"
},
{
"code": null,
"e": 502,
"s": 448,
"text": "Answer: To predict the wait time until future events."
},
{
"code": null,
"e": 659,
"s": 502,
"text": "Hmmm ok, but I thought that’s what the exponential distribution is for. Then, what’s the difference between exponential distribution and gamma distribution?"
},
{
"code": null,
"e": 838,
"s": 659,
"text": "The exponential distribution predicts the wait time until the *very first* event. The gamma distribution, on the other hand, predicts the wait time until the *k-th* event occurs."
},
{
"code": null,
"e": 1183,
"s": 838,
"text": "In our previous post, we derived the PDF of exponential distribution from the Poisson process. I highly recommend learning Poisson & Exponential distribution if you haven’t already done so. Understanding them well is absolutely required for understanding the Gamma well. The order of your reading should be 1. Poisson, 2. Exponential, 3. Gamma."
},
{
"code": null,
"e": 1384,
"s": 1183,
"text": "The derivation of the PDF of Gamma distribution is very similar to that of the exponential distribution PDF, except for one thing — it’s the wait time until the k-th event, instead of the first event."
},
{
"code": null,
"e": 1933,
"s": 1384,
"text": "< Notation! >* T : the random variable for wait time until the k-th event (This is the random variable of interest!)* Event arrivals are modeled by a Poisson process with rate λ.* k : the 1st parameter of Gamma. The # of events for which you are waiting.* λ : the 2nd parameter of Gamma. The rate of events happening which follows the Poisson process.* P(T > t) : The probability that the waiting time until the k-th event is greater than t time units* P(X = k in t time units) : The Poisson probability of k events occuring during t time units"
},
{
"code": null,
"e": 2022,
"s": 1933,
"text": "As usual, in order to get the PDF, we will first find the CDF and then differentiate it."
},
{
"code": null,
"e": 2051,
"s": 2022,
"text": "Now, let’s differentiate it."
},
{
"code": null,
"e": 2141,
"s": 2051,
"text": "For easier differentiation, we take out the term (e^(-λt)) when x = 0 from the summation."
},
{
"code": null,
"e": 2179,
"s": 2141,
"text": "We got the PDF of gamma distribution!"
},
{
"code": null,
"e": 2351,
"s": 2179,
"text": "The derivation looks complicated but we are merely rearranging the variables, applying the product rule of differentiation, expanding the summation, and crossing some out."
},
{
"code": null,
"e": 2488,
"s": 2351,
"text": "If you look at the final output of the derivation, you will notice that it is the same as the PDF of Exponential distribution, when k=1."
},
{
"code": null,
"e": 2629,
"s": 2488,
"text": "Since k is a positive integer (number of k events), Γ(k) = (k−1)! where Γ denotes the gamma function. The final product can be rewritten as:"
},
{
"code": null,
"e": 2739,
"s": 2629,
"text": "If arrivals of events follow a Poisson process with a rate λ, the wait time until k arrivals follows Γ(k, λ)."
},
{
"code": null,
"e": 2806,
"s": 2739,
"text": "There are two aspects of Gamma’s parameterization that confuse us!"
},
{
"code": null,
"e": 2999,
"s": 2806,
"text": "One is that it has two different parameterization sets — (k, θ) &(α, β) — and different forms of PDF. The other is that there is no universal consensus of what the “scale” parameter should be."
},
{
"code": null,
"e": 3019,
"s": 2999,
"text": "Let’s clarify this."
},
{
"code": null,
"e": 3074,
"s": 3019,
"text": "The first issue is pretty straightforward to clear up."
},
{
"code": null,
"e": 3397,
"s": 3074,
"text": "For (α, β) parameterization: Using our notation k (the # of events) & λ (the rate of events), simply substitute α with k, β with λ. The PDF stays the same format as what we’ve derived.For (k, θ) parameterization: θ is a reciprocal of the event rate λ, which is the mean wait time (the average time between event arrivals)."
},
{
"code": null,
"e": 3882,
"s": 3397,
"text": "Even though the PDFs have different formats, both parametrizations generate the same model. Just like in order to define a straight line, some use a slope and a y-intercept, while others use an x-intercept and a y-intercept, choosing one parameterization over another is a matter of taste. In my opinion, using λ as a rate parameter makes more sense, given how we derive both exponential and gamma using the Poisson rate λ. I also found (α, β) parameterization is easier to integrate."
},
{
"code": null,
"e": 4404,
"s": 3882,
"text": "Second, some authors call λ a scale parameter while others call θ=1/λ the scale parameter instead. IMHO, a “shape” or a “scale” parameter is really more of a misnomer. I plotted multiple Gamma PDFs with different k & λ sets (there are infinite parameter choices of k and λ, thus, there is an infinite number of possible Gamma distributions) and realized both k (and λ) change both “shape” AND “scale”. Whoever named them seriously could have given more intuitive names such as — the number of events and the Poisson rate!"
},
{
"code": null,
"e": 4443,
"s": 4404,
"text": "Seeing is believing! Let’s visualize 🌈"
},
{
"code": null,
"e": 4577,
"s": 4443,
"text": "Recap:k : The number of events for which you are waiting to occur.λ : The rate of events happening which follows the Poisson process."
},
{
"code": null,
"e": 4673,
"s": 4577,
"text": "For a fixed rate λ, if we wait for more events (k) to happen, the wait time (T) will be longer."
},
{
"code": null,
"e": 4778,
"s": 4673,
"text": "For a fixed number of events k, when the event rate λ is higher, we wait for a shorter amount of time T."
},
{
"code": null,
"e": 4921,
"s": 4778,
"text": "Here is Python code to generate the beautiful plots above. (Plot them yourself and see how the two parameters change the “scale” and “shape”!)"
},
{
"code": null,
"e": 6991,
"s": 4921,
"text": "import numpy as npfrom scipy.stats import gammaimport matplotlib.pyplot as pltdef plot_gamma_k(): \"\"\" k : the number of events for which you are waiting to occur. λ : the rate of events happening following Poisson dist. \"\"\" x = np.linspace(0, 50, 1000) a = 1 # k = 1 mean, var, skew, kurt = gamma.stats(a, moments='mvsk') y1 = gamma.pdf(x, a) a = 5 # k = 5 mean, var, skew, kurt = gamma.stats(a, moments='mvsk') y2 = gamma.pdf(x, a) a = 10 # k = 15 mean, var, skew, kurt = gamma.stats(a, moments='mvsk') y3 = gamma.pdf(x, a)plt.title(\"PDF of Gamma Distribution\") plt.xlabel(\"T\") plt.ylabel(\"Probability Density\") plt.plot(x, y1, label=\"k = 1\", color='palegreen') plt.plot(x, y2, label=\"k = 5\", color='yellowgreen') plt.plot(x, y3, label=\"k = 10\", color='olivedrab') plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=1, fontsize=12) plt.ylim([0, 0.40]) plt.xlim([0, 20]) plt.savefig('gamma_k.png') plt.clf()def plot_gamma_lambda(): \"\"\" k : the number of events for which you are waiting to occur. λ : the rate of events happening following Poisson dist. \"\"\" a = 10 # k = 10 x = np.linspace(0, 50, 1000) lambda_ = 1 mean, var, skew, kurt = gamma.stats(a, scale=1/lambda_, moments='mvsk') y1 = gamma.pdf(x, a, scale=1/lambda_) lambda_ = 2 mean, var, skew, kurt = gamma.stats(a, scale=1/lambda_, moments='mvsk') y2 = gamma.pdf(x, a, scale=1/lambda_) lambda_ = 3 mean, var, skew, kurt = gamma.stats(a, scale=1/lambda_, moments='mvsk') y3 = gamma.pdf(x, a, scale=1/lambda_)plt.title(\"PDF of Gamma Distribution (k = 10)\") plt.xlabel(\"T\") plt.ylabel(\"Probability Density\") plt.plot(x, y1, label=\"λ = 1\", color='gold') plt.plot(x, y2, label=\"λ = 2\", color='burlywood') plt.plot(x, y3, label=\"λ = 3\", color='darkorange') plt.legend(bbox_to_anchor=(1, 1), loc='upper right', borderaxespad=1, fontsize=12) plt.ylim([0, 0.40]) plt.xlim([0, 20]) plt.savefig('gamma_lambda.png') plt.clf()"
},
{
"code": null,
"e": 7092,
"s": 6991,
"text": "Code in ipynb: https://github.com/aerinkim/TowardsDataScience/blob/master/Gamma%20Distribution.ipynb"
},
{
"code": null,
"e": 7387,
"s": 7092,
"text": "We can use the Gamma distribution for every application where the exponential distribution is used — Wait time modeling, Reliability (failure) modeling, Service time modeling (Queuing Theory), etc. — because exponential distribution is a special case of Gamma distribution (just plug 1 into k)."
},
{
"code": null,
"e": 7740,
"s": 7387,
"text": "[Queuing Theory Example] You went to Chipotle and joined a line with two people ahead of you. One is being served and the other is waiting. Their service times S1 and S2 are independent, exponential random variables with a mean of 2 minutes. (Thus the mean service rate is .5/minute. If this “rate vs. time” concept confuses you, read this to clarify.)"
},
{
"code": null,
"e": 7812,
"s": 7740,
"text": "What is the probability that you wait more than 5 minutes in the queue?"
},
{
"code": null,
"e": 8064,
"s": 7812,
"text": "All we did was to plug t = 5 and λ = 0.5 into the CDF of the Gamma distribution that we have already derived. This is the same example that we covered in The Sum of Exponential Random Variables. As you see, we can solve this using Gamma’s CDF as well."
},
{
"code": null,
"e": 8155,
"s": 8064,
"text": "A less-than-30% chance that I’ll wait for more than 5 minutes at Chipotle? I’ll take that!"
},
{
"code": null,
"e": 8177,
"s": 8155,
"text": "A few things to note:"
},
{
"code": null,
"e": 8706,
"s": 8177,
"text": "Poisson, Exponential, and Gamma distribution model different aspects of the same process — the Poisson process. Poisson distribution is used to model the # of events in the future, Exponential distribution is used to predict the wait time until the very first event, and Gamma distribution is used to predict the wait time until the k-th event.Gamma’s two parameters are both strictly positive, because one is the number of events and the other is the rate of events. They can’t be negative.Special cases of a Gamma distribution"
},
{
"code": null,
"e": 9051,
"s": 8706,
"text": "Poisson, Exponential, and Gamma distribution model different aspects of the same process — the Poisson process. Poisson distribution is used to model the # of events in the future, Exponential distribution is used to predict the wait time until the very first event, and Gamma distribution is used to predict the wait time until the k-th event."
},
{
"code": null,
"e": 9199,
"s": 9051,
"text": "Gamma’s two parameters are both strictly positive, because one is the number of events and the other is the rate of events. They can’t be negative."
},
{
"code": null,
"e": 9237,
"s": 9199,
"text": "Special cases of a Gamma distribution"
},
{
"code": null,
"e": 9665,
"s": 9237,
"text": "╔═════════════╦══════════════════════╦══════════════════════╗║ Dist. ║ k ║ λ ║╠═════════════╬══════════════════════╬══════════════════════╣║ Gamma ║ positive real number ║ positive real number ║║ Exponential ║ 1 ║ \" ║║ Erlang ║ positive integer ║ \" ║╚═════════════╩══════════════════════╩══════════════════════╝"
},
{
"code": null,
"e": 9827,
"s": 9665,
"text": "The difference between Erlang and Gamma is that in a Gamma distribution, k can be a non-integer (positive real number) and in Erlang, k is positive integer only."
}
] |
Add arrow in tooltip with CSS
|
With CSS, you can add a small arrow to the tooltip, using :after. With that, use the content property as well.
You can try to run the following code to add an arrow in the tooltip:
Live Demo
<!DOCTYPE html>
<html>
<style>
.mytooltip .mytext {
visibility: hidden;
width: 140px;
background-color: blue;
color: #fff;
z-index: 1;
bottom: 100%;
left: 60%;
margin-left: -90px;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
}
.mytooltip {
position: relative;
display: inline-block;
margin-top: 50px;
}
.mytooltip .mytext:after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 7px;
border-style: solid;
border-color: blue transparent transparent transparent;
}
.mytooltip:hover .mytext {
visibility: visible;
}
</style>
<body>
<div class = "mytooltip">Keep mouse cursor over me
<span class = "mytext"> My Tooltip text</span>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "With CSS, you can add a small arrow to the tooltip, using :after. With that, use the content property as well."
},
{
"code": null,
"e": 1243,
"s": 1173,
"text": "You can try to run the following code to add an arrow in the tooltip:"
},
{
"code": null,
"e": 1253,
"s": 1243,
"text": "Live Demo"
},
{
"code": null,
"e": 2272,
"s": 1253,
"text": "<!DOCTYPE html>\n<html>\n <style>\n .mytooltip .mytext {\n visibility: hidden;\n width: 140px;\n background-color: blue;\n color: #fff;\n z-index: 1;\n bottom: 100%;\n left: 60%;\n margin-left: -90px;\n text-align: center;\n border-radius: 6px;\n padding: 5px 0;\n position: absolute;\n }\n .mytooltip {\n position: relative;\n display: inline-block;\n margin-top: 50px;\n }\n .mytooltip .mytext:after {\n content: \"\";\n position: absolute;\n top: 100%;\n left: 50%;\n margin-left: -10px;\n border-width: 7px;\n border-style: solid;\n border-color: blue transparent transparent transparent;\n }\n .mytooltip:hover .mytext {\n visibility: visible;\n }\n </style>\n\n <body>\n <div class = \"mytooltip\">Keep mouse cursor over me\n <span class = \"mytext\"> My Tooltip text</span>\n </div>\n </body>\n</html>"
}
] |
Python Lambda Function. In this article, you will learn more... | by Tanu N Prabhu | Towards Data Science
|
In this article, you will learn more about lambda functions in python. How can we use lambda functions, what is the syntax of lambda functions and why do we need them?
Lambda functions are also called anonymous functions. An anonymous function is a function defined without a name. As you know to define a normal function in python, you need to use the def keyword. But in this case of anonymous functions, we use thelambda keyword to define the functions. Alonzo Church in the 1930s to the field of mathematics introduced the lambda functions.
Also, the whole code for this tutorial can be found on my GitHub Repository below:
github.com
The lambda function can take many arguments but can return only one expression. Here the expression is nothing but the result returned by the lambda function.Lambda functions are syntactically restricted to return a single expression.You can use them as an anonymous function inside other functions.The lambda functions do not need a return statement, they always return a single expression.
The lambda function can take many arguments but can return only one expression. Here the expression is nothing but the result returned by the lambda function.
Lambda functions are syntactically restricted to return a single expression.
You can use them as an anonymous function inside other functions.
The lambda functions do not need a return statement, they always return a single expression.
Use lambda functions when an anonymous function is required for a short period of time. — I don’t why they say this, if you know, please let me know, I’m curious.
The syntax of lambda functions is shown below:
lambda arguments: expression
The expression is always executed and returned.
Lets us understand the working of lambda functions, we will just use simple logic to understand the working of lambda functions by adding two numbers. Firstly, I will write the program and then explain to you what it does?
add = lambda a: a + aprint(add(20))40
Ok firstly did you understand anything from the program, don’t worry I will explain it to you step by step.
First, define the anonymous/ lambda function by using lambda keyword.Just remember the syntax of lambda functions which is as shown below: lambda arguments: expression, then just use the variable “a” as an argument and “a + a” as the expression, remember we are adding two numbers (a + a).Then to store the final added result let us use a variable “add”.And then just as calling a normal function, we shall call the lambda function with the name of its variable “add” by sending a parameter “20” to perform the addition and then print it “print(add(20))”.This is the final step, here when we print the result we then get 40 because of “20+20” since we are adding “a+a”. Look here I’m not using the return statement.
First, define the anonymous/ lambda function by using lambda keyword.
Just remember the syntax of lambda functions which is as shown below: lambda arguments: expression, then just use the variable “a” as an argument and “a + a” as the expression, remember we are adding two numbers (a + a).
Then to store the final added result let us use a variable “add”.
And then just as calling a normal function, we shall call the lambda function with the name of its variable “add” by sending a parameter “20” to perform the addition and then print it “print(add(20))”.
This is the final step, here when we print the result we then get 40 because of “20+20” since we are adding “a+a”. Look here I’m not using the return statement.
Now that we know how lambda function works its time to play with it. Lambda function takes multiple arguments, let us see if this statement is true or not.
add = lambda a, b, c: a + b + cprint(add(10, 10, 10))30
Wow, the above statement is actually true, because I passed more than one argument to the lambda function and then it worked.
This is one of the hardest questions to answer, after doing some research I nearly came to answer the above question. I don't want to make general assumptions rather I would like to answer this question with the help of an example:
def add(a,b,c): return a+b+cresult = add(10, 10, 10)print(result)30print(type(result))int
add = lambda a, b, c: a + b + cprint(add(10, 10, 10))30print(type(add))function
Based on the above two examples I have made a few differences between the normal function and the lambda function. I hope it is helpful.
You are wondering how did I calculate the execution time of the program. Its simple I just used the time library. Alright, I will provide you the code below.
import timestart_time = time.time()add = lambda a, b, c: a + b + cprint(add(10, 10, 10))print("--- %s seconds ---" % (time.time() - start_time))30 --- 0.0005075931549072266 seconds ---
We can use lambda functions as anonymous functions inside any normal functions of python. This is the actual superpower of lambda functions. Because of its simplicity, you can write a lambda function with no hassle. Now just think you need to write a normal function of adding every number and the current given number you have given.
Confused, OK imagine now you have the number 100 as constant and every time you need to add another number such as 200, 300, 400,.... to the existing number. Here, rather than defining another function inside the same function, you use the lambda function as shown below.
def add(n): return lambda a : a + nresult = add(100)print(result(200))300
You can get the job done in just one step of using a lambda function. Like I said the simplicity and the usability inside another function are the prime features of a lambda function compared to the normal functions.
I guess the answer is yes because in the below example I can reuse the same lambda function to add the number to the existing numbers.
def add(n): return lambda a : a + nresult = add(100)print(result(200))print("-------------------")print(result(300))print("-------------------")print(result(400))print("-------------------")print(result(500))300 ------------------- 400 ------------------- 500 ------------------- 600
Well, there you go you would have now got a better understanding of lambda functions. This is the end of the tutorial of “Python Lambda Functions”, there are more important concepts such as maps, filters and many more. These are altogether different concepts, I shall write them as separate tutorials shortly. Stay tuned!!. Until then see you, have a nice day.
|
[
{
"code": null,
"e": 340,
"s": 172,
"text": "In this article, you will learn more about lambda functions in python. How can we use lambda functions, what is the syntax of lambda functions and why do we need them?"
},
{
"code": null,
"e": 717,
"s": 340,
"text": "Lambda functions are also called anonymous functions. An anonymous function is a function defined without a name. As you know to define a normal function in python, you need to use the def keyword. But in this case of anonymous functions, we use thelambda keyword to define the functions. Alonzo Church in the 1930s to the field of mathematics introduced the lambda functions."
},
{
"code": null,
"e": 800,
"s": 717,
"text": "Also, the whole code for this tutorial can be found on my GitHub Repository below:"
},
{
"code": null,
"e": 811,
"s": 800,
"text": "github.com"
},
{
"code": null,
"e": 1203,
"s": 811,
"text": "The lambda function can take many arguments but can return only one expression. Here the expression is nothing but the result returned by the lambda function.Lambda functions are syntactically restricted to return a single expression.You can use them as an anonymous function inside other functions.The lambda functions do not need a return statement, they always return a single expression."
},
{
"code": null,
"e": 1362,
"s": 1203,
"text": "The lambda function can take many arguments but can return only one expression. Here the expression is nothing but the result returned by the lambda function."
},
{
"code": null,
"e": 1439,
"s": 1362,
"text": "Lambda functions are syntactically restricted to return a single expression."
},
{
"code": null,
"e": 1505,
"s": 1439,
"text": "You can use them as an anonymous function inside other functions."
},
{
"code": null,
"e": 1598,
"s": 1505,
"text": "The lambda functions do not need a return statement, they always return a single expression."
},
{
"code": null,
"e": 1761,
"s": 1598,
"text": "Use lambda functions when an anonymous function is required for a short period of time. — I don’t why they say this, if you know, please let me know, I’m curious."
},
{
"code": null,
"e": 1808,
"s": 1761,
"text": "The syntax of lambda functions is shown below:"
},
{
"code": null,
"e": 1837,
"s": 1808,
"text": "lambda arguments: expression"
},
{
"code": null,
"e": 1885,
"s": 1837,
"text": "The expression is always executed and returned."
},
{
"code": null,
"e": 2108,
"s": 1885,
"text": "Lets us understand the working of lambda functions, we will just use simple logic to understand the working of lambda functions by adding two numbers. Firstly, I will write the program and then explain to you what it does?"
},
{
"code": null,
"e": 2146,
"s": 2108,
"text": "add = lambda a: a + aprint(add(20))40"
},
{
"code": null,
"e": 2254,
"s": 2146,
"text": "Ok firstly did you understand anything from the program, don’t worry I will explain it to you step by step."
},
{
"code": null,
"e": 2970,
"s": 2254,
"text": "First, define the anonymous/ lambda function by using lambda keyword.Just remember the syntax of lambda functions which is as shown below: lambda arguments: expression, then just use the variable “a” as an argument and “a + a” as the expression, remember we are adding two numbers (a + a).Then to store the final added result let us use a variable “add”.And then just as calling a normal function, we shall call the lambda function with the name of its variable “add” by sending a parameter “20” to perform the addition and then print it “print(add(20))”.This is the final step, here when we print the result we then get 40 because of “20+20” since we are adding “a+a”. Look here I’m not using the return statement."
},
{
"code": null,
"e": 3040,
"s": 2970,
"text": "First, define the anonymous/ lambda function by using lambda keyword."
},
{
"code": null,
"e": 3261,
"s": 3040,
"text": "Just remember the syntax of lambda functions which is as shown below: lambda arguments: expression, then just use the variable “a” as an argument and “a + a” as the expression, remember we are adding two numbers (a + a)."
},
{
"code": null,
"e": 3327,
"s": 3261,
"text": "Then to store the final added result let us use a variable “add”."
},
{
"code": null,
"e": 3529,
"s": 3327,
"text": "And then just as calling a normal function, we shall call the lambda function with the name of its variable “add” by sending a parameter “20” to perform the addition and then print it “print(add(20))”."
},
{
"code": null,
"e": 3690,
"s": 3529,
"text": "This is the final step, here when we print the result we then get 40 because of “20+20” since we are adding “a+a”. Look here I’m not using the return statement."
},
{
"code": null,
"e": 3846,
"s": 3690,
"text": "Now that we know how lambda function works its time to play with it. Lambda function takes multiple arguments, let us see if this statement is true or not."
},
{
"code": null,
"e": 3902,
"s": 3846,
"text": "add = lambda a, b, c: a + b + cprint(add(10, 10, 10))30"
},
{
"code": null,
"e": 4028,
"s": 3902,
"text": "Wow, the above statement is actually true, because I passed more than one argument to the lambda function and then it worked."
},
{
"code": null,
"e": 4260,
"s": 4028,
"text": "This is one of the hardest questions to answer, after doing some research I nearly came to answer the above question. I don't want to make general assumptions rather I would like to answer this question with the help of an example:"
},
{
"code": null,
"e": 4353,
"s": 4260,
"text": "def add(a,b,c): return a+b+cresult = add(10, 10, 10)print(result)30print(type(result))int"
},
{
"code": null,
"e": 4433,
"s": 4353,
"text": "add = lambda a, b, c: a + b + cprint(add(10, 10, 10))30print(type(add))function"
},
{
"code": null,
"e": 4570,
"s": 4433,
"text": "Based on the above two examples I have made a few differences between the normal function and the lambda function. I hope it is helpful."
},
{
"code": null,
"e": 4728,
"s": 4570,
"text": "You are wondering how did I calculate the execution time of the program. Its simple I just used the time library. Alright, I will provide you the code below."
},
{
"code": null,
"e": 4913,
"s": 4728,
"text": "import timestart_time = time.time()add = lambda a, b, c: a + b + cprint(add(10, 10, 10))print(\"--- %s seconds ---\" % (time.time() - start_time))30 --- 0.0005075931549072266 seconds ---"
},
{
"code": null,
"e": 5248,
"s": 4913,
"text": "We can use lambda functions as anonymous functions inside any normal functions of python. This is the actual superpower of lambda functions. Because of its simplicity, you can write a lambda function with no hassle. Now just think you need to write a normal function of adding every number and the current given number you have given."
},
{
"code": null,
"e": 5520,
"s": 5248,
"text": "Confused, OK imagine now you have the number 100 as constant and every time you need to add another number such as 200, 300, 400,.... to the existing number. Here, rather than defining another function inside the same function, you use the lambda function as shown below."
},
{
"code": null,
"e": 5597,
"s": 5520,
"text": "def add(n): return lambda a : a + nresult = add(100)print(result(200))300"
},
{
"code": null,
"e": 5814,
"s": 5597,
"text": "You can get the job done in just one step of using a lambda function. Like I said the simplicity and the usability inside another function are the prime features of a lambda function compared to the normal functions."
},
{
"code": null,
"e": 5949,
"s": 5814,
"text": "I guess the answer is yes because in the below example I can reuse the same lambda function to add the number to the existing numbers."
},
{
"code": null,
"e": 6236,
"s": 5949,
"text": "def add(n): return lambda a : a + nresult = add(100)print(result(200))print(\"-------------------\")print(result(300))print(\"-------------------\")print(result(400))print(\"-------------------\")print(result(500))300 ------------------- 400 ------------------- 500 ------------------- 600"
}
] |
Nested functions in C
|
In some applications, we have seen that some functions are declared inside another function. This is sometimes known as nested function, but actually this is not the nested function. This is called the lexical scoping. Lexical scoping is not valid in C because the compiler is unable to reach correct memory location of inner function.
Nested function definitions cannot access local variables of surrounding blocks. They can access only global variables. In C there are two nested scopes the local and the global. So nested function has some limited use. If we want to create nested function like below, it will generate error.
#include <stdio.h>
main(void) {
printf("Main Function");
int my_fun() {
printf("my_fun function");
// defining another function inside the first function.
int my_fun2() {
printf("my_fun2 is inner function");
}
}
my_fun2();
}
text.c:(.text+0x1a): undefined reference to `my_fun2'
But an extension of GNU C compiler allows declaration of the nested function. For this we have to add auto keyword before the declaration of nested function.
#include <stdio.h>
main(void) {
auto int my_fun();
my_fun();
printf("Main Function\n");
int my_fun() {
printf("my_fun function\n");
}
printf("Done");
}
my_fun function
Main Function
Done
|
[
{
"code": null,
"e": 1398,
"s": 1062,
"text": "In some applications, we have seen that some functions are declared inside another function. This is sometimes known as nested function, but actually this is not the nested function. This is called the lexical scoping. Lexical scoping is not valid in C because the compiler is unable to reach correct memory location of inner function."
},
{
"code": null,
"e": 1691,
"s": 1398,
"text": "Nested function definitions cannot access local variables of surrounding blocks. They can access only global variables. In C there are two nested scopes the local and the global. So nested function has some limited use. If we want to create nested function like below, it will generate error."
},
{
"code": null,
"e": 1961,
"s": 1691,
"text": "#include <stdio.h>\nmain(void) {\n printf(\"Main Function\");\n int my_fun() {\n printf(\"my_fun function\");\n // defining another function inside the first function.\n int my_fun2() {\n printf(\"my_fun2 is inner function\");\n }\n }\n my_fun2();\n}"
},
{
"code": null,
"e": 2015,
"s": 1961,
"text": "text.c:(.text+0x1a): undefined reference to `my_fun2'"
},
{
"code": null,
"e": 2173,
"s": 2015,
"text": "But an extension of GNU C compiler allows declaration of the nested function. For this we have to add auto keyword before the declaration of nested function."
},
{
"code": null,
"e": 2349,
"s": 2173,
"text": "#include <stdio.h>\nmain(void) {\n auto int my_fun();\n my_fun();\n printf(\"Main Function\\n\");\n int my_fun() {\n printf(\"my_fun function\\n\");\n }\n printf(\"Done\");\n}"
},
{
"code": null,
"e": 2384,
"s": 2349,
"text": "my_fun function\nMain Function\nDone"
}
] |
SymPy - Printing
|
There are several printers available in SymPy. Following is a partial list −
str
srepr
ASCII pretty printer
Unicode pretty printer
LaTeX
MathML
Dot
SymPy objects can also be sent as output to code of various languages, such as C, Fortran, Javascript, Theano, and Python.
SymPy uses Unicode characters to render output in form of pretty print. If you are using Python console for executing SymPy session, the best pretty printing environment is activated by calling init_session() function.
>>> from sympy import init_session
>>> init_session()
IPython console for SymPy 1.5.1 (Python 3.7.4-64-bit) (ground types: python).
These commands were executed −
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()
Documentation can be found at https://docs.sympy.org/1.5.1/.
>>> Integral(sqrt(1/x),x)
∫1xdx
If LATEX is not installed, but Matplotlib is installed, it will use the Matplotlib rendering engine. If Matplotlib is not installed, it uses the Unicode pretty printer. However, Jupyter notebook uses MathJax to render LATEX.
In a terminal that does not support Unicode, ASCII pretty printer is used.
To use ASCII printer use pprint() function with use_unicode property set to False
>>> pprint(Integral(sqrt(1/x),x),use_unicode=False)
The Unicode pretty printer is also accessed from pprint() and pretty(). If the terminal supports Unicode, it is used automatically. If pprint() is not able to detect that the terminal supports unicode, you can pass use_unicode=True to force it to use Unicode.
To get the LATEX form of an expression, use latex() function.
>>> print(latex(Integral(sqrt(1/x),x)))
\int \sqrt{\frac{1}{x}}\, dx
You can also use mathml printer. for that purpose, import print_mathml function. A string version is obtained by mathml() function.
>>> from sympy.printing.mathml import print_mathml
>>> print_mathml(Integral(sqrt(1/x),x))
<apply>
<int/>
<bvar>
<ci>x</ci>
</bvar>
<apply>
<root/>
<apply>
<power/>
<ci>x</ci>
<cn>-1</cn>
</apply>
</apply>
</apply>
>>>mathml(Integral(sqrt(1/x),x))
'<apply><int/><bvar><ci>x</ci></bvar><apply><root/><apply><power/><ci>x</ci><cn>-1</cn></apply></apply></apply>'
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2096,
"s": 2019,
"text": "There are several printers available in SymPy. Following is a partial list −"
},
{
"code": null,
"e": 2100,
"s": 2096,
"text": "str"
},
{
"code": null,
"e": 2106,
"s": 2100,
"text": "srepr"
},
{
"code": null,
"e": 2127,
"s": 2106,
"text": "ASCII pretty printer"
},
{
"code": null,
"e": 2150,
"s": 2127,
"text": "Unicode pretty printer"
},
{
"code": null,
"e": 2156,
"s": 2150,
"text": "LaTeX"
},
{
"code": null,
"e": 2163,
"s": 2156,
"text": "MathML"
},
{
"code": null,
"e": 2167,
"s": 2163,
"text": "Dot"
},
{
"code": null,
"e": 2290,
"s": 2167,
"text": "SymPy objects can also be sent as output to code of various languages, such as C, Fortran, Javascript, Theano, and Python."
},
{
"code": null,
"e": 2509,
"s": 2290,
"text": "SymPy uses Unicode characters to render output in form of pretty print. If you are using Python console for executing SymPy session, the best pretty printing environment is activated by calling init_session() function."
},
{
"code": null,
"e": 2565,
"s": 2509,
"text": ">>> from sympy import init_session \n>>> init_session()\n"
},
{
"code": null,
"e": 2643,
"s": 2565,
"text": "IPython console for SymPy 1.5.1 (Python 3.7.4-64-bit) (ground types: python)."
},
{
"code": null,
"e": 2674,
"s": 2643,
"text": "These commands were executed −"
},
{
"code": null,
"e": 2881,
"s": 2674,
"text": ">>> from __future__ import division\n>>> from sympy import *\n>>> x, y, z, t = symbols('x y z t')\n>>> k, m, n = symbols('k m n', integer=True)\n>>> f, g, h = symbols('f g h', cls=Function)\n>>> init_printing()\n"
},
{
"code": null,
"e": 2942,
"s": 2881,
"text": "Documentation can be found at https://docs.sympy.org/1.5.1/."
},
{
"code": null,
"e": 2969,
"s": 2942,
"text": ">>> Integral(sqrt(1/x),x)\n"
},
{
"code": null,
"e": 2975,
"s": 2969,
"text": "∫1xdx"
},
{
"code": null,
"e": 3200,
"s": 2975,
"text": "If LATEX is not installed, but Matplotlib is installed, it will use the Matplotlib rendering engine. If Matplotlib is not installed, it uses the Unicode pretty printer. However, Jupyter notebook uses MathJax to render LATEX."
},
{
"code": null,
"e": 3275,
"s": 3200,
"text": "In a terminal that does not support Unicode, ASCII pretty printer is used."
},
{
"code": null,
"e": 3357,
"s": 3275,
"text": "To use ASCII printer use pprint() function with use_unicode property set to False"
},
{
"code": null,
"e": 3410,
"s": 3357,
"text": ">>> pprint(Integral(sqrt(1/x),x),use_unicode=False)\n"
},
{
"code": null,
"e": 3670,
"s": 3410,
"text": "The Unicode pretty printer is also accessed from pprint() and pretty(). If the terminal supports Unicode, it is used automatically. If pprint() is not able to detect that the terminal supports unicode, you can pass use_unicode=True to force it to use Unicode."
},
{
"code": null,
"e": 3732,
"s": 3670,
"text": "To get the LATEX form of an expression, use latex() function."
},
{
"code": null,
"e": 3773,
"s": 3732,
"text": ">>> print(latex(Integral(sqrt(1/x),x)))\n"
},
{
"code": null,
"e": 3802,
"s": 3773,
"text": "\\int \\sqrt{\\frac{1}{x}}\\, dx"
},
{
"code": null,
"e": 3934,
"s": 3802,
"text": "You can also use mathml printer. for that purpose, import print_mathml function. A string version is obtained by mathml() function."
},
{
"code": null,
"e": 4027,
"s": 3934,
"text": ">>> from sympy.printing.mathml import print_mathml \n>>> print_mathml(Integral(sqrt(1/x),x))\n"
},
{
"code": null,
"e": 4035,
"s": 4027,
"text": "<apply>"
},
{
"code": null,
"e": 4042,
"s": 4035,
"text": "<int/>"
},
{
"code": null,
"e": 4049,
"s": 4042,
"text": "<bvar>"
},
{
"code": null,
"e": 4060,
"s": 4049,
"text": "<ci>x</ci>"
},
{
"code": null,
"e": 4068,
"s": 4060,
"text": "</bvar>"
},
{
"code": null,
"e": 4076,
"s": 4068,
"text": "<apply>"
},
{
"code": null,
"e": 4084,
"s": 4076,
"text": "<root/>"
},
{
"code": null,
"e": 4092,
"s": 4084,
"text": "<apply>"
},
{
"code": null,
"e": 4101,
"s": 4092,
"text": "<power/>"
},
{
"code": null,
"e": 4112,
"s": 4101,
"text": "<ci>x</ci>"
},
{
"code": null,
"e": 4124,
"s": 4112,
"text": "<cn>-1</cn>"
},
{
"code": null,
"e": 4133,
"s": 4124,
"text": "</apply>"
},
{
"code": null,
"e": 4142,
"s": 4133,
"text": "</apply>"
},
{
"code": null,
"e": 4151,
"s": 4142,
"text": "</apply>"
},
{
"code": null,
"e": 4185,
"s": 4151,
"text": ">>>mathml(Integral(sqrt(1/x),x))\n"
},
{
"code": null,
"e": 4298,
"s": 4185,
"text": "'<apply><int/><bvar><ci>x</ci></bvar><apply><root/><apply><power/><ci>x</ci><cn>-1</cn></apply></apply></apply>'"
},
{
"code": null,
"e": 4305,
"s": 4298,
"text": " Print"
},
{
"code": null,
"e": 4316,
"s": 4305,
"text": " Add Notes"
}
] |
Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space - GeeksforGeeks
|
11 Aug, 2021
Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space.
Examples:
Input : arr[] = { 1, 2, 9, 15 }
Output : 1 9 2 15
Input : arr[] = { 1, 2, 3, 4, 5, 6 }
Output : 1 4 2 5 3 6
Method 1: Brute Force A brute force solution involves two nested loops to rotate the elements in the second half of the array to the left. The first loop runs n times to cover all elements in the second half of the array. The second loop rotates the elements to the left. Note that the start index in the second loop depends on which element we are rotating and the end index depends on how many positions we need to move to the left.
Below is implementation of this approach:
C++
Java
Python3
C#
Javascript
// C++ Naive program to shuffle an array of size 2n#include <bits/stdc++.h>using namespace std; // function to shuffle an array of size 2nvoid shuffleArray(int a[], int n){ // Rotate the element to the left for (int i = 0, q = 1, k = n; i < n; i++, k++, q++) for (int j = k; j > i + q; j--) swap(a[j - 1], a[j]);} // Driven Programint main(){ int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; int n = sizeof(a) / sizeof(a[0]); shuffleArray(a, n / 2); for (int i = 0; i < n; i++) cout << a[i] << " "; return 0;}
// Java Naive program to shuffle an array of size 2n import java.util.Arrays; public class GFG { // method to shuffle an array of size 2n static void shuffleArray(int a[], int n) { // Rotate the element to the left for (int i = 0, q = 1, k = n; i < n; i++, k++, q++) for (int j = k; j > i + q; j--) { // swap a[j-1], a[j] int temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } // Driver Method public static void main(String[] args) { int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; shuffleArray(a, a.length / 2); System.out.println(Arrays.toString(a)); }}
# Python3 Naive program to# shuffle an array of size 2n # Function to shuffle an array of size 2ndef shuffleArray(a, n): # Rotate the element to the left i, q, k = 0, 1, n while(i < n): j = k while(j > i + q): a[j - 1], a[j] = a[j], a[j - 1] j -= 1 i += 1 k += 1 q += 1 # Driver Codea = [1, 3, 5, 7, 2, 4, 6, 8]n = len(a)shuffleArray(a, int(n / 2))for i in range(0, n): print(a[i], end = " ") # This code is contributed by Smitha Dinesh Semwal.
// C# Naive program to shuffle an// array of size 2nusing System; class GFG { // method to shuffle an array of size 2n static void shuffleArray(int[] a, int n) { // Rotate the element to the left for (int i = 0, q = 1, k = n; i < n; i++, k++, q++) for (int j = k; j > i + q; j--) { // swap a[j-1], a[j] int temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } // Driver Code public static void Main() { int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 }; shuffleArray(a, a.Length / 2); for (int i = 0; i < a.Length; i++) Console.Write(a[i] + " "); }} // This code is contributed// by ChitraNayal
<script>// Javascript Naive program to shuffle an array of size 2n // method to shuffle an array of size 2n function shuffleArray(a,n) { // Rotate the element to the left for (let i = 0, q = 1, k = n; i < n; i++, k++, q++) for (let j = k; j > i + q; j--) { // swap a[j-1], a[j] let temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } // Driver Method let a=[ 1, 3, 5, 7, 2, 4, 6, 8]; shuffleArray(a, a.length / 2); document.write(a.join(" ")); //This code is contributed by avanitrachhadiya2155 </script>
Output:
1 2 3 4 5 6 7 8
Time Complexity: O(n2)
Method 2: (Divide and Conquer) The idea is to use Divide and Conquer Technique. Divide the given array into half (say arr1[] and arr2[]) and swap second half element of arr1[] with first half element of arr2[]. Recursively do this for arr1 and arr2.
Let us explain with the help of an example.
Let the array be a1, a2, a3, a4, b1, b2, b3, b4Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly. you get: a1, a2, b1, b2, a3, a4, b3, b4Recursively split a1, a2, b1, b2 into a1, a2 : b1, b2 then split a3, a4, b3, b4 into a3, a4 : b3, b4.Exchange elements around the center for each subarray we get: a1, b1, a2, b2 and a3, b3, a4, b4.
Let the array be a1, a2, a3, a4, b1, b2, b3, b4
Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4
Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly. you get: a1, a2, b1, b2, a3, a4, b3, b4
Recursively split a1, a2, b1, b2 into a1, a2 : b1, b2 then split a3, a4, b3, b4 into a3, a4 : b3, b4.
Exchange elements around the center for each subarray we get: a1, b1, a2, b2 and a3, b3, a4, b4.
Note: This solution only handles the case when n = 2i where i = 0, 1, 2, ...etc.
Below is implementation of this approach:
C++
Java
Python3
C#
Javascript
// C++ Effective program to shuffle an array of size 2n #include <bits/stdc++.h>using namespace std; // function to shuffle an array of size 2nvoid shufleArray(int a[], int f, int l){ if (f > l) { return; } // If only 2 element, return if (l - f == 1) return; // finding mid to divide the array int mid = (f + l) / 2; // using temp for swapping first half of second array int temp = mid + 1; // mmid is use for swapping second half for first array int mmid = (f + mid) / 2; // Swapping the element for (int i = mmid + 1; i <= mid; i++) swap(a[i], a[temp++]); // Recursively doing for first half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l);} // Driven Programint main(){ int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; int n = sizeof(a) / sizeof(a[0]); shufleArray(a, 0, n - 1); for (int i = 0; i < n; i++) cout << a[i] << " "; return 0;}
// Java Effective program to shuffle an array of size 2n import java.util.Arrays; public class GFG { // method to shuffle an array of size 2n static void shufleArray(int a[], int f, int l) { if (f > l) return; // If only 2 element, return if (l - f == 1) return; // finding mid to divide the array int mid = (f + l) / 2; // using temp for swapping first half of second array int temp = mid + 1; // mmid is use for swapping second half for first array int mmid = (f + mid) / 2; // Swapping the element for (int i = mmid + 1; i <= mid; i++) { // swap a[i], a[temp++] int temp1 = a[i]; a[i] = a[temp]; a[temp++] = temp1; } // Recursively doing for first half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l); } // Driver Method public static void main(String[] args) { int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; shufleArray(a, 0, a.length - 1); System.out.println(Arrays.toString(a)); }}
# Python3 effective program to# shuffle an array of size 2n # Function to shuffle an array of size 2ndef shufleArray(a, f, l): if (f > l): return # If only 2 element, return if (l - f == 1): return # Finding mid to divide the array mid = int((f + l) / 2) # Using temp for swapping first # half of the second array temp = mid + 1 # Mid is use for swapping second # half for first array mmid = int((f + mid) / 2) # Swapping the element for i in range(mmid + 1, mid + 1): (a[i], a[temp]) = (a[temp], a[i]) temp += 1 # Recursively doing for first # half and second half shufleArray(a, f, mid) shufleArray(a, mid + 1, l) # Driver Codea = [1, 3, 5, 7, 2, 4, 6, 8]n = len(a)shufleArray(a, 0, n - 1) for i in range(0, n): print(a[i], end = " ") # This code is contributed by Smitha Dinesh Semwal
// C# program program to merge two// sorted arrays with O(1) extra space.using System; // method to shuffle an array of size 2n public class GFG { // method to shuffle an array of size 2n static void shufleArray(int[] a, int f, int l) { if (f > l) return; // If only 2 element, return if (l - f == 1) return; // finding mid to divide the array int mid = (f + l) / 2; // using temp for swapping first half of second array int temp = mid + 1; // mmid is use for swapping second half for first array int mmid = (f + mid) / 2; // Swapping the element for (int i = mmid + 1; i <= mid; i++) { // swap a[i], a[temp++] int temp1 = a[i]; a[i] = a[temp]; a[temp++] = temp1; } // Recursively doing for first half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l); } // Driver Method public static void Main() { int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 }; shufleArray(a, 0, a.Length - 1); for (int i = 0; i < a.Length; i++) Console.Write(a[i] + " "); }} /*This code is contributed by 29AjayKumar*/
<script> // Javascript Effective program to// shuffle an array of size 2n // method to shuffle an array of size 2nfunction shufleArray(a, f, l){ if (f > l) return; // If only 2 element, return if (l - f == 1) return; // Finding mid to divide the array let mid = Math.floor((f + l) / 2); // Using temp for swapping first // half of second array let temp = mid + 1; // mmid is use for swapping second // half for first array let mmid = Math.floor((f + mid) / 2); // Swapping the element for(let i = mmid + 1; i <= mid; i++) { // Swap a[i], a[temp++] let temp1 = a[i]; a[i] = a[temp]; a[temp++] = temp1; } // Recursively doing for first // half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l);} // Driver Codelet a = [ 1, 3, 5, 7, 2, 4, 6, 8 ];shufleArray(a, 0, a.length - 1); document.write(a.join(" ")); // This code is contributed by rag2127 </script>
Output:
1 2 3 4 5 6 7 8
Time Complexity: O(n log n)Linear time solution
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
29AjayKumar
ADITYA_VERMA_
coder_krishna
avanitrachhadiya2155
rag2127
akshaysingh98088
Adobe
Arrays
Divide and Conquer
Recursion
Adobe
Arrays
Recursion
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi
|
[
{
"code": null,
"e": 25012,
"s": 24984,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25226,
"s": 25012,
"text": "Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space. "
},
{
"code": null,
"e": 25237,
"s": 25226,
"text": "Examples: "
},
{
"code": null,
"e": 25347,
"s": 25237,
"text": "Input : arr[] = { 1, 2, 9, 15 }\nOutput : 1 9 2 15\n\nInput : arr[] = { 1, 2, 3, 4, 5, 6 }\nOutput : 1 4 2 5 3 6"
},
{
"code": null,
"e": 25782,
"s": 25347,
"text": "Method 1: Brute Force A brute force solution involves two nested loops to rotate the elements in the second half of the array to the left. The first loop runs n times to cover all elements in the second half of the array. The second loop rotates the elements to the left. Note that the start index in the second loop depends on which element we are rotating and the end index depends on how many positions we need to move to the left."
},
{
"code": null,
"e": 25825,
"s": 25782,
"text": "Below is implementation of this approach: "
},
{
"code": null,
"e": 25829,
"s": 25825,
"text": "C++"
},
{
"code": null,
"e": 25834,
"s": 25829,
"text": "Java"
},
{
"code": null,
"e": 25842,
"s": 25834,
"text": "Python3"
},
{
"code": null,
"e": 25845,
"s": 25842,
"text": "C#"
},
{
"code": null,
"e": 25856,
"s": 25845,
"text": "Javascript"
},
{
"code": "// C++ Naive program to shuffle an array of size 2n#include <bits/stdc++.h>using namespace std; // function to shuffle an array of size 2nvoid shuffleArray(int a[], int n){ // Rotate the element to the left for (int i = 0, q = 1, k = n; i < n; i++, k++, q++) for (int j = k; j > i + q; j--) swap(a[j - 1], a[j]);} // Driven Programint main(){ int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; int n = sizeof(a) / sizeof(a[0]); shuffleArray(a, n / 2); for (int i = 0; i < n; i++) cout << a[i] << \" \"; return 0;}",
"e": 26404,
"s": 25856,
"text": null
},
{
"code": "// Java Naive program to shuffle an array of size 2n import java.util.Arrays; public class GFG { // method to shuffle an array of size 2n static void shuffleArray(int a[], int n) { // Rotate the element to the left for (int i = 0, q = 1, k = n; i < n; i++, k++, q++) for (int j = k; j > i + q; j--) { // swap a[j-1], a[j] int temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } // Driver Method public static void main(String[] args) { int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; shuffleArray(a, a.length / 2); System.out.println(Arrays.toString(a)); }}",
"e": 27095,
"s": 26404,
"text": null
},
{
"code": "# Python3 Naive program to# shuffle an array of size 2n # Function to shuffle an array of size 2ndef shuffleArray(a, n): # Rotate the element to the left i, q, k = 0, 1, n while(i < n): j = k while(j > i + q): a[j - 1], a[j] = a[j], a[j - 1] j -= 1 i += 1 k += 1 q += 1 # Driver Codea = [1, 3, 5, 7, 2, 4, 6, 8]n = len(a)shuffleArray(a, int(n / 2))for i in range(0, n): print(a[i], end = \" \") # This code is contributed by Smitha Dinesh Semwal.",
"e": 27614,
"s": 27095,
"text": null
},
{
"code": "// C# Naive program to shuffle an// array of size 2nusing System; class GFG { // method to shuffle an array of size 2n static void shuffleArray(int[] a, int n) { // Rotate the element to the left for (int i = 0, q = 1, k = n; i < n; i++, k++, q++) for (int j = k; j > i + q; j--) { // swap a[j-1], a[j] int temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } // Driver Code public static void Main() { int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 }; shuffleArray(a, a.Length / 2); for (int i = 0; i < a.Length; i++) Console.Write(a[i] + \" \"); }} // This code is contributed// by ChitraNayal",
"e": 28360,
"s": 27614,
"text": null
},
{
"code": "<script>// Javascript Naive program to shuffle an array of size 2n // method to shuffle an array of size 2n function shuffleArray(a,n) { // Rotate the element to the left for (let i = 0, q = 1, k = n; i < n; i++, k++, q++) for (let j = k; j > i + q; j--) { // swap a[j-1], a[j] let temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } // Driver Method let a=[ 1, 3, 5, 7, 2, 4, 6, 8]; shuffleArray(a, a.length / 2); document.write(a.join(\" \")); //This code is contributed by avanitrachhadiya2155 </script>",
"e": 29009,
"s": 28360,
"text": null
},
{
"code": null,
"e": 29018,
"s": 29009,
"text": "Output: "
},
{
"code": null,
"e": 29035,
"s": 29018,
"text": "1 2 3 4 5 6 7 8 "
},
{
"code": null,
"e": 29058,
"s": 29035,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 29308,
"s": 29058,
"text": "Method 2: (Divide and Conquer) The idea is to use Divide and Conquer Technique. Divide the given array into half (say arr1[] and arr2[]) and swap second half element of arr1[] with first half element of arr2[]. Recursively do this for arr1 and arr2."
},
{
"code": null,
"e": 29353,
"s": 29308,
"text": "Let us explain with the help of an example. "
},
{
"code": null,
"e": 29782,
"s": 29353,
"text": "Let the array be a1, a2, a3, a4, b1, b2, b3, b4Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly. you get: a1, a2, b1, b2, a3, a4, b3, b4Recursively split a1, a2, b1, b2 into a1, a2 : b1, b2 then split a3, a4, b3, b4 into a3, a4 : b3, b4.Exchange elements around the center for each subarray we get: a1, b1, a2, b2 and a3, b3, a4, b4."
},
{
"code": null,
"e": 29830,
"s": 29782,
"text": "Let the array be a1, a2, a3, a4, b1, b2, b3, b4"
},
{
"code": null,
"e": 29895,
"s": 29830,
"text": "Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4"
},
{
"code": null,
"e": 30016,
"s": 29895,
"text": "Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly. you get: a1, a2, b1, b2, a3, a4, b3, b4"
},
{
"code": null,
"e": 30118,
"s": 30016,
"text": "Recursively split a1, a2, b1, b2 into a1, a2 : b1, b2 then split a3, a4, b3, b4 into a3, a4 : b3, b4."
},
{
"code": null,
"e": 30215,
"s": 30118,
"text": "Exchange elements around the center for each subarray we get: a1, b1, a2, b2 and a3, b3, a4, b4."
},
{
"code": null,
"e": 30296,
"s": 30215,
"text": "Note: This solution only handles the case when n = 2i where i = 0, 1, 2, ...etc."
},
{
"code": null,
"e": 30339,
"s": 30296,
"text": "Below is implementation of this approach: "
},
{
"code": null,
"e": 30343,
"s": 30339,
"text": "C++"
},
{
"code": null,
"e": 30348,
"s": 30343,
"text": "Java"
},
{
"code": null,
"e": 30356,
"s": 30348,
"text": "Python3"
},
{
"code": null,
"e": 30359,
"s": 30356,
"text": "C#"
},
{
"code": null,
"e": 30370,
"s": 30359,
"text": "Javascript"
},
{
"code": "// C++ Effective program to shuffle an array of size 2n #include <bits/stdc++.h>using namespace std; // function to shuffle an array of size 2nvoid shufleArray(int a[], int f, int l){ if (f > l) { return; } // If only 2 element, return if (l - f == 1) return; // finding mid to divide the array int mid = (f + l) / 2; // using temp for swapping first half of second array int temp = mid + 1; // mmid is use for swapping second half for first array int mmid = (f + mid) / 2; // Swapping the element for (int i = mmid + 1; i <= mid; i++) swap(a[i], a[temp++]); // Recursively doing for first half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l);} // Driven Programint main(){ int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; int n = sizeof(a) / sizeof(a[0]); shufleArray(a, 0, n - 1); for (int i = 0; i < n; i++) cout << a[i] << \" \"; return 0;}",
"e": 31319,
"s": 30370,
"text": null
},
{
"code": "// Java Effective program to shuffle an array of size 2n import java.util.Arrays; public class GFG { // method to shuffle an array of size 2n static void shufleArray(int a[], int f, int l) { if (f > l) return; // If only 2 element, return if (l - f == 1) return; // finding mid to divide the array int mid = (f + l) / 2; // using temp for swapping first half of second array int temp = mid + 1; // mmid is use for swapping second half for first array int mmid = (f + mid) / 2; // Swapping the element for (int i = mmid + 1; i <= mid; i++) { // swap a[i], a[temp++] int temp1 = a[i]; a[i] = a[temp]; a[temp++] = temp1; } // Recursively doing for first half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l); } // Driver Method public static void main(String[] args) { int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; shufleArray(a, 0, a.length - 1); System.out.println(Arrays.toString(a)); }}",
"e": 32443,
"s": 31319,
"text": null
},
{
"code": "# Python3 effective program to# shuffle an array of size 2n # Function to shuffle an array of size 2ndef shufleArray(a, f, l): if (f > l): return # If only 2 element, return if (l - f == 1): return # Finding mid to divide the array mid = int((f + l) / 2) # Using temp for swapping first # half of the second array temp = mid + 1 # Mid is use for swapping second # half for first array mmid = int((f + mid) / 2) # Swapping the element for i in range(mmid + 1, mid + 1): (a[i], a[temp]) = (a[temp], a[i]) temp += 1 # Recursively doing for first # half and second half shufleArray(a, f, mid) shufleArray(a, mid + 1, l) # Driver Codea = [1, 3, 5, 7, 2, 4, 6, 8]n = len(a)shufleArray(a, 0, n - 1) for i in range(0, n): print(a[i], end = \" \") # This code is contributed by Smitha Dinesh Semwal",
"e": 33321,
"s": 32443,
"text": null
},
{
"code": "// C# program program to merge two// sorted arrays with O(1) extra space.using System; // method to shuffle an array of size 2n public class GFG { // method to shuffle an array of size 2n static void shufleArray(int[] a, int f, int l) { if (f > l) return; // If only 2 element, return if (l - f == 1) return; // finding mid to divide the array int mid = (f + l) / 2; // using temp for swapping first half of second array int temp = mid + 1; // mmid is use for swapping second half for first array int mmid = (f + mid) / 2; // Swapping the element for (int i = mmid + 1; i <= mid; i++) { // swap a[i], a[temp++] int temp1 = a[i]; a[i] = a[temp]; a[temp++] = temp1; } // Recursively doing for first half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l); } // Driver Method public static void Main() { int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 }; shufleArray(a, 0, a.Length - 1); for (int i = 0; i < a.Length; i++) Console.Write(a[i] + \" \"); }} /*This code is contributed by 29AjayKumar*/",
"e": 34553,
"s": 33321,
"text": null
},
{
"code": "<script> // Javascript Effective program to// shuffle an array of size 2n // method to shuffle an array of size 2nfunction shufleArray(a, f, l){ if (f > l) return; // If only 2 element, return if (l - f == 1) return; // Finding mid to divide the array let mid = Math.floor((f + l) / 2); // Using temp for swapping first // half of second array let temp = mid + 1; // mmid is use for swapping second // half for first array let mmid = Math.floor((f + mid) / 2); // Swapping the element for(let i = mmid + 1; i <= mid; i++) { // Swap a[i], a[temp++] let temp1 = a[i]; a[i] = a[temp]; a[temp++] = temp1; } // Recursively doing for first // half and second half shufleArray(a, f, mid); shufleArray(a, mid + 1, l);} // Driver Codelet a = [ 1, 3, 5, 7, 2, 4, 6, 8 ];shufleArray(a, 0, a.length - 1); document.write(a.join(\" \")); // This code is contributed by rag2127 </script>",
"e": 35546,
"s": 34553,
"text": null
},
{
"code": null,
"e": 35555,
"s": 35546,
"text": "Output: "
},
{
"code": null,
"e": 35572,
"s": 35555,
"text": "1 2 3 4 5 6 7 8 "
},
{
"code": null,
"e": 35620,
"s": 35572,
"text": "Time Complexity: O(n log n)Linear time solution"
},
{
"code": null,
"e": 36041,
"s": 35620,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36047,
"s": 36041,
"text": "ukasp"
},
{
"code": null,
"e": 36059,
"s": 36047,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36073,
"s": 36059,
"text": "ADITYA_VERMA_"
},
{
"code": null,
"e": 36087,
"s": 36073,
"text": "coder_krishna"
},
{
"code": null,
"e": 36108,
"s": 36087,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 36116,
"s": 36108,
"text": "rag2127"
},
{
"code": null,
"e": 36133,
"s": 36116,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 36139,
"s": 36133,
"text": "Adobe"
},
{
"code": null,
"e": 36146,
"s": 36139,
"text": "Arrays"
},
{
"code": null,
"e": 36165,
"s": 36146,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 36175,
"s": 36165,
"text": "Recursion"
},
{
"code": null,
"e": 36181,
"s": 36175,
"text": "Adobe"
},
{
"code": null,
"e": 36188,
"s": 36181,
"text": "Arrays"
},
{
"code": null,
"e": 36198,
"s": 36188,
"text": "Recursion"
},
{
"code": null,
"e": 36217,
"s": 36198,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 36315,
"s": 36217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36324,
"s": 36315,
"text": "Comments"
},
{
"code": null,
"e": 36337,
"s": 36324,
"text": "Old Comments"
},
{
"code": null,
"e": 36360,
"s": 36337,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36392,
"s": 36360,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36406,
"s": 36392,
"text": "Linear Search"
},
{
"code": null,
"e": 36474,
"s": 36406,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36519,
"s": 36474,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36530,
"s": 36519,
"text": "Merge Sort"
},
{
"code": null,
"e": 36540,
"s": 36530,
"text": "QuickSort"
},
{
"code": null,
"e": 36554,
"s": 36540,
"text": "Binary Search"
},
{
"code": null,
"e": 36622,
"s": 36554,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
Java Connection rollBack() method with example
|
A rollback operation undoes all the changes done by the current transaction i.e. If you call a rollBack() method of the Connection interface, all the modifications are reverted until the last commit.Con.rollback()
You can also rollback the changes in the database up to a particular save point by passing the required Savepoint object as a parameter to this method as −
//Setting the save point
con.rollback("MysavePoint");
To roll back a transaction
Register the driver using the registerDriver() method of the DriverManager class as −
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get the connection using the getConnection() method of the DriverManager class as −
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
Turn off the auto-commit using the setAutoCommit() method as −
//Setting the auto commit false
con.setAutoCommit(false);
Set the save point using the setSavepoint() or, commit the transaction using the commit() method as −
Savepoint savePoint = con.setSavepoint("MysavePoint");
Con.commit();
Finally, rollback to the last save point or, last commit using the rollback() or, rollback(Savepoint savepoint) methods.
con.rollback()
Or,
con. rollback(mySavepoint);
Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −
CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
Following JDBC program demonstrates the rollback() method of the Connection interface. Here, we inserted a new record in the Myplayers table. Completed the transaction using the commit() method, deleted the previously inserted record and rolled back to the created save point and displayed the contents of the table
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connection_rollBack {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
System.out.println("Connection established......");
//Setting the auto commit false
con.setAutoCommit(false);
//Creating a Statement object
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from MyPlayers");
System.out.println("Contents of the table initially");
while(rs.next()) {
System.out.print("ID: "+rs.getString("ID")+", ");
System.out.print("First_Name: "+rs.getString("First_Name")+", ");
System.out.print("Last_Name: "+rs.getString("Last_Name")+", ");
System.out.print("Date_Of_Birth: "+rs.getString("Date_Of_Birth")+", ");
System.out.print("Place_Of_Birth: "+rs.getString("Place_Of_Birth")+", ");
System.out.print("Country: "+rs.getString("Country"));
System.out.println("");
}
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyPlayers VALUES (?, ?, ?, ?, ?, ?)");
pstmt.setInt(1, 8);
pstmt.setString(2, "Ishant");
pstmt.setString(3, "Sharma");
pstmt.setDate(4, new Date(904694400000L));
pstmt.setString(5, "Delhi");
pstmt.setString(6, "India");
pstmt.executeUpdate();
//Committing the transaction
con.commit();
//Deleting the record
stmt.execute("Delete from MyPlayers where id = 8");
//Rolling back to the save point
con.rollback();
//Contents of the table after the roll-back
System.out.println("Contents of the table");
rs = stmt.executeQuery("select * from MyPlayers");
while(rs.next()) {
System.out.print("ID: "+rs.getString("ID")+", ");
System.out.print("First_Name: "+rs.getString("First_Name")+", ");
System.out.print("Last_Name: "+rs.getString("Last_Name")+", ");
System.out.print("Date_Of_Birth: "+rs.getString("Date_Of_Birth")+", ");
System.out.print("Place_Of_Birth: "+rs.getString("Place_Of_Birth")+", ");
System.out.print("Country: "+rs.getString("Country"));
System.out.println("");
}
}
}
Now, you can observe the new record created before the save point in the result though we have deleted it.
All the changes done past the last commit will be reverted if we rollback a transaction.
Since we have deleted the 8th record after setting the commit, this delete is reverted at the time of roll back.
Connection established......
Contents of the table initially
ID: 1, First_Name: Shikhar, Last_Name: Dhawan, Date_Of_Birth: 1981-12-05, Place_Of_Birth: Delhi, Country: India
ID: 2, First_Name: Jonathan, Last_Name: Trott, Date_Of_Birth: 1981-04-22, Place_Of_Birth: CapeTown, Country: SouthAfrica
ID: 3, First_Name: Kumara, Last_Name: Sangakkara, Date_Of_Birth: 1977-10-27, Place_Of_Birth: Matale, Country: Srilanka
ID: 4, First_Name: Virat, Last_Name: Kohli, Date_Of_Birth: 1988-11-05, Place_Of_Birth: Mumbai, Country: India
ID: 5, First_Name: Rohit, Last_Name: Sharma, Date_Of_Birth: 1987-04-30, Place_Of_Birth: Nagpur, Country: India
ID: 6, First_Name: Ravindra, Last_Name: Jadeja, Date_Of_Birth: 1988-12-06, Place_Of_Birth: Nagpur, Country: India
ID: 7, First_Name: James, Last_Name: Anderson, Date_Of_Birth: 1982-06-30, Place_Of_Birth: Burnley , Country: England
Contents of the table after rollback
ID: 1, First_Name: Shikhar, Last_Name: Dhawan, Date_Of_Birth: 1981-12-05, Place_Of_Birth: Delhi, Country: India
ID: 2, First_Name: Jonathan, Last_Name: Trott, Date_Of_Birth: 1981-04-22, Place_Of_Birth: CapeTown, Country: SouthAfrica
ID: 3, First_Name: Kumara, Last_Name: Sangakkara, Date_Of_Birth: 1977-10-27, Place_Of_Birth: Matale, Country: Srilanka
ID: 4, First_Name: Virat, Last_Name: Kohli, Date_Of_Birth: 1988-11-05, Place_Of_Birth: Mumbai, Country: India
ID: 5, First_Name: Rohit, Last_Name: Sharma, Date_Of_Birth: 1987-04-30, Place_Of_Birth: Nagpur, Country: India
ID: 6, First_Name: Ravindra, Last_Name: Jadeja, Date_Of_Birth: 1988-12-06, Place_Of_Birth: Nagpur, Country: India
ID: 7, First_Name: James, Last_Name: Anderson, Date_Of_Birth: 1982-06-30, Place_Of_Birth: Burnley , Country: England
ID: 8, First_Name: Ishant, Last_Name: Sharma, Date_Of_Birth: 1998-09-02, Place_Of_Birth: Delhi, Country: India
|
[
{
"code": null,
"e": 1276,
"s": 1062,
"text": "A rollback operation undoes all the changes done by the current transaction i.e. If you call a rollBack() method of the Connection interface, all the modifications are reverted until the last commit.Con.rollback()"
},
{
"code": null,
"e": 1432,
"s": 1276,
"text": "You can also rollback the changes in the database up to a particular save point by passing the required Savepoint object as a parameter to this method as −"
},
{
"code": null,
"e": 1486,
"s": 1432,
"text": "//Setting the save point\ncon.rollback(\"MysavePoint\");"
},
{
"code": null,
"e": 1513,
"s": 1486,
"text": "To roll back a transaction"
},
{
"code": null,
"e": 1599,
"s": 1513,
"text": "Register the driver using the registerDriver() method of the DriverManager class as −"
},
{
"code": null,
"e": 1683,
"s": 1599,
"text": "//Registering the Driver\nDriverManager.registerDriver(new com.mysql.jdbc.Driver());"
},
{
"code": null,
"e": 1767,
"s": 1683,
"text": "Get the connection using the getConnection() method of the DriverManager class as −"
},
{
"code": null,
"e": 1913,
"s": 1767,
"text": "//Getting the connection\nString url = \"jdbc:mysql://localhost/mydatabase\";\nConnection con = DriverManager.getConnection(url, \"root\", \"password\");"
},
{
"code": null,
"e": 1976,
"s": 1913,
"text": "Turn off the auto-commit using the setAutoCommit() method as −"
},
{
"code": null,
"e": 2034,
"s": 1976,
"text": "//Setting the auto commit false\ncon.setAutoCommit(false);"
},
{
"code": null,
"e": 2136,
"s": 2034,
"text": "Set the save point using the setSavepoint() or, commit the transaction using the commit() method as −"
},
{
"code": null,
"e": 2205,
"s": 2136,
"text": "Savepoint savePoint = con.setSavepoint(\"MysavePoint\");\nCon.commit();"
},
{
"code": null,
"e": 2326,
"s": 2205,
"text": "Finally, rollback to the last save point or, last commit using the rollback() or, rollback(Savepoint savepoint) methods."
},
{
"code": null,
"e": 2373,
"s": 2326,
"text": "con.rollback()\nOr,\ncon. rollback(mySavepoint);"
},
{
"code": null,
"e": 2473,
"s": 2373,
"text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −"
},
{
"code": null,
"e": 2666,
"s": 2473,
"text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 2741,
"s": 2666,
"text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −"
},
{
"code": null,
"e": 3403,
"s": 2741,
"text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');"
},
{
"code": null,
"e": 3719,
"s": 3403,
"text": "Following JDBC program demonstrates the rollback() method of the Connection interface. Here, we inserted a new record in the Myplayers table. Completed the transaction using the commit() method, deleted the previously inserted record and rolled back to the created save point and displayed the contents of the table"
},
{
"code": null,
"e": 6423,
"s": 3719,
"text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class Connection_rollBack {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(url, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Setting the auto commit false\n con.setAutoCommit(false);\n //Creating a Statement object\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from MyPlayers\");\n System.out.println(\"Contents of the table initially\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getString(\"ID\")+\", \");\n System.out.print(\"First_Name: \"+rs.getString(\"First_Name\")+\", \");\n System.out.print(\"Last_Name: \"+rs.getString(\"Last_Name\")+\", \");\n System.out.print(\"Date_Of_Birth: \"+rs.getString(\"Date_Of_Birth\")+\", \");\n System.out.print(\"Place_Of_Birth: \"+rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs.getString(\"Country\"));\n System.out.println(\"\");\n }\n PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO MyPlayers VALUES (?, ?, ?, ?, ?, ?)\");\n pstmt.setInt(1, 8);\n pstmt.setString(2, \"Ishant\");\n pstmt.setString(3, \"Sharma\");\n pstmt.setDate(4, new Date(904694400000L));\n pstmt.setString(5, \"Delhi\");\n pstmt.setString(6, \"India\");\n pstmt.executeUpdate();\n //Committing the transaction\n con.commit();\n //Deleting the record\n stmt.execute(\"Delete from MyPlayers where id = 8\");\n //Rolling back to the save point\n con.rollback();\n //Contents of the table after the roll-back\n System.out.println(\"Contents of the table\");\n rs = stmt.executeQuery(\"select * from MyPlayers\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getString(\"ID\")+\", \");\n System.out.print(\"First_Name: \"+rs.getString(\"First_Name\")+\", \");\n System.out.print(\"Last_Name: \"+rs.getString(\"Last_Name\")+\", \");\n System.out.print(\"Date_Of_Birth: \"+rs.getString(\"Date_Of_Birth\")+\", \");\n System.out.print(\"Place_Of_Birth: \"+rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs.getString(\"Country\"));\n System.out.println(\"\");\n }\n }\n}"
},
{
"code": null,
"e": 6530,
"s": 6423,
"text": "Now, you can observe the new record created before the save point in the result though we have deleted it."
},
{
"code": null,
"e": 6619,
"s": 6530,
"text": "All the changes done past the last commit will be reverted if we rollback a transaction."
},
{
"code": null,
"e": 6732,
"s": 6619,
"text": "Since we have deleted the 8th record after setting the commit, this delete is reverted at the time of roll back."
},
{
"code": null,
"e": 8549,
"s": 6732,
"text": "Connection established......\nContents of the table initially\nID: 1, First_Name: Shikhar, Last_Name: Dhawan, Date_Of_Birth: 1981-12-05, Place_Of_Birth: Delhi, Country: India\nID: 2, First_Name: Jonathan, Last_Name: Trott, Date_Of_Birth: 1981-04-22, Place_Of_Birth: CapeTown, Country: SouthAfrica\nID: 3, First_Name: Kumara, Last_Name: Sangakkara, Date_Of_Birth: 1977-10-27, Place_Of_Birth: Matale, Country: Srilanka\nID: 4, First_Name: Virat, Last_Name: Kohli, Date_Of_Birth: 1988-11-05, Place_Of_Birth: Mumbai, Country: India\nID: 5, First_Name: Rohit, Last_Name: Sharma, Date_Of_Birth: 1987-04-30, Place_Of_Birth: Nagpur, Country: India\nID: 6, First_Name: Ravindra, Last_Name: Jadeja, Date_Of_Birth: 1988-12-06, Place_Of_Birth: Nagpur, Country: India\nID: 7, First_Name: James, Last_Name: Anderson, Date_Of_Birth: 1982-06-30, Place_Of_Birth: Burnley , Country: England\nContents of the table after rollback\nID: 1, First_Name: Shikhar, Last_Name: Dhawan, Date_Of_Birth: 1981-12-05, Place_Of_Birth: Delhi, Country: India\nID: 2, First_Name: Jonathan, Last_Name: Trott, Date_Of_Birth: 1981-04-22, Place_Of_Birth: CapeTown, Country: SouthAfrica\nID: 3, First_Name: Kumara, Last_Name: Sangakkara, Date_Of_Birth: 1977-10-27, Place_Of_Birth: Matale, Country: Srilanka\nID: 4, First_Name: Virat, Last_Name: Kohli, Date_Of_Birth: 1988-11-05, Place_Of_Birth: Mumbai, Country: India\nID: 5, First_Name: Rohit, Last_Name: Sharma, Date_Of_Birth: 1987-04-30, Place_Of_Birth: Nagpur, Country: India\nID: 6, First_Name: Ravindra, Last_Name: Jadeja, Date_Of_Birth: 1988-12-06, Place_Of_Birth: Nagpur, Country: India\nID: 7, First_Name: James, Last_Name: Anderson, Date_Of_Birth: 1982-06-30, Place_Of_Birth: Burnley , Country: England\nID: 8, First_Name: Ishant, Last_Name: Sharma, Date_Of_Birth: 1998-09-02, Place_Of_Birth: Delhi, Country: India"
}
] |
Different Methods to find Prime Number in Java
|
A prime number is a number that is only divisible by one or itself. Some of the prime numbers are 2, 3, 5, 7, 11, 13 etc.
Some of the different methods to find a prime number in Java are given as follows −
A program that finds if the given number is prime without using a function is given as follow −
Live Demo
public class Example {
public static void main(String args[]) {
int num = 11, flag=0;
if(num == 0||num == 1) {
System.out.println( num + " is not a prime number");
} else {
for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
System.out.println( num + " is not prime number");
flag = 1;
break;
}
}
if(flag == 0) {
System.out.println( num + " is a prime number");
}
}
}
}
11 is a prime number
A program that finds if the given number is prime using a function is given as follow −
Live Demo
public class Example {
static int PrimeOrNot(int num) {
int flag = 0;
if(num == 0||num == 1) {
flag = 1;
} else {
for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
flag = 1;
break;
}
}
}
return flag;
}
public static void main(String args[]) {
int flag, num = 11;
flag = PrimeOrNot(num);
if(flag == 0) {
System.out.println( num + " is a prime number");
} else {
System.out.println( num + " is not a prime number");
}
}
}
11 is a prime number
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "A prime number is a number that is only divisible by one or itself. Some of the prime numbers are 2, 3, 5, 7, 11, 13 etc."
},
{
"code": null,
"e": 1268,
"s": 1184,
"text": "Some of the different methods to find a prime number in Java are given as follows −"
},
{
"code": null,
"e": 1364,
"s": 1268,
"text": "A program that finds if the given number is prime without using a function is given as follow −"
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": " Live Demo"
},
{
"code": null,
"e": 1902,
"s": 1375,
"text": "public class Example {\n public static void main(String args[]) {\n int num = 11, flag=0;\n if(num == 0||num == 1) {\n System.out.println( num + \" is not a prime number\");\n } else {\n for(int i = 2; i <= num/2; i++) {\n if(num % i == 0) {\n System.out.println( num + \" is not prime number\");\n flag = 1;\n break;\n }\n }\n if(flag == 0) {\n System.out.println( num + \" is a prime number\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 1923,
"s": 1902,
"text": "11 is a prime number"
},
{
"code": null,
"e": 2011,
"s": 1923,
"text": "A program that finds if the given number is prime using a function is given as follow −"
},
{
"code": null,
"e": 2022,
"s": 2011,
"text": " Live Demo"
},
{
"code": null,
"e": 2616,
"s": 2022,
"text": "public class Example {\n static int PrimeOrNot(int num) {\n int flag = 0;\n if(num == 0||num == 1) {\n flag = 1;\n } else {\n for(int i = 2; i <= num/2; i++) {\n if(num % i == 0) {\n flag = 1;\n break;\n }\n }\n }\n return flag;\n }\n public static void main(String args[]) {\n int flag, num = 11;\n flag = PrimeOrNot(num);\n if(flag == 0) {\n System.out.println( num + \" is a prime number\");\n } else {\n System.out.println( num + \" is not a prime number\");\n }\n }\n}"
},
{
"code": null,
"e": 2637,
"s": 2616,
"text": "11 is a prime number"
}
] |
Check if it possible to partition in k subarrays with equal sum - GeeksforGeeks
|
05 May, 2021
Given an array A of size N, and a number K. Task is to find out if it is possible to partition the array A into K contiguous subarrays such that the sum of elements within each of these subarrays is the same.Prerequisite: Count the number of ways to divide an array into three contiguous parts having equal sum
Examples :
Input : arr[] = { 1, 4, 2, 3, 5 } K = 3
Output : Yes
Explanation :
Three possible partitions which have equal sum :
(1 + 4), (2 + 3) and (5)
Input : arr[] = { 1, 1, 2, 2 } K = 2
Output : No
Approach : Can be solved by using Prefix Sums. Firstly, note that total sum of all elements in the array should be divisible by K to create K partitions each having equal sum. If it is divisible then, check each partition have an equal sum by doing : 1. For a particular K, each subarray should have a required sum = total_sum / K.2. Starting from the 0th index, start comparing prefix sum, as soon as it is equal to the sum, it implies the end of one subarray (let’s say at index j).3. From (j + 1)th index, find another suitable i whose sum (prefix_sum[i] – prefix_sum[j]) gets equal to the required sum. And the process goes until required number of contiguous subarrays i.e. K is found.4. If at any index, any subarray sum becomes greater than required sum, break out from loop since each subarray should contain that an equal sum.
Following is the implementation for above Approach
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to check if array// can be split into K contiguous// subarrays each having equal sum#include <bits/stdc++.h>using namespace std; // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falsebool KpartitionsPossible(int arr[], int n, int K){ // Creating and filling prefix sum array int prefix_sum[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is not // divisible by K int total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions int temp = 0; int pos = -1; for (int i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == total_sum / K) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - prefix_sum[pos] > total_sum / K) break; } // check if temp has reached to K return (temp == K);} // Driver Codeint main(){ int arr[] = { 4, 4, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 3; if (KpartitionsPossible(arr, n, K)) cout << "Yes"; else cout << "No"; return 0;}
// Java Program to check if an array// can be split into K contiguous// subarrays each having equal sumpublic class GfG{ // Function returns true to it is possible to // create K contiguous partitions each having // equal sum, otherwise false static boolean KpartitionsPossible(int arr[], int n, int K) { // Creating and filling prefix sum array int prefix_sum[] = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is not divisible by K int total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions int temp = 0, pos = -1; for (int i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == total_sum / K) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) > total_sum / K) break; } // check if temp has reached to K return (temp == K); } public static void main(String []args){ int arr[] = { 4, 4, 3, 5, 6, 2 }; int n = arr.length; int K = 3; if (KpartitionsPossible(arr, n, K)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Rituraj Jain
# Python 3 Program to check if array# can be split into K contiguous# subarrays each having equal sum # function returns true to it is possible to# create K contiguous partitions each having# equal sum, otherwise falsedef KpartitionsPossible(arr, n, K): # Creating and filling prefix sum array prefix_sum = [0 for i in range(n)] prefix_sum[0] = arr[0] for i in range(1, n, 1): prefix_sum[i] = prefix_sum[i - 1] + arr[i] # return false if total_sum is not # divisible by K total_sum = prefix_sum[n - 1] if (total_sum % K != 0): return False # a temporary variable to check # there are exactly K partitions temp = 0 pos = -1 for i in range(0, n, 1): # find suitable i for which first # partition have the required sum # and then find next partition and so on if (pos == -1): sub = 0 else: sub = prefix_sum[pos] if (prefix_sum[i] - sub == total_sum / K) : pos = i temp += 1 # if it becomes greater than # required sum break out elif (prefix_sum[i] - prefix_sum[pos] > total_sum / K): break # check if temp has reached to K return (temp == K) # Driver Codeif __name__ =='__main__': arr = [4, 4, 3, 5, 6, 2] n = len(arr) K = 3 if (KpartitionsPossible(arr, n, K)): print("Yes") else: print("No") # This code is contributed by# Shashank_Sharma
// C# Program to check if an array// can be split into K contiguous// subarrays each having equal sumusing System; class GfG{ // Function returns true to it is possible to // create K contiguous partitions each having // equal sum, otherwise false static bool KpartitionsPossible(int[] arr, int n, int K) { // Creating and filling prefix sum array int[] prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is not divisible by K int total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions int temp = 0, pos = -1; for (int i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == total_sum / K) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) > total_sum / K) break; } // check if temp has reached to K return (temp == K); } // Driver code public static void Main() { int[] arr = { 4, 4, 3, 5, 6, 2 }; int n = arr.Length; int K = 3; if (KpartitionsPossible(arr, n, K)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by ChitraNayal
<?php// PHP Program to check if array// can be split into K contiguous// subarrays each having equal sum // function returns true to// it is possible to create// K contiguous partitions// each having equal sum,// otherwise falsefunction KpartitionsPossible($arr, $n, $K){ // Creating and filling // prefix sum array $prefix_sum = Array(); $prefix_sum[0] = $arr[0]; for ($i = 1; $i < $n; $i++) $prefix_sum[$i] = $prefix_sum[$i - 1] + $arr[$i]; // return false if total_sum // is not divisible by K $total_sum = $prefix_sum[$n - 1]; if ($total_sum % $K != 0) return false; // a temporary variable to // check there are exactly // K partitions $temp = 0; $pos = -1; for ($i = 0; $i < $n; $i++) { // find suitable i for which // first partition have the // required sum and then find // next partition and so on if ($prefix_sum[$i] - ($pos == -1 ? 0 : $prefix_sum[$pos]) == (int)$total_sum / $K) { $pos = $i; $temp++; } } // check if temp has // reached to K return ($temp == $K);} // Driver Code$arr = array (4, 4, 3, 5, 6, 2);$n = sizeof($arr) ; $K = 3;if (KpartitionsPossible($arr, $n, $K)) echo "Yes";else echo "No"; // This code is contributed by m_kit?>
<script> // Javascript Program to check if an array // can be split into K contiguous // subarrays each having equal sum // Function returns true to it is possible to // create K contiguous partitions each having // equal sum, otherwise false function KpartitionsPossible(arr, n, K) { // Creating and filling prefix sum array let prefix_sum = new Array(n); prefix_sum[0] = arr[0]; for (let i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is // not divisible by K let total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions let temp = 0, pos = -1; for (let i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == parseInt(total_sum / K, 10)) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) > parseInt(total_sum / K, 10)) break; } // check if temp has reached to K return (temp == K); } let arr = [ 4, 4, 3, 5, 6, 2 ]; let n = arr.length; let K = 3; if (KpartitionsPossible(arr, n, K)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity : O(N), where N is the size of array. Auxiliary Space : O(N), where N is the size of array.
We can further reduce the space complexity to O(1).Since the array will be divided to k sub arrays and all the sub arrays will be continuous. So idea is to calculate the count of sub arrays whose sum is equal to sum of whole array divided by k. if count == k print Yes else print No.
Following is the implementation for above Approach
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to check if array// can be split into K contiguous// subarrays each having equal sum#include <bits/stdc++.h>using namespace std; // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falseint KpartitionsPossible(int arr[], int n, int k){ int sum = 0; int count = 0; // calculate the sum of the array for(int i = 0; i < n; i++) sum = sum + arr[i]; if(sum % k != 0) return 0; sum = sum / k; int ksum = 0; // ksum denotes the sum of each subarray for(int i = 0; i < n; i++) { ksum=ksum + arr[i]; // one subarray is found if(ksum == sum) { // to locate another ksum = 0; count++; } } if(count == k) return 1; else return 0; } // Driver codeint main() { int arr[] = { 1, 1, 2, 2};int k = 2; int n = sizeof(arr) / sizeof(arr[0]); if (KpartitionsPossible(arr, n, k) == 0) cout << "Yes"; else cout<<"No"; return 0; }
//Java Program to check if array// can be split into K contiguous// subarrays each having equal sum public class GFG { // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise false static int KpartitionsPossible(int arr[], int n, int k) { int sum = 0; int count = 0; // calculate the sum of the array for (int i = 0; i < n; i++) { sum = sum + arr[i]; } if (sum % k != 0) { return 0; } sum = sum / k; int ksum = 0; // ksum denotes the sum of each subarray for (int i = 0; i < n; i++) { ksum = ksum + arr[i]; // one subarray is found if (ksum == sum) { // to locate another ksum = 0; count++; } } if (count == k) { return 1; } else { return 0; } } // Driver Code public static void main(String[] args) { int arr[] = {1, 1, 2, 2}; int k = 2; int n = arr.length; if (KpartitionsPossible(arr, n, k) == 0) { System.out.println("Yes"); } else { System.out.println("No"); } } } /*This code is contributed by PrinciRaj1992*/
# Python3 Program to check if array# can be split into K contiguous# subarrays each having equal sum # Function returns true to it is possible# to create K contiguous partitions each# having equal sum, otherwise falsedef KpartitionsPossible(arr, n, k) : sum = 0 count = 0 # calculate the sum of the array for i in range(n) : sum = sum + arr[i] if(sum % k != 0) : return 0 sum = sum // k ksum = 0 # ksum denotes the sum of each subarray for i in range(n) : ksum = ksum + arr[i] # one subarray is found if(ksum == sum) : # to locate another ksum = 0 count += 1 if(count == k) : return 1 else : return 0 # Driver codeif __name__ == "__main__" : arr = [ 1, 1, 2, 2] k = 2 n = len(arr) if (KpartitionsPossible(arr, n, k) == 0) : print("Yes") else : print("No") # This code is contributed by Ryuga
// C# Program to check if array// can be split into K contiguous// subarrays each having equal sum using System;public class GFG{ // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise false static int KpartitionsPossible(int []arr, int n, int k) { int sum = 0; int count = 0; // calculate the sum of the array for (int i = 0; i < n; i++) { sum = sum + arr[i]; } if (sum % k != 0) { return 0; } sum = sum / k; int ksum = 0; // ksum denotes the sum of each subarray for (int i = 0; i < n; i++) { ksum = ksum + arr[i]; // one subarray is found if (ksum == sum) { // to locate another ksum = 0; count++; } } if (count == k) { return 1; } else { return 0; } } // Driver Code public static void Main() { int []arr = {1, 1, 2, 2}; int k = 2; int n = arr.Length; if (KpartitionsPossible(arr, n, k) == 0) { Console.Write("Yes"); } else { Console.Write("No"); } } } /*This code is contributed by PrinciRaj1992*/
<?php// PHP Program to check if array// can be split into K contiguous// subarrays each having equal sum // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falsefunction KpartitionsPossible($arr, $n, $k){ $sum = 0; $count = 0; // calculate the sum of the array for($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; if($sum % $k != 0) return 0; $sum = $sum / $k; $ksum = 0; // ksum denotes the sum of each subarray for( $i = 0; $i < $n; $i++) { $ksum = $ksum + $arr[$i]; // one subarray is found if($ksum == $sum) { // to locate another $ksum = 0; $count++; } } if($count == $k) return 1; else return 0; } // Driver code$arr = array(1, 1, 2, 2);$k = 2;$n = count($arr);if (KpartitionsPossible($arr, $n, $k) == 0) echo "Yes";else echo "No"; // This code is contributed by// Rajput-Ji?>
<script> // Javascript program to check if array// can be split into K contiguous// subarrays each having equal sum // Function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falsefunction KpartitionsPossible(arr, n, k){ let sum = 0; let count = 0; // Calculate the sum of the array for(let i = 0; i < n; i++) sum = sum + arr[i]; if (sum % k != 0) return 0; sum = parseInt(sum / k, 10); let ksum = 0; // ksum denotes the sum of each subarray for(let i = 0; i < n; i++) { ksum = ksum + arr[i]; // One subarray is found if (ksum == sum) { // To locate another ksum = 0; count++; } } if (count == k) return 1; else return 0;} // Driver codelet arr = [ 1, 1, 2, 2 ];let k = 2;let n = arr.length; if (KpartitionsPossible(arr, n, k) == 0) document.write("Yes");else document.write("No"); // This code is contributed by mukesh07 </script>
Yes
jit_t
Kushdeep_Mittal
princiraj1992
ankthon
Shashank_Sharma
Rajput-Ji
rituraj_jain
ukasp
divyeshrabadiya07
mukesh07
prefix-sum
subarray
subarray-sum
Arrays
Technical Scripter
prefix-sum
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25611,
"s": 25300,
"text": "Given an array A of size N, and a number K. Task is to find out if it is possible to partition the array A into K contiguous subarrays such that the sum of elements within each of these subarrays is the same.Prerequisite: Count the number of ways to divide an array into three contiguous parts having equal sum"
},
{
"code": null,
"e": 25623,
"s": 25611,
"text": "Examples : "
},
{
"code": null,
"e": 25815,
"s": 25623,
"text": "Input : arr[] = { 1, 4, 2, 3, 5 } K = 3\nOutput : Yes\nExplanation :\nThree possible partitions which have equal sum : \n(1 + 4), (2 + 3) and (5)\n\nInput : arr[] = { 1, 1, 2, 2 } K = 2\nOutput : No"
},
{
"code": null,
"e": 26651,
"s": 25815,
"text": "Approach : Can be solved by using Prefix Sums. Firstly, note that total sum of all elements in the array should be divisible by K to create K partitions each having equal sum. If it is divisible then, check each partition have an equal sum by doing : 1. For a particular K, each subarray should have a required sum = total_sum / K.2. Starting from the 0th index, start comparing prefix sum, as soon as it is equal to the sum, it implies the end of one subarray (let’s say at index j).3. From (j + 1)th index, find another suitable i whose sum (prefix_sum[i] – prefix_sum[j]) gets equal to the required sum. And the process goes until required number of contiguous subarrays i.e. K is found.4. If at any index, any subarray sum becomes greater than required sum, break out from loop since each subarray should contain that an equal sum."
},
{
"code": null,
"e": 26703,
"s": 26651,
"text": "Following is the implementation for above Approach "
},
{
"code": null,
"e": 26707,
"s": 26703,
"text": "C++"
},
{
"code": null,
"e": 26712,
"s": 26707,
"text": "Java"
},
{
"code": null,
"e": 26720,
"s": 26712,
"text": "Python3"
},
{
"code": null,
"e": 26723,
"s": 26720,
"text": "C#"
},
{
"code": null,
"e": 26727,
"s": 26723,
"text": "PHP"
},
{
"code": null,
"e": 26738,
"s": 26727,
"text": "Javascript"
},
{
"code": "// CPP Program to check if array// can be split into K contiguous// subarrays each having equal sum#include <bits/stdc++.h>using namespace std; // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falsebool KpartitionsPossible(int arr[], int n, int K){ // Creating and filling prefix sum array int prefix_sum[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is not // divisible by K int total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions int temp = 0; int pos = -1; for (int i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == total_sum / K) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - prefix_sum[pos] > total_sum / K) break; } // check if temp has reached to K return (temp == K);} // Driver Codeint main(){ int arr[] = { 4, 4, 3, 5, 6, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 3; if (KpartitionsPossible(arr, n, K)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 28281,
"s": 26738,
"text": null
},
{
"code": "// Java Program to check if an array// can be split into K contiguous// subarrays each having equal sumpublic class GfG{ // Function returns true to it is possible to // create K contiguous partitions each having // equal sum, otherwise false static boolean KpartitionsPossible(int arr[], int n, int K) { // Creating and filling prefix sum array int prefix_sum[] = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is not divisible by K int total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions int temp = 0, pos = -1; for (int i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == total_sum / K) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) > total_sum / K) break; } // check if temp has reached to K return (temp == K); } public static void main(String []args){ int arr[] = { 4, 4, 3, 5, 6, 2 }; int n = arr.length; int K = 3; if (KpartitionsPossible(arr, n, K)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Rituraj Jain",
"e": 30094,
"s": 28281,
"text": null
},
{
"code": "# Python 3 Program to check if array# can be split into K contiguous# subarrays each having equal sum # function returns true to it is possible to# create K contiguous partitions each having# equal sum, otherwise falsedef KpartitionsPossible(arr, n, K): # Creating and filling prefix sum array prefix_sum = [0 for i in range(n)] prefix_sum[0] = arr[0] for i in range(1, n, 1): prefix_sum[i] = prefix_sum[i - 1] + arr[i] # return false if total_sum is not # divisible by K total_sum = prefix_sum[n - 1] if (total_sum % K != 0): return False # a temporary variable to check # there are exactly K partitions temp = 0 pos = -1 for i in range(0, n, 1): # find suitable i for which first # partition have the required sum # and then find next partition and so on if (pos == -1): sub = 0 else: sub = prefix_sum[pos] if (prefix_sum[i] - sub == total_sum / K) : pos = i temp += 1 # if it becomes greater than # required sum break out elif (prefix_sum[i] - prefix_sum[pos] > total_sum / K): break # check if temp has reached to K return (temp == K) # Driver Codeif __name__ =='__main__': arr = [4, 4, 3, 5, 6, 2] n = len(arr) K = 3 if (KpartitionsPossible(arr, n, K)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Shashank_Sharma",
"e": 31582,
"s": 30094,
"text": null
},
{
"code": "// C# Program to check if an array// can be split into K contiguous// subarrays each having equal sumusing System; class GfG{ // Function returns true to it is possible to // create K contiguous partitions each having // equal sum, otherwise false static bool KpartitionsPossible(int[] arr, int n, int K) { // Creating and filling prefix sum array int[] prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is not divisible by K int total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions int temp = 0, pos = -1; for (int i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == total_sum / K) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) > total_sum / K) break; } // check if temp has reached to K return (temp == K); } // Driver code public static void Main() { int[] arr = { 4, 4, 3, 5, 6, 2 }; int n = arr.Length; int K = 3; if (KpartitionsPossible(arr, n, K)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by ChitraNayal",
"e": 33401,
"s": 31582,
"text": null
},
{
"code": "<?php// PHP Program to check if array// can be split into K contiguous// subarrays each having equal sum // function returns true to// it is possible to create// K contiguous partitions// each having equal sum,// otherwise falsefunction KpartitionsPossible($arr, $n, $K){ // Creating and filling // prefix sum array $prefix_sum = Array(); $prefix_sum[0] = $arr[0]; for ($i = 1; $i < $n; $i++) $prefix_sum[$i] = $prefix_sum[$i - 1] + $arr[$i]; // return false if total_sum // is not divisible by K $total_sum = $prefix_sum[$n - 1]; if ($total_sum % $K != 0) return false; // a temporary variable to // check there are exactly // K partitions $temp = 0; $pos = -1; for ($i = 0; $i < $n; $i++) { // find suitable i for which // first partition have the // required sum and then find // next partition and so on if ($prefix_sum[$i] - ($pos == -1 ? 0 : $prefix_sum[$pos]) == (int)$total_sum / $K) { $pos = $i; $temp++; } } // check if temp has // reached to K return ($temp == $K);} // Driver Code$arr = array (4, 4, 3, 5, 6, 2);$n = sizeof($arr) ; $K = 3;if (KpartitionsPossible($arr, $n, $K)) echo \"Yes\";else echo \"No\"; // This code is contributed by m_kit?>",
"e": 34830,
"s": 33401,
"text": null
},
{
"code": "<script> // Javascript Program to check if an array // can be split into K contiguous // subarrays each having equal sum // Function returns true to it is possible to // create K contiguous partitions each having // equal sum, otherwise false function KpartitionsPossible(arr, n, K) { // Creating and filling prefix sum array let prefix_sum = new Array(n); prefix_sum[0] = arr[0]; for (let i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // return false if total_sum is // not divisible by K let total_sum = prefix_sum[n-1]; if (total_sum % K != 0) return false; // a temporary variable to check // there are exactly K partitions let temp = 0, pos = -1; for (let i = 0; i < n; i++) { // find suitable i for which first // partition have the required sum // and then find next partition and so on if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) == parseInt(total_sum / K, 10)) { pos = i; temp++; } // if it becomes greater than // required sum break out else if (prefix_sum[i] - (pos == -1 ? 0 : prefix_sum[pos]) > parseInt(total_sum / K, 10)) break; } // check if temp has reached to K return (temp == K); } let arr = [ 4, 4, 3, 5, 6, 2 ]; let n = arr.length; let K = 3; if (KpartitionsPossible(arr, n, K)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 36586,
"s": 34830,
"text": null
},
{
"code": null,
"e": 36590,
"s": 36586,
"text": "Yes"
},
{
"code": null,
"e": 36700,
"s": 36592,
"text": "Time Complexity : O(N), where N is the size of array. Auxiliary Space : O(N), where N is the size of array."
},
{
"code": null,
"e": 36984,
"s": 36700,
"text": "We can further reduce the space complexity to O(1).Since the array will be divided to k sub arrays and all the sub arrays will be continuous. So idea is to calculate the count of sub arrays whose sum is equal to sum of whole array divided by k. if count == k print Yes else print No."
},
{
"code": null,
"e": 37036,
"s": 36984,
"text": "Following is the implementation for above Approach "
},
{
"code": null,
"e": 37040,
"s": 37036,
"text": "C++"
},
{
"code": null,
"e": 37045,
"s": 37040,
"text": "Java"
},
{
"code": null,
"e": 37053,
"s": 37045,
"text": "Python3"
},
{
"code": null,
"e": 37056,
"s": 37053,
"text": "C#"
},
{
"code": null,
"e": 37060,
"s": 37056,
"text": "PHP"
},
{
"code": null,
"e": 37071,
"s": 37060,
"text": "Javascript"
},
{
"code": "// CPP Program to check if array// can be split into K contiguous// subarrays each having equal sum#include <bits/stdc++.h>using namespace std; // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falseint KpartitionsPossible(int arr[], int n, int k){ int sum = 0; int count = 0; // calculate the sum of the array for(int i = 0; i < n; i++) sum = sum + arr[i]; if(sum % k != 0) return 0; sum = sum / k; int ksum = 0; // ksum denotes the sum of each subarray for(int i = 0; i < n; i++) { ksum=ksum + arr[i]; // one subarray is found if(ksum == sum) { // to locate another ksum = 0; count++; } } if(count == k) return 1; else return 0; } // Driver codeint main() { int arr[] = { 1, 1, 2, 2};int k = 2; int n = sizeof(arr) / sizeof(arr[0]); if (KpartitionsPossible(arr, n, k) == 0) cout << \"Yes\"; else cout<<\"No\"; return 0; }",
"e": 38107,
"s": 37071,
"text": null
},
{
"code": "//Java Program to check if array// can be split into K contiguous// subarrays each having equal sum public class GFG { // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise false static int KpartitionsPossible(int arr[], int n, int k) { int sum = 0; int count = 0; // calculate the sum of the array for (int i = 0; i < n; i++) { sum = sum + arr[i]; } if (sum % k != 0) { return 0; } sum = sum / k; int ksum = 0; // ksum denotes the sum of each subarray for (int i = 0; i < n; i++) { ksum = ksum + arr[i]; // one subarray is found if (ksum == sum) { // to locate another ksum = 0; count++; } } if (count == k) { return 1; } else { return 0; } } // Driver Code public static void main(String[] args) { int arr[] = {1, 1, 2, 2}; int k = 2; int n = arr.length; if (KpartitionsPossible(arr, n, k) == 0) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } } } /*This code is contributed by PrinciRaj1992*/",
"e": 39409,
"s": 38107,
"text": null
},
{
"code": "# Python3 Program to check if array# can be split into K contiguous# subarrays each having equal sum # Function returns true to it is possible# to create K contiguous partitions each# having equal sum, otherwise falsedef KpartitionsPossible(arr, n, k) : sum = 0 count = 0 # calculate the sum of the array for i in range(n) : sum = sum + arr[i] if(sum % k != 0) : return 0 sum = sum // k ksum = 0 # ksum denotes the sum of each subarray for i in range(n) : ksum = ksum + arr[i] # one subarray is found if(ksum == sum) : # to locate another ksum = 0 count += 1 if(count == k) : return 1 else : return 0 # Driver codeif __name__ == \"__main__\" : arr = [ 1, 1, 2, 2] k = 2 n = len(arr) if (KpartitionsPossible(arr, n, k) == 0) : print(\"Yes\") else : print(\"No\") # This code is contributed by Ryuga",
"e": 40366,
"s": 39409,
"text": null
},
{
"code": "// C# Program to check if array// can be split into K contiguous// subarrays each having equal sum using System;public class GFG{ // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise false static int KpartitionsPossible(int []arr, int n, int k) { int sum = 0; int count = 0; // calculate the sum of the array for (int i = 0; i < n; i++) { sum = sum + arr[i]; } if (sum % k != 0) { return 0; } sum = sum / k; int ksum = 0; // ksum denotes the sum of each subarray for (int i = 0; i < n; i++) { ksum = ksum + arr[i]; // one subarray is found if (ksum == sum) { // to locate another ksum = 0; count++; } } if (count == k) { return 1; } else { return 0; } } // Driver Code public static void Main() { int []arr = {1, 1, 2, 2}; int k = 2; int n = arr.Length; if (KpartitionsPossible(arr, n, k) == 0) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); } } } /*This code is contributed by PrinciRaj1992*/",
"e": 41657,
"s": 40366,
"text": null
},
{
"code": "<?php// PHP Program to check if array// can be split into K contiguous// subarrays each having equal sum // function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falsefunction KpartitionsPossible($arr, $n, $k){ $sum = 0; $count = 0; // calculate the sum of the array for($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; if($sum % $k != 0) return 0; $sum = $sum / $k; $ksum = 0; // ksum denotes the sum of each subarray for( $i = 0; $i < $n; $i++) { $ksum = $ksum + $arr[$i]; // one subarray is found if($ksum == $sum) { // to locate another $ksum = 0; $count++; } } if($count == $k) return 1; else return 0; } // Driver code$arr = array(1, 1, 2, 2);$k = 2;$n = count($arr);if (KpartitionsPossible($arr, $n, $k) == 0) echo \"Yes\";else echo \"No\"; // This code is contributed by// Rajput-Ji?>",
"e": 42680,
"s": 41657,
"text": null
},
{
"code": "<script> // Javascript program to check if array// can be split into K contiguous// subarrays each having equal sum // Function returns true to it is possible to// create K contiguous partitions each having// equal sum, otherwise falsefunction KpartitionsPossible(arr, n, k){ let sum = 0; let count = 0; // Calculate the sum of the array for(let i = 0; i < n; i++) sum = sum + arr[i]; if (sum % k != 0) return 0; sum = parseInt(sum / k, 10); let ksum = 0; // ksum denotes the sum of each subarray for(let i = 0; i < n; i++) { ksum = ksum + arr[i]; // One subarray is found if (ksum == sum) { // To locate another ksum = 0; count++; } } if (count == k) return 1; else return 0;} // Driver codelet arr = [ 1, 1, 2, 2 ];let k = 2;let n = arr.length; if (KpartitionsPossible(arr, n, k) == 0) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by mukesh07 </script>",
"e": 43739,
"s": 42680,
"text": null
},
{
"code": null,
"e": 43743,
"s": 43739,
"text": "Yes"
},
{
"code": null,
"e": 43751,
"s": 43745,
"text": "jit_t"
},
{
"code": null,
"e": 43767,
"s": 43751,
"text": "Kushdeep_Mittal"
},
{
"code": null,
"e": 43781,
"s": 43767,
"text": "princiraj1992"
},
{
"code": null,
"e": 43789,
"s": 43781,
"text": "ankthon"
},
{
"code": null,
"e": 43805,
"s": 43789,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 43815,
"s": 43805,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 43828,
"s": 43815,
"text": "rituraj_jain"
},
{
"code": null,
"e": 43834,
"s": 43828,
"text": "ukasp"
},
{
"code": null,
"e": 43852,
"s": 43834,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 43861,
"s": 43852,
"text": "mukesh07"
},
{
"code": null,
"e": 43872,
"s": 43861,
"text": "prefix-sum"
},
{
"code": null,
"e": 43881,
"s": 43872,
"text": "subarray"
},
{
"code": null,
"e": 43894,
"s": 43881,
"text": "subarray-sum"
},
{
"code": null,
"e": 43901,
"s": 43894,
"text": "Arrays"
},
{
"code": null,
"e": 43920,
"s": 43901,
"text": "Technical Scripter"
},
{
"code": null,
"e": 43931,
"s": 43920,
"text": "prefix-sum"
},
{
"code": null,
"e": 43938,
"s": 43931,
"text": "Arrays"
},
{
"code": null,
"e": 44036,
"s": 43938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44045,
"s": 44036,
"text": "Comments"
},
{
"code": null,
"e": 44058,
"s": 44045,
"text": "Old Comments"
},
{
"code": null,
"e": 44106,
"s": 44058,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 44150,
"s": 44106,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 44173,
"s": 44150,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 44205,
"s": 44173,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 44219,
"s": 44205,
"text": "Linear Search"
},
{
"code": null,
"e": 44287,
"s": 44219,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 44332,
"s": 44287,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 44353,
"s": 44332,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 44407,
"s": 44353,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
}
] |
React Props
|
Props are arguments passed into React components.
Props are passed to components via HTML attributes.
props stands for properties.
React Props are like function arguments in JavaScript and attributes
in HTML.
To send props into a component, use the same syntax as HTML attributes:
Add a "brand" attribute to the Car element:
const myElement = <Car brand="Ford" />;
The component receives the argument as a props object:
Use the brand attribute in the component:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
Run
Example »
Props are also how you pass data from one component to another, as parameters.
Send the "brand" property from the Garage component to the Car component:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Run
Example »
If you have a variable to send, and not a string as in the example above, you just put the variable name inside curly brackets:
Create a variable named carName and send it to the
Car component:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Run
Example »
Or if it was an object:
Create an object named carInfo and send it to the
Car component:
function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Run
Example »
Note: React Props are read-only! You will get an error if you try to change their
value.
Create a variable named name and pass it to the Message component.
function Person(props) {
return <h2>I'm { props.name }!</h2>;
}
function Greeting() {
const name = "Jesse"
return (
<>
<h1>Hello!</h1>
<Person name= name />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Greeting />);
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:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 50,
"s": 0,
"text": "Props are arguments passed into React components."
},
{
"code": null,
"e": 102,
"s": 50,
"text": "Props are passed to components via HTML attributes."
},
{
"code": null,
"e": 131,
"s": 102,
"text": "props stands for properties."
},
{
"code": null,
"e": 210,
"s": 131,
"text": "React Props are like function arguments in JavaScript and attributes \nin HTML."
},
{
"code": null,
"e": 282,
"s": 210,
"text": "To send props into a component, use the same syntax as HTML attributes:"
},
{
"code": null,
"e": 326,
"s": 282,
"text": "Add a \"brand\" attribute to the Car element:"
},
{
"code": null,
"e": 366,
"s": 326,
"text": "const myElement = <Car brand=\"Ford\" />;"
},
{
"code": null,
"e": 421,
"s": 366,
"text": "The component receives the argument as a props object:"
},
{
"code": null,
"e": 463,
"s": 421,
"text": "Use the brand attribute in the component:"
},
{
"code": null,
"e": 531,
"s": 463,
"text": "function Car(props) {\n return <h2>I am a { props.brand }!</h2>;\n}\n"
},
{
"code": null,
"e": 548,
"s": 531,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 627,
"s": 548,
"text": "Props are also how you pass data from one component to another, as parameters."
},
{
"code": null,
"e": 701,
"s": 627,
"text": "Send the \"brand\" property from the Garage component to the Car component:"
},
{
"code": null,
"e": 982,
"s": 701,
"text": "function Car(props) {\n return <h2>I am a { props.brand }!</h2>;\n}\n\nfunction Garage() {\n return (\n <>\n <h1>Who lives in my garage?</h1>\n <Car brand=\"Ford\" />\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Garage />);\n"
},
{
"code": null,
"e": 999,
"s": 982,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1127,
"s": 999,
"text": "If you have a variable to send, and not a string as in the example above, you just put the variable name inside curly brackets:"
},
{
"code": null,
"e": 1194,
"s": 1127,
"text": "Create a variable named carName and send it to the \nCar component:"
},
{
"code": null,
"e": 1506,
"s": 1194,
"text": "function Car(props) {\n return <h2>I am a { props.brand }!</h2>;\n}\n\nfunction Garage() {\n const carName = \"Ford\";\n return (\n <>\n <h1>Who lives in my garage?</h1>\n <Car brand={ carName } />\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Garage />);\n"
},
{
"code": null,
"e": 1523,
"s": 1506,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1547,
"s": 1523,
"text": "Or if it was an object:"
},
{
"code": null,
"e": 1613,
"s": 1547,
"text": "Create an object named carInfo and send it to the \nCar component:"
},
{
"code": null,
"e": 1959,
"s": 1613,
"text": "function Car(props) {\n return <h2>I am a { props.brand.model }!</h2>;\n}\n\nfunction Garage() {\n const carInfo = { name: \"Ford\", model: \"Mustang\" };\n return (\n <>\n <h1>Who lives in my garage?</h1>\n <Car brand={ carInfo } />\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Garage />);\n"
},
{
"code": null,
"e": 1976,
"s": 1959,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2066,
"s": 1976,
"text": "Note: React Props are read-only! You will get an error if you try to change their \nvalue."
},
{
"code": null,
"e": 2133,
"s": 2066,
"text": "Create a variable named name and pass it to the Message component."
},
{
"code": null,
"e": 2425,
"s": 2133,
"text": "function Person(props) {\n return <h2>I'm { props.name }!</h2>;\n}\n\nfunction Greeting() {\n const name = \"Jesse\"\n return (\n <>\n <h1>Hello!</h1>\n <Person name= name />\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Greeting />);\n"
},
{
"code": null,
"e": 2444,
"s": 2425,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2477,
"s": 2444,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2519,
"s": 2477,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2626,
"s": 2519,
"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": 2645,
"s": 2626,
"text": "help@w3schools.com"
}
] |
How do you overlap widgets/frames in Python tkinter?
|
There are three general ways through which we can align and position a particular widget in a Tkinter application. Let us suppose that we want to overlap two or more widgets or frames one on another, then we can use place() geometry manager. What place() geometry manager does is that it lines up the widget in rows and columns of a grid. We can certainly overlap the widget by providing the same coordinate in each.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Add a Frame
frame1= Frame(win, bg= "LightPink1")
# Add an optional Label widget
Label(frame1, text= "Welcome Folks!", font= ('Aerial 18 bold italic'), background= "white").pack(pady= 50)
frame1.place(x= 260, y= 50)
# Add a Button widget in second frame
ttk.Button(frame1, text= "Button").place(x= 260, y=50)
win.mainloop()
Executing the above code will display a window with a Label and a button widget inside the frame.
|
[
{
"code": null,
"e": 1479,
"s": 1062,
"text": "There are three general ways through which we can align and position a particular widget in a Tkinter application. Let us suppose that we want to overlap two or more widgets or frames one on another, then we can use place() geometry manager. What place() geometry manager does is that it lines up the widget in rows and columns of a grid. We can certainly overlap the widget by providing the same coordinate in each."
},
{
"code": null,
"e": 1997,
"s": 1479,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Add a Frame\nframe1= Frame(win, bg= \"LightPink1\")\n\n# Add an optional Label widget\nLabel(frame1, text= \"Welcome Folks!\", font= ('Aerial 18 bold italic'), background= \"white\").pack(pady= 50)\nframe1.place(x= 260, y= 50)\n\n# Add a Button widget in second frame\nttk.Button(frame1, text= \"Button\").place(x= 260, y=50)\nwin.mainloop()"
},
{
"code": null,
"e": 2095,
"s": 1997,
"text": "Executing the above code will display a window with a Label and a button widget inside the frame."
}
] |
PyTorch - Loading Data
|
PyTorch includes a package called torchvision which is used to load and prepare the dataset. It includes two basic functions namely Dataset and DataLoader which helps in transformation and loading of dataset.
Dataset is used to read and transform a datapoint from the given dataset. The basic syntax to implement is mentioned below −
trainset = torchvision.datasets.CIFAR10(root = './data', train = True,
download = True, transform = transform)
DataLoader is used to shuffle and batch data. It can be used to load the data in parallel with multiprocessing workers.
trainloader = torch.utils.data.DataLoader(trainset, batch_size = 4,
shuffle = True, num_workers = 2)
We use the Python package Panda to load the csv file. The original file has the following format: (image name, 68 landmarks - each landmark has a x, y coordinates).
landmarks_frame = pd.read_csv('faces/face_landmarks.csv')
n = 65
img_name = landmarks_frame.iloc[n, 0]
landmarks = landmarks_frame.iloc[n, 1:].as_matrix()
landmarks = landmarks.astype('float').reshape(-1, 2)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2468,
"s": 2259,
"text": "PyTorch includes a package called torchvision which is used to load and prepare the dataset. It includes two basic functions namely Dataset and DataLoader which helps in transformation and loading of dataset."
},
{
"code": null,
"e": 2593,
"s": 2468,
"text": "Dataset is used to read and transform a datapoint from the given dataset. The basic syntax to implement is mentioned below −"
},
{
"code": null,
"e": 2707,
"s": 2593,
"text": "trainset = torchvision.datasets.CIFAR10(root = './data', train = True,\n download = True, transform = transform)"
},
{
"code": null,
"e": 2827,
"s": 2707,
"text": "DataLoader is used to shuffle and batch data. It can be used to load the data in parallel with multiprocessing workers."
},
{
"code": null,
"e": 2931,
"s": 2827,
"text": "trainloader = torch.utils.data.DataLoader(trainset, batch_size = 4,\n shuffle = True, num_workers = 2)"
},
{
"code": null,
"e": 3096,
"s": 2931,
"text": "We use the Python package Panda to load the csv file. The original file has the following format: (image name, 68 landmarks - each landmark has a x, y coordinates)."
},
{
"code": null,
"e": 3305,
"s": 3096,
"text": "landmarks_frame = pd.read_csv('faces/face_landmarks.csv')\n\nn = 65\nimg_name = landmarks_frame.iloc[n, 0]\nlandmarks = landmarks_frame.iloc[n, 1:].as_matrix()\nlandmarks = landmarks.astype('float').reshape(-1, 2)"
},
{
"code": null,
"e": 3312,
"s": 3305,
"text": " Print"
},
{
"code": null,
"e": 3323,
"s": 3312,
"text": " Add Notes"
}
] |
How to set Spring Boot SetTimeZone - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show how to set/change the time zone in spring boot application.
JVM will take the default time zone as the server’s time zone. For example, if the server is running on IST, then the JVM takes the IST time as default.
In Spring boot we can quickly change/set this default timezone using java.util.TimeZone class like below.
package com.onlinetutorialspoint.SpringBoot_Custom_ErrorPage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.TimeZone;
@SpringBootApplication
public class Application {
@PostConstruct
public void init(){
// Setting Spring Boot SetTimeZone
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Run Application :
[INFO] --- spring-boot-maven-plugin:1.5.10.RELEASE:run (default-cli) @ SpringBoot_Custom_ErrorPage ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-17 20:43:21.353 INFO 10356 --- [ main] c.o.S.Application : Starting Application on DESKTOP-RN4SMHT with PID 10356 (E:\work\SpringBoot_Custom
_ErrorPage\target\classes started by Lenovo in E:\work\SpringBoot_Custom_ErrorPage)
2018-02-17 20:43:21.353 INFO 10356 --- [ main] c.o.S.Application : No active profile set, falling back to default profiles: default
2018-02-17 20:43:21.462 INFO 10356 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebA
pplicationContext@62f32a29: startup date [Sat Feb 17 20:43:21 IST 2018]; root of context hierarchy
2018-02-17 20:43:24.572 INFO 10356 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
You can see the updated time zone while running the application above.
Happy Learning 🙂
How to use Spring Boot Random Port
Spring Boot How to change the Tomcat to Jetty Server
How to set Spring boot favicon image
How to Set Spring Boot Custom Banner
MicroServices Spring Boot Eureka Server Example
Spring Boot Environment Properties reading based on activeprofile
How to Create own Spring Boot Error Page
Spring Boot Apache ActiveMq In Memory Example
How to change Spring Boot Tomcat Port Number
SSL Spring Boot HTTPs Enabling Example
External Apache ActiveMQ Spring Boot Example
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example
Spring Boot FileUpload Ajax Example
How to use Spring Boot Random Port
Spring Boot How to change the Tomcat to Jetty Server
How to set Spring boot favicon image
How to Set Spring Boot Custom Banner
MicroServices Spring Boot Eureka Server Example
Spring Boot Environment Properties reading based on activeprofile
How to Create own Spring Boot Error Page
Spring Boot Apache ActiveMq In Memory Example
How to change Spring Boot Tomcat Port Number
SSL Spring Boot HTTPs Enabling Example
External Apache ActiveMQ Spring Boot Example
Spring Boot MongoDB + Spring Data Example
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example
Spring Boot FileUpload Ajax Example
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 495,
"s": 398,
"text": "In this tutorial, I am going to show how to set/change the time zone in spring boot application."
},
{
"code": null,
"e": 648,
"s": 495,
"text": "JVM will take the default time zone as the server’s time zone. For example, if the server is running on IST, then the JVM takes the IST time as default."
},
{
"code": null,
"e": 754,
"s": 648,
"text": "In Spring boot we can quickly change/set this default timezone using java.util.TimeZone class like below."
},
{
"code": null,
"e": 1315,
"s": 754,
"text": "package com.onlinetutorialspoint.SpringBoot_Custom_ErrorPage;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\nimport javax.annotation.PostConstruct;\nimport java.util.Date;\nimport java.util.TimeZone;\n\n@SpringBootApplication\npublic class Application {\n @PostConstruct\n public void init(){\n // Setting Spring Boot SetTimeZone\n TimeZone.setDefault(TimeZone.getTimeZone(\"IST\"));\n }\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n"
},
{
"code": null,
"e": 1333,
"s": 1315,
"text": "Run Application :"
},
{
"code": null,
"e": 2592,
"s": 1333,
"text": "[INFO] --- spring-boot-maven-plugin:1.5.10.RELEASE:run (default-cli) @ SpringBoot_Custom_ErrorPage ---\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v1.5.10.RELEASE)\n\n2018-02-17 20:43:21.353 INFO 10356 --- [ main] c.o.S.Application : Starting Application on DESKTOP-RN4SMHT with PID 10356 (E:\\work\\SpringBoot_Custom\n_ErrorPage\\target\\classes started by Lenovo in E:\\work\\SpringBoot_Custom_ErrorPage)\n2018-02-17 20:43:21.353 INFO 10356 --- [ main] c.o.S.Application : No active profile set, falling back to default profiles: default\n2018-02-17 20:43:21.462 INFO 10356 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebA\npplicationContext@62f32a29: startup date [Sat Feb 17 20:43:21 IST 2018]; root of context hierarchy\n2018-02-17 20:43:24.572 INFO 10356 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)\n"
},
{
"code": null,
"e": 2663,
"s": 2592,
"text": "You can see the updated time zone while running the application above."
},
{
"code": null,
"e": 2680,
"s": 2663,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3330,
"s": 2680,
"text": "\nHow to use Spring Boot Random Port\nSpring Boot How to change the Tomcat to Jetty Server\nHow to set Spring boot favicon image\nHow to Set Spring Boot Custom Banner\nMicroServices Spring Boot Eureka Server Example\nSpring Boot Environment Properties reading based on activeprofile\nHow to Create own Spring Boot Error Page\nSpring Boot Apache ActiveMq In Memory Example\nHow to change Spring Boot Tomcat Port Number\nSSL Spring Boot HTTPs Enabling Example\nExternal Apache ActiveMQ Spring Boot Example\nSpring Boot MongoDB + Spring Data Example\nSpring Boot JPA Integration Example\nSpring Boot Hibernate Integration Example\nSpring Boot FileUpload Ajax Example\n"
},
{
"code": null,
"e": 3365,
"s": 3330,
"text": "How to use Spring Boot Random Port"
},
{
"code": null,
"e": 3418,
"s": 3365,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 3455,
"s": 3418,
"text": "How to set Spring boot favicon image"
},
{
"code": null,
"e": 3492,
"s": 3455,
"text": "How to Set Spring Boot Custom Banner"
},
{
"code": null,
"e": 3540,
"s": 3492,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 3606,
"s": 3540,
"text": "Spring Boot Environment Properties reading based on activeprofile"
},
{
"code": null,
"e": 3647,
"s": 3606,
"text": "How to Create own Spring Boot Error Page"
},
{
"code": null,
"e": 3693,
"s": 3647,
"text": "Spring Boot Apache ActiveMq In Memory Example"
},
{
"code": null,
"e": 3738,
"s": 3693,
"text": "How to change Spring Boot Tomcat Port Number"
},
{
"code": null,
"e": 3777,
"s": 3738,
"text": "SSL Spring Boot HTTPs Enabling Example"
},
{
"code": null,
"e": 3822,
"s": 3777,
"text": "External Apache ActiveMQ Spring Boot Example"
},
{
"code": null,
"e": 3864,
"s": 3822,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 3900,
"s": 3864,
"text": "Spring Boot JPA Integration Example"
},
{
"code": null,
"e": 3942,
"s": 3900,
"text": "Spring Boot Hibernate Integration Example"
},
{
"code": null,
"e": 3978,
"s": 3942,
"text": "Spring Boot FileUpload Ajax Example"
},
{
"code": null,
"e": 3984,
"s": 3982,
"text": "Δ"
},
{
"code": null,
"e": 4011,
"s": 3984,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 4038,
"s": 4011,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 4072,
"s": 4038,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 4113,
"s": 4072,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 4158,
"s": 4113,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 4196,
"s": 4158,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 4230,
"s": 4196,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 4261,
"s": 4230,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 4295,
"s": 4261,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 4328,
"s": 4295,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 4361,
"s": 4328,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 4401,
"s": 4361,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 4426,
"s": 4401,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 4457,
"s": 4426,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 4481,
"s": 4457,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 4527,
"s": 4481,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 4550,
"s": 4527,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 4577,
"s": 4550,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 4623,
"s": 4577,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 4663,
"s": 4623,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 4692,
"s": 4663,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 4726,
"s": 4692,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 4756,
"s": 4726,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 4792,
"s": 4756,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 4825,
"s": 4792,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 4858,
"s": 4825,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 4902,
"s": 4858,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 4936,
"s": 4902,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 4968,
"s": 4936,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 4996,
"s": 4968,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 5027,
"s": 4996,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 5068,
"s": 5027,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 5102,
"s": 5068,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 5127,
"s": 5102,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 5161,
"s": 5127,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 5197,
"s": 5161,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 5243,
"s": 5197,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 5294,
"s": 5243,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 5336,
"s": 5294,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 5367,
"s": 5336,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 5390,
"s": 5367,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 5420,
"s": 5390,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 5450,
"s": 5420,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 5499,
"s": 5450,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 5533,
"s": 5499,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 5566,
"s": 5533,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 5595,
"s": 5566,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 5627,
"s": 5595,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 5664,
"s": 5627,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 5693,
"s": 5664,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 5722,
"s": 5693,
"text": " Spring Boot – MockMvc JUnit"
}
] |
How can Tensorflow and pre-trained model be used to continue training the model using Python?
|
Tensorflow and the pre-trained model can be used to continue training the model by using the ‘fit’ method and specifying the number of training steps. The validation data is used to fit the model.
Read More:
What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?
A neural network that contains at least one layer is known as a convolutional layer. We can use the Convolutional Neural Network to build learning model.
We will understand how to classify images of cats and dogs with the help of transfer learning from a pre-trained network. The intuition behind transfer learning for image classification is, if a model is trained on a large and general dataset, this model can be used to effectively serve as a generic model for the visual world. It would have learned the feature maps, which means the user won’t have to start from scratch by training a large model on a large dataset.
Read More:
How can a customized model be pre-trained?
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.
print("The model training continues")
fine_tune_epochs = 10
total_epochs = initial_epochs + fine_tune_epochs
print("The model is being fit to the data")
history_fine = model.fit(train_dataset,
epochs=total_epochs,
initial_epoch=history.epoch[-1],
validation_data=validation_dataset)
Code credit −https://www.tensorflow.org/tutorials/images/transfer_learning
The model training continues
The model is being fit to the data
Epoch 10/20
63/63 [==============================] - 85s 1s/step - loss: 0.1568 - accuracy: 0.9244 - val_loss: 0.0506 - val_accuracy: 0.9864
Epoch 11/20
63/63 [==============================] - 73s 1s/step - loss: 0.1433 - accuracy: 0.9419 - val_loss: 0.0429 - val_accuracy: 0.9851
Epoch 12/20
63/63 [==============================] - 72s 1s/step - loss: 0.0984 - accuracy: 0.9609 - val_loss: 0.0450 - val_accuracy: 0.9827
Epoch 13/20
63/63 [==============================] - 72s 1s/step - loss: 0.1130 - accuracy: 0.9567 - val_loss: 0.0377 - val_accuracy: 0.9876
Epoch 14/20
63/63 [==============================] - 72s 1s/step - loss: 0.0783 - accuracy: 0.9685 - val_loss: 0.0406 - val_accuracy: 0.9889
Epoch 15/20
63/63 [==============================] - 72s 1s/step - loss: 0.0740 - accuracy: 0.9697 - val_loss: 0.0365 - val_accuracy: 0.9839
Epoch 16/20
63/63 [==============================] - 72s 1s/step - loss: 0.0794 - accuracy: 0.9647 - val_loss: 0.0376 - val_accuracy: 0.9839
Epoch 17/20
63/63 [==============================] - 71s 1s/step - loss: 0.0744 - accuracy: 0.9710 - val_loss: 0.0318 - val_accuracy: 0.9913
Epoch 18/20
63/63 [==============================] - 72s 1s/step - loss: 0.0725 - accuracy: 0.9719 - val_loss: 0.0410 - val_accuracy: 0.9876
Epoch 19/20
63/63 [==============================] - 72s 1s/step - loss: 0.0761 - accuracy: 0.9684 - val_loss: 0.0331 - val_accuracy: 0.9889
Epoch 20/20
63/63 [==============================] - 71s 1s/step - loss: 0.0632 - accuracy: 0.9742 - val_loss: 0.0405 - val_accuracy: 0.9814
The model is fit to the data.
This is done using the ‘fit’ method.
The number of epochs used is initially 10.
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "Tensorflow and the pre-trained model can be used to continue training the model by using the ‘fit’ method and specifying the number of training steps. The validation data is used to fit the model."
},
{
"code": null,
"e": 1351,
"s": 1259,
"text": "Read More:\nWhat is TensorFlow and how Keras work with TensorFlow to create Neural Networks?"
},
{
"code": null,
"e": 1506,
"s": 1351,
"text": "A neural network that contains at least one layer is known as a convolutional layer. We can use the Convolutional Neural Network to build learning model. "
},
{
"code": null,
"e": 1975,
"s": 1506,
"text": "We will understand how to classify images of cats and dogs with the help of transfer learning from a pre-trained network. The intuition behind transfer learning for image classification is, if a model is trained on a large and general dataset, this model can be used to effectively serve as a generic model for the visual world. It would have learned the feature maps, which means the user won’t have to start from scratch by training a large model on a large dataset."
},
{
"code": null,
"e": 2029,
"s": 1975,
"text": "Read More:\nHow can a customized model be pre-trained?"
},
{
"code": null,
"e": 2299,
"s": 2029,
"text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook."
},
{
"code": null,
"e": 2591,
"s": 2299,
"text": "print(\"The model training continues\")\nfine_tune_epochs = 10\ntotal_epochs = initial_epochs + fine_tune_epochs\nprint(\"The model is being fit to the data\")\nhistory_fine = model.fit(train_dataset,\n epochs=total_epochs,\n initial_epoch=history.epoch[-1],\n validation_data=validation_dataset)"
},
{
"code": null,
"e": 2666,
"s": 2591,
"text": "Code credit −https://www.tensorflow.org/tutorials/images/transfer_learning"
},
{
"code": null,
"e": 4281,
"s": 2666,
"text": "The model training continues\nThe model is being fit to the data\nEpoch 10/20\n63/63 [==============================] - 85s 1s/step - loss: 0.1568 - accuracy: 0.9244 - val_loss: 0.0506 - val_accuracy: 0.9864\nEpoch 11/20\n63/63 [==============================] - 73s 1s/step - loss: 0.1433 - accuracy: 0.9419 - val_loss: 0.0429 - val_accuracy: 0.9851\nEpoch 12/20\n63/63 [==============================] - 72s 1s/step - loss: 0.0984 - accuracy: 0.9609 - val_loss: 0.0450 - val_accuracy: 0.9827\nEpoch 13/20\n63/63 [==============================] - 72s 1s/step - loss: 0.1130 - accuracy: 0.9567 - val_loss: 0.0377 - val_accuracy: 0.9876\nEpoch 14/20\n63/63 [==============================] - 72s 1s/step - loss: 0.0783 - accuracy: 0.9685 - val_loss: 0.0406 - val_accuracy: 0.9889\nEpoch 15/20\n63/63 [==============================] - 72s 1s/step - loss: 0.0740 - accuracy: 0.9697 - val_loss: 0.0365 - val_accuracy: 0.9839\nEpoch 16/20\n63/63 [==============================] - 72s 1s/step - loss: 0.0794 - accuracy: 0.9647 - val_loss: 0.0376 - val_accuracy: 0.9839\nEpoch 17/20\n63/63 [==============================] - 71s 1s/step - loss: 0.0744 - accuracy: 0.9710 - val_loss: 0.0318 - val_accuracy: 0.9913\nEpoch 18/20\n63/63 [==============================] - 72s 1s/step - loss: 0.0725 - accuracy: 0.9719 - val_loss: 0.0410 - val_accuracy: 0.9876\nEpoch 19/20\n63/63 [==============================] - 72s 1s/step - loss: 0.0761 - accuracy: 0.9684 - val_loss: 0.0331 - val_accuracy: 0.9889\nEpoch 20/20\n63/63 [==============================] - 71s 1s/step - loss: 0.0632 - accuracy: 0.9742 - val_loss: 0.0405 - val_accuracy: 0.9814"
},
{
"code": null,
"e": 4311,
"s": 4281,
"text": "The model is fit to the data."
},
{
"code": null,
"e": 4348,
"s": 4311,
"text": "This is done using the ‘fit’ method."
},
{
"code": null,
"e": 4391,
"s": 4348,
"text": "The number of epochs used is initially 10."
}
] |
Flatten a 2d numpy array into 1d array in Python
|
A 2d numpy array is an array of arrays. In this article we will see how to flatten it to get the elements as one dimensional arrays.
The flatten function in numpy is a direct way to convert the 2d array in to a 1D array.
Live Demo
import numpy as np
array2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]])
# printing initial arrays
print("Given array:\n",array2D)
# Using flatten()
res = array2D.flatten()
# Result
print("Flattened array:\n ", res)
Running the above code gives us the following result −
Given array:
[[31 12 43]
[21 9 16]
[ 0 9 0]]
Flattened array:
[31 12 43 21 9 16 0 9 0]
There is another function called ravel which will do a similar thing of flattening the 2D array into 1D.
Live Demo
import numpy as np
array2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]])
# printing initial arrays
print("Given array:\n",array2D)
# Using ravel
res = array2D.ravel()
# Result
print("Flattened array:\n ", res)
Running the above code gives us the following result −
Given array:
[[31 12 43]
[21 9 16]
[ 0 9 0]]
Flattened array:
[31 12 43 21 9 16 0 9 0]
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "A 2d numpy array is an array of arrays. In this article we will see how to flatten it to get the elements as one dimensional arrays."
},
{
"code": null,
"e": 1283,
"s": 1195,
"text": "The flatten function in numpy is a direct way to convert the 2d array in to a 1D array."
},
{
"code": null,
"e": 1294,
"s": 1283,
"text": " Live Demo"
},
{
"code": null,
"e": 1515,
"s": 1294,
"text": "import numpy as np\narray2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]])\n# printing initial arrays\nprint(\"Given array:\\n\",array2D)\n# Using flatten()\nres = array2D.flatten()\n# Result\nprint(\"Flattened array:\\n \", res)"
},
{
"code": null,
"e": 1570,
"s": 1515,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1657,
"s": 1570,
"text": "Given array:\n[[31 12 43]\n[21 9 16]\n[ 0 9 0]]\nFlattened array:\n[31 12 43 21 9 16 0 9 0]"
},
{
"code": null,
"e": 1762,
"s": 1657,
"text": "There is another function called ravel which will do a similar thing of flattening the 2D array into 1D."
},
{
"code": null,
"e": 1773,
"s": 1762,
"text": " Live Demo"
},
{
"code": null,
"e": 1988,
"s": 1773,
"text": "import numpy as np\narray2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]])\n# printing initial arrays\nprint(\"Given array:\\n\",array2D)\n# Using ravel\nres = array2D.ravel()\n# Result\nprint(\"Flattened array:\\n \", res)"
},
{
"code": null,
"e": 2043,
"s": 1988,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2130,
"s": 2043,
"text": "Given array:\n[[31 12 43]\n[21 9 16]\n[ 0 9 0]]\nFlattened array:\n[31 12 43 21 9 16 0 9 0]"
}
] |
Installing Multiple CUDA & cuDNN Versions in Ubuntu | by Mathanraj Sharma | Towards Data Science
|
Nowadays most of us use the CUDA toolkit to train deep learning models. But things get messy when we grow from PROJECT to PROJECTS. Yes, soon as we start to work on two or three deep learning projects we may end up with the need for different environments. Sometimes we may need different versions of CUDA and cuDNN for different projects.
If you are a person who only uses Python the Anaconda (conda package manager) will come in handy in such situations. But there are situations you need to be relay on C++ as well. One good example is when you try to use TensorRT to optimize your inference time. Recently I ended up in such a situation where I need to use a specific version of TensorRT which is not compatible with the CUDA version I have in my Ubuntu system. I struggled a bit and found a way to have multiple CUDA installation on the system.
First of all, you need to check whether your laptop/desktop has a NVIDIA GPU. Open your terminal and run the below command.
sudo lshw -C display
You will get a similar output and notice that VGA from NVIDIA is available.
Then we need to ensure that we have installed proper Nvidia Driver
sudo ubuntu-drivers devices
Listed are the available drivers that we can install. Some suggest it is good to install the latest “distro non-free” (proprietary) version. But I choose to install the recommended version by ubuntu. It is totally up to you.
# To install recommended sudo ubuntu-drivers autoinstall OR# To install specific distrosudo apt install nvidia-driver-[version number]
Once the driver installation finished, reboot your system and run this command to check whether the driver installed properly.
nvidia-smi
You can see the Nvidia configurations printed. Note, the CUDA version displayed on the top right corner is the driver version. Not the CUDA-toolkit version itself.
NOTE: You can repeat Step 03, 04 & 05 as many times as you need to install different versions of CUDA. But first, install the latest compatible version of CUDA Toolkit for the Nvidia driver you installed. If you start to install the CUDA Toolkit from the smaller version it will replace the driver.
The main intention of this article starts here. CUDA is a parallel computing platform developed by NVIDIA it will help us to train our models much faster than in CPUs. We can install a cuda-toolkit suitable for the Nvidia-driver through the apt manager. Since we are intended to install multiple versions it is good to install through deb (Debian) or tar installation method.
Go to the cuda-toolkit archive and click on the version you need to download. It will redirect you to the download page. Select the preferences as shown in the below image
Go to your Download directory then run the commands popped on the Cuda download page.
cd ~/Downloads
Instead of the last command to install Cuda,
sudo apt install cuda-[version]Eg: If you have downloaded cuda 11.2sudo apt install cuda-11.2
It will take a few minutes to download and install the cuda-toolkit.
cd /usr/localls
You will see cuda-11.2 directory listed there.
After installing the cuda-toolkit we need to install a suitable version of cuDNN libraries in order to use GPU for deep learning tasks. Actually, cuDNN stands for CUDA Deep Neural Network library is a GPU-accelerated library of primitives for deep neural networks. He will optimize our training and make it run in GPU using CUDA.
Since we installing multiple versions it is recommended to follow tar installation. If you install using deb or run file it will replace the existing cudnn installation.
So to install cudnn go to the download page and select the cudnn suitable for your CUDA version.
Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 11.1Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 11.0Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 10.2Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 10.1
Note: Since there is no cuDNN for CUDA 11.2 is listed we can use cuDNN for CUDA 11.1. Caution don’t go for any further down versions.
Download the tar file of the selected version
Once you download go to your Download directory and run the below commands,
Before issuing the following commands, you’ll need to replace x.x and v8.x.x.x with your specific CUDA and cuDNN versions and the package date you downloaded.
And M.m with the CUDA version you installed in the example it is 11.2
cd ~/Downloads [OR where you downloaded]tar -xzvf cudnn-x.x-linux-x64-v8.x.x.x.tgztar -xzvf cudnn-x.x-linux-aarch64sbsa-v8.x.x.x.tgzsudo cp cuda/include/cudnn*.h /usr/local/cuda-M.m/includesudo cp cuda/lib64/libcudnn* /usr/local/cuda-M.m/lib64sudo chmod a+r /usr/local/cuda-M.m/include/cudnn*.h /usr/local/cuda-M.m/lib64/libcudnn*
Once you have installed your CUDA versions, you will get something similar to this.
cd /usr/localls
As you can see I have installed “cuda-10.1”, “cuda-11”, “cuda-11.1”, “cuda-11.2”. And there is also another directory “cuda” which is installed default when I installed multiple CUDA versions. Now,
sudo gedit ~./bashrc
Copy and paste these lines
export PATH=/usr/local/cuda/bin${PATH:+:${PATH}}export LD_LIBRARY_PATH="/usr/local/cuda/lib64:/usr/local/cuda-10.1/lib64:/usr/local/cuda-11/lib64:/usr/local/cuda-11.1/lib64:/usr/local/cuda-11.2/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"#make sure you add your cuda-X.x lib64 paths
Save and close the editor. What it does is, when a specific version of CUDA library is required by a task it will simply search through all the paths listed here one by one and finds it.
Now all set reboot your computer and you can enjoy your multiple versions of CUDA & cuDNN.
|
[
{
"code": null,
"e": 512,
"s": 172,
"text": "Nowadays most of us use the CUDA toolkit to train deep learning models. But things get messy when we grow from PROJECT to PROJECTS. Yes, soon as we start to work on two or three deep learning projects we may end up with the need for different environments. Sometimes we may need different versions of CUDA and cuDNN for different projects."
},
{
"code": null,
"e": 1022,
"s": 512,
"text": "If you are a person who only uses Python the Anaconda (conda package manager) will come in handy in such situations. But there are situations you need to be relay on C++ as well. One good example is when you try to use TensorRT to optimize your inference time. Recently I ended up in such a situation where I need to use a specific version of TensorRT which is not compatible with the CUDA version I have in my Ubuntu system. I struggled a bit and found a way to have multiple CUDA installation on the system."
},
{
"code": null,
"e": 1146,
"s": 1022,
"text": "First of all, you need to check whether your laptop/desktop has a NVIDIA GPU. Open your terminal and run the below command."
},
{
"code": null,
"e": 1167,
"s": 1146,
"text": "sudo lshw -C display"
},
{
"code": null,
"e": 1243,
"s": 1167,
"text": "You will get a similar output and notice that VGA from NVIDIA is available."
},
{
"code": null,
"e": 1310,
"s": 1243,
"text": "Then we need to ensure that we have installed proper Nvidia Driver"
},
{
"code": null,
"e": 1338,
"s": 1310,
"text": "sudo ubuntu-drivers devices"
},
{
"code": null,
"e": 1563,
"s": 1338,
"text": "Listed are the available drivers that we can install. Some suggest it is good to install the latest “distro non-free” (proprietary) version. But I choose to install the recommended version by ubuntu. It is totally up to you."
},
{
"code": null,
"e": 1698,
"s": 1563,
"text": "# To install recommended sudo ubuntu-drivers autoinstall OR# To install specific distrosudo apt install nvidia-driver-[version number]"
},
{
"code": null,
"e": 1825,
"s": 1698,
"text": "Once the driver installation finished, reboot your system and run this command to check whether the driver installed properly."
},
{
"code": null,
"e": 1836,
"s": 1825,
"text": "nvidia-smi"
},
{
"code": null,
"e": 2000,
"s": 1836,
"text": "You can see the Nvidia configurations printed. Note, the CUDA version displayed on the top right corner is the driver version. Not the CUDA-toolkit version itself."
},
{
"code": null,
"e": 2299,
"s": 2000,
"text": "NOTE: You can repeat Step 03, 04 & 05 as many times as you need to install different versions of CUDA. But first, install the latest compatible version of CUDA Toolkit for the Nvidia driver you installed. If you start to install the CUDA Toolkit from the smaller version it will replace the driver."
},
{
"code": null,
"e": 2675,
"s": 2299,
"text": "The main intention of this article starts here. CUDA is a parallel computing platform developed by NVIDIA it will help us to train our models much faster than in CPUs. We can install a cuda-toolkit suitable for the Nvidia-driver through the apt manager. Since we are intended to install multiple versions it is good to install through deb (Debian) or tar installation method."
},
{
"code": null,
"e": 2847,
"s": 2675,
"text": "Go to the cuda-toolkit archive and click on the version you need to download. It will redirect you to the download page. Select the preferences as shown in the below image"
},
{
"code": null,
"e": 2933,
"s": 2847,
"text": "Go to your Download directory then run the commands popped on the Cuda download page."
},
{
"code": null,
"e": 2948,
"s": 2933,
"text": "cd ~/Downloads"
},
{
"code": null,
"e": 2993,
"s": 2948,
"text": "Instead of the last command to install Cuda,"
},
{
"code": null,
"e": 3087,
"s": 2993,
"text": "sudo apt install cuda-[version]Eg: If you have downloaded cuda 11.2sudo apt install cuda-11.2"
},
{
"code": null,
"e": 3156,
"s": 3087,
"text": "It will take a few minutes to download and install the cuda-toolkit."
},
{
"code": null,
"e": 3172,
"s": 3156,
"text": "cd /usr/localls"
},
{
"code": null,
"e": 3219,
"s": 3172,
"text": "You will see cuda-11.2 directory listed there."
},
{
"code": null,
"e": 3549,
"s": 3219,
"text": "After installing the cuda-toolkit we need to install a suitable version of cuDNN libraries in order to use GPU for deep learning tasks. Actually, cuDNN stands for CUDA Deep Neural Network library is a GPU-accelerated library of primitives for deep neural networks. He will optimize our training and make it run in GPU using CUDA."
},
{
"code": null,
"e": 3719,
"s": 3549,
"text": "Since we installing multiple versions it is recommended to follow tar installation. If you install using deb or run file it will replace the existing cudnn installation."
},
{
"code": null,
"e": 3816,
"s": 3719,
"text": "So to install cudnn go to the download page and select the cudnn suitable for your CUDA version."
},
{
"code": null,
"e": 4053,
"s": 3816,
"text": "Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 11.1Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 11.0Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 10.2Download cuDNN v8.0.4 (September 28th, 2020), for CUDA 10.1"
},
{
"code": null,
"e": 4187,
"s": 4053,
"text": "Note: Since there is no cuDNN for CUDA 11.2 is listed we can use cuDNN for CUDA 11.1. Caution don’t go for any further down versions."
},
{
"code": null,
"e": 4233,
"s": 4187,
"text": "Download the tar file of the selected version"
},
{
"code": null,
"e": 4309,
"s": 4233,
"text": "Once you download go to your Download directory and run the below commands,"
},
{
"code": null,
"e": 4468,
"s": 4309,
"text": "Before issuing the following commands, you’ll need to replace x.x and v8.x.x.x with your specific CUDA and cuDNN versions and the package date you downloaded."
},
{
"code": null,
"e": 4538,
"s": 4468,
"text": "And M.m with the CUDA version you installed in the example it is 11.2"
},
{
"code": null,
"e": 4869,
"s": 4538,
"text": "cd ~/Downloads [OR where you downloaded]tar -xzvf cudnn-x.x-linux-x64-v8.x.x.x.tgztar -xzvf cudnn-x.x-linux-aarch64sbsa-v8.x.x.x.tgzsudo cp cuda/include/cudnn*.h /usr/local/cuda-M.m/includesudo cp cuda/lib64/libcudnn* /usr/local/cuda-M.m/lib64sudo chmod a+r /usr/local/cuda-M.m/include/cudnn*.h /usr/local/cuda-M.m/lib64/libcudnn*"
},
{
"code": null,
"e": 4953,
"s": 4869,
"text": "Once you have installed your CUDA versions, you will get something similar to this."
},
{
"code": null,
"e": 4969,
"s": 4953,
"text": "cd /usr/localls"
},
{
"code": null,
"e": 5167,
"s": 4969,
"text": "As you can see I have installed “cuda-10.1”, “cuda-11”, “cuda-11.1”, “cuda-11.2”. And there is also another directory “cuda” which is installed default when I installed multiple CUDA versions. Now,"
},
{
"code": null,
"e": 5188,
"s": 5167,
"text": "sudo gedit ~./bashrc"
},
{
"code": null,
"e": 5215,
"s": 5188,
"text": "Copy and paste these lines"
},
{
"code": null,
"e": 5499,
"s": 5215,
"text": "export PATH=/usr/local/cuda/bin${PATH:+:${PATH}}export LD_LIBRARY_PATH=\"/usr/local/cuda/lib64:/usr/local/cuda-10.1/lib64:/usr/local/cuda-11/lib64:/usr/local/cuda-11.1/lib64:/usr/local/cuda-11.2/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\"#make sure you add your cuda-X.x lib64 paths"
},
{
"code": null,
"e": 5686,
"s": 5499,
"text": "Save and close the editor. What it does is, when a specific version of CUDA library is required by a task it will simply search through all the paths listed here one by one and finds it."
}
] |
How I Built My Own Dating App Algorithm | Towards Data Science
|
Almost every dating app on the market right now have some form of a dating algorithm. However, these algorithms are usually not publicly available for public scrutiny. Also, the companies behind them probably wouldn’t want their secret formula to be exposed to competitors. But, we can still try and figure out how a potential dating algorithm is made.
In the past, I have delved into this subject numerous times. I even built a simple dating app using machine learning clustering algorithms:
towardsdatascience.com
It was great exercise in using unsupervised machine learning and the resulting dating algorithm was not too bad! It was a great experience but I thought it could use some improvements.
In this article, I won’t be strictly using machine learning but instead will opt for a simpler approach using Data Science tools and some recommendation system techniques. The logic of this algorithm is simple — it will be based on the idea of the wisdom of the crowd. This means the algorithm will find users just like you, aggregate the interactions of those like-minded users, then finally recommend profiles you may like based on the like-minded users’ opinions and interactions.
I’ll walk you through how I created this dating algorithm using mainly Python and Pandas. But before I begin, I have to list several prerequisites and assumptions about this dating algorithm:
This dating algorithm is working under an already established platform. Meaning users and user interactions already exist.
This established platform onboards users with a quick and simple questionnaire. Similar to filling in questions on a dating profile.
The platform works similar to other popular dating apps with right and left swipes indicating likes between profiles.
Straight men and women will be the only users on this platform for now. Other preferences can potentially be added later.
And that’s it! We can now move on to the coding aspect and feel free to code-along if you wish to create your own dating algorithm!
Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!
Since our dating algorithm only works with an already established set of data, we’ll need to manufacture that data with random values. We could make more complex datasets that mimic real world dating profiles but that’s not necessary for now.
towardsdatascience.com
First, let’s import the following libraries:
import pandas as pdimport randomimport numpy as np
For this algorithm, there will be 3 data tables or DataFrames. One table for men, one table for women, and one table showing how they interacted. The tables for men and women will contain 5 columns representing the questions and answers from the “profile questionnaire” and their user IDs. The questions and answers will just be represented as a simple “Q1 to Q5” and the answers as “A to E”.
The ratings or interaction table will display 3 different values. These values represent the resulting interactions between an M and W user:
1 represents corresponding right swipes between two users resulting in a successful match.
0 represents a left swipe from either user resulting in no match.
“unseen” represents two users that have yet to see one another.
Now that we have data to play around with, we can continue to the fun part — building the dating algorithm. This dating algorithm will work in the following sequence:
Find an M user that hasn’t yet seen a lot of W profiles.Find other similar M users based on the chosen M user’s dating profile answers.Rank the similar M users from most to least similar.Include only the most similar M users. In our case it will just be the top 10 most similar.Get the top 10’s interactions with all the W users that our chosen M user hasn’t yet seen.Aggregate those interaction values from the top 10 in order to find the cumulative values.Use those cumulative values to predict the potential interaction between the unseen W users and our chosen M user.
Find an M user that hasn’t yet seen a lot of W profiles.
Find other similar M users based on the chosen M user’s dating profile answers.
Rank the similar M users from most to least similar.
Include only the most similar M users. In our case it will just be the top 10 most similar.
Get the top 10’s interactions with all the W users that our chosen M user hasn’t yet seen.
Aggregate those interaction values from the top 10 in order to find the cumulative values.
Use those cumulative values to predict the potential interaction between the unseen W users and our chosen M user.
There are additional steps afterwards such as sorting the cumulative values for each W user but that isn’t too important right now. The above sequence will be the blueprint for our matchmaking algorithm. Also, this sequence can also be applied for W users as well.
Now that we have the blueprint, let’s get to coding. In order to find the M user with the most “unseen” values in the ratings table, run this code:
m_user = ratings.T.apply(pd.Series.value_counts).T.sort_values( by="unseen", ascending=False).iloc[0]
Next, we’ll find and save a list of all the W users that this M user has yet to see:
m_nrate = ratings.T[ratings.T[m_user.name]=="unseen"].index
Now we can find all the similar M users by using the variables we created above. But first, we’ll have to do some light data preprocessing. We’ll need to categorize the answers in the Men’s Table so we can use their corresponding numerical values to calculate correlation:
n_men = men.apply(lambda x: x.cat.codes)
Resulting in the transformed DataFrame:
With this table, we can calculate the correlation scores with Pandas.
m_sim = n_men.T.corrwith( n_men.T[m_user.name]).sort_values( ascending=False)[1:11]
Running this code will result in the table on the left showing the most similar users to our chosen M user. The most similar users have a correlation score of 1.0 and the least similar users will have a score of 0. By default, Pandas uses the “Pearson” method to calculate correlation.
With the Top 10 similar users known, let’s find their interaction values for each of the W users our chosen M user hasn’t yet seen:
msim_rate = ratings.loc[list(m_sim.index)][m_nrate]
So it appears that even with the top 10 similar users, there are still some “unseen” values. This can be a future issue that can be potentially resolved by adding more similar users than just the top 10. However, for the purposes of this project, we will continue with what we have.
We can now aggregate these values to find what the overall value was for each W user. To do so, there are multiple ways we can calculate the cumulative values. Let’s keep it simple and just find the average, frequency, and median results:
# Man predictionsm_predict = pd.DataFrame()# Replacing the unseen values with NaNs for calculation purposesmsim_rate.replace( "unseen", np.nan, inplace=True)# Averagem_predict['avg'] = msim_rate.mean()# Frequencym_predict['freq'] = msim_rate.mode().T[0]# Medianm_predict['median'] = msim_rate.median()
On the left, you should see the resulting DF of values from the cumulation of the Top 10’s interaction values.
From here, we can choose which calculation best represents the overall sentiment from the top 10 similar users — the average, frequency, or median?
The average appears to be the best because of its wide range of values. We can use this to sort the W users to find which ones were the most consistently liked amongst the top 10. It can also serve as a match/compatibility score for our chosen M user. For example:
Let’s say you were the chosen user. If the value is 0.80, then there is an 80% chance you will like this profile because 8 out of the 10 users most similar to you liked this profile.
With the decision to use the average value, we now have our finished dating algorithm! In this instance, we only applied the algorithm to an existing user. But, how would we apply it to a new user on the platform?
Now that we have laid out the code for our dating algorithm, let’s apply it to a new user! This new user will be onboarded with the same questionnaire as the existing users. So we are basically just adding them to the existing dataset.
I’ve already constructed a function that uses the code and sequence of our recently created dating algorithm:
Given that our new user will be introduced to the platform by answering a few questions, we’ll just use random answers for them. Afterwards, we’ll run the above function and then our new user will be able to see which users they will most likely match with:
ans = ['A', 'B', 'C', 'D', 'E']# Randomly picking answersnew_man_answers = random.choices(ans, k=5)# Running the functionrecs = matchMan( men, women, ratings, new_man_answers, num_sim=10)# Finding the top 20 most potentially compatiblerecs[:20]
Running the function above and using the same tables as before, the new user will be presented with these recommended W users sorted by the average score. We can see the score decrease further down the list, which means the algorithm is working.
Now these W users can be shown with the scores to inform the new M user of their potential match compatibility. Or, they can be shown without the scores and the new user will just see these profiles as their top recommended matches. The decision of how these W users are presented is ultimately up to the people in charge of the dating platform.
We have successfully constructed a simple dating algorithm without the use of any machine learning models. However, there are steps we can take to potentially improve this dating algorithm. For instance, we’ll need to validate our results by comparing predicted scores with the actual scores for the existing users. From there we can make changes to improve the algorithm such as including more similar users than just the top 10 or even weighting the interaction values.
I’ve completed some basic validation processes in my code on Github — see below. However, any validation done here will be pointless because our existing datasets are all random.
Another potential issue to be aware of is the scale. What happens when the amount of users on the platform (or even the onboarding questions) increases to a point where the algorithm begins to slow down? How do we compensate for that? These are things that need to be considered as we improve upon this algorithm.
All in all, building this algorithm was a great exercise in coding and utilizing some recommendation system techniques. If you wish to continue improving upon this existing algorithm, feel free to check out my code on Github. I hope you enjoyed this article and check out my other articles if you wish!
|
[
{
"code": null,
"e": 525,
"s": 172,
"text": "Almost every dating app on the market right now have some form of a dating algorithm. However, these algorithms are usually not publicly available for public scrutiny. Also, the companies behind them probably wouldn’t want their secret formula to be exposed to competitors. But, we can still try and figure out how a potential dating algorithm is made."
},
{
"code": null,
"e": 665,
"s": 525,
"text": "In the past, I have delved into this subject numerous times. I even built a simple dating app using machine learning clustering algorithms:"
},
{
"code": null,
"e": 688,
"s": 665,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 873,
"s": 688,
"text": "It was great exercise in using unsupervised machine learning and the resulting dating algorithm was not too bad! It was a great experience but I thought it could use some improvements."
},
{
"code": null,
"e": 1357,
"s": 873,
"text": "In this article, I won’t be strictly using machine learning but instead will opt for a simpler approach using Data Science tools and some recommendation system techniques. The logic of this algorithm is simple — it will be based on the idea of the wisdom of the crowd. This means the algorithm will find users just like you, aggregate the interactions of those like-minded users, then finally recommend profiles you may like based on the like-minded users’ opinions and interactions."
},
{
"code": null,
"e": 1549,
"s": 1357,
"text": "I’ll walk you through how I created this dating algorithm using mainly Python and Pandas. But before I begin, I have to list several prerequisites and assumptions about this dating algorithm:"
},
{
"code": null,
"e": 1672,
"s": 1549,
"text": "This dating algorithm is working under an already established platform. Meaning users and user interactions already exist."
},
{
"code": null,
"e": 1805,
"s": 1672,
"text": "This established platform onboards users with a quick and simple questionnaire. Similar to filling in questions on a dating profile."
},
{
"code": null,
"e": 1923,
"s": 1805,
"text": "The platform works similar to other popular dating apps with right and left swipes indicating likes between profiles."
},
{
"code": null,
"e": 2045,
"s": 1923,
"text": "Straight men and women will be the only users on this platform for now. Other preferences can potentially be added later."
},
{
"code": null,
"e": 2177,
"s": 2045,
"text": "And that’s it! We can now move on to the coding aspect and feel free to code-along if you wish to create your own dating algorithm!"
},
{
"code": null,
"e": 2342,
"s": 2177,
"text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!"
},
{
"code": null,
"e": 2585,
"s": 2342,
"text": "Since our dating algorithm only works with an already established set of data, we’ll need to manufacture that data with random values. We could make more complex datasets that mimic real world dating profiles but that’s not necessary for now."
},
{
"code": null,
"e": 2608,
"s": 2585,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2653,
"s": 2608,
"text": "First, let’s import the following libraries:"
},
{
"code": null,
"e": 2704,
"s": 2653,
"text": "import pandas as pdimport randomimport numpy as np"
},
{
"code": null,
"e": 3097,
"s": 2704,
"text": "For this algorithm, there will be 3 data tables or DataFrames. One table for men, one table for women, and one table showing how they interacted. The tables for men and women will contain 5 columns representing the questions and answers from the “profile questionnaire” and their user IDs. The questions and answers will just be represented as a simple “Q1 to Q5” and the answers as “A to E”."
},
{
"code": null,
"e": 3238,
"s": 3097,
"text": "The ratings or interaction table will display 3 different values. These values represent the resulting interactions between an M and W user:"
},
{
"code": null,
"e": 3329,
"s": 3238,
"text": "1 represents corresponding right swipes between two users resulting in a successful match."
},
{
"code": null,
"e": 3395,
"s": 3329,
"text": "0 represents a left swipe from either user resulting in no match."
},
{
"code": null,
"e": 3459,
"s": 3395,
"text": "“unseen” represents two users that have yet to see one another."
},
{
"code": null,
"e": 3626,
"s": 3459,
"text": "Now that we have data to play around with, we can continue to the fun part — building the dating algorithm. This dating algorithm will work in the following sequence:"
},
{
"code": null,
"e": 4199,
"s": 3626,
"text": "Find an M user that hasn’t yet seen a lot of W profiles.Find other similar M users based on the chosen M user’s dating profile answers.Rank the similar M users from most to least similar.Include only the most similar M users. In our case it will just be the top 10 most similar.Get the top 10’s interactions with all the W users that our chosen M user hasn’t yet seen.Aggregate those interaction values from the top 10 in order to find the cumulative values.Use those cumulative values to predict the potential interaction between the unseen W users and our chosen M user."
},
{
"code": null,
"e": 4256,
"s": 4199,
"text": "Find an M user that hasn’t yet seen a lot of W profiles."
},
{
"code": null,
"e": 4336,
"s": 4256,
"text": "Find other similar M users based on the chosen M user’s dating profile answers."
},
{
"code": null,
"e": 4389,
"s": 4336,
"text": "Rank the similar M users from most to least similar."
},
{
"code": null,
"e": 4481,
"s": 4389,
"text": "Include only the most similar M users. In our case it will just be the top 10 most similar."
},
{
"code": null,
"e": 4572,
"s": 4481,
"text": "Get the top 10’s interactions with all the W users that our chosen M user hasn’t yet seen."
},
{
"code": null,
"e": 4663,
"s": 4572,
"text": "Aggregate those interaction values from the top 10 in order to find the cumulative values."
},
{
"code": null,
"e": 4778,
"s": 4663,
"text": "Use those cumulative values to predict the potential interaction between the unseen W users and our chosen M user."
},
{
"code": null,
"e": 5043,
"s": 4778,
"text": "There are additional steps afterwards such as sorting the cumulative values for each W user but that isn’t too important right now. The above sequence will be the blueprint for our matchmaking algorithm. Also, this sequence can also be applied for W users as well."
},
{
"code": null,
"e": 5191,
"s": 5043,
"text": "Now that we have the blueprint, let’s get to coding. In order to find the M user with the most “unseen” values in the ratings table, run this code:"
},
{
"code": null,
"e": 5300,
"s": 5191,
"text": "m_user = ratings.T.apply(pd.Series.value_counts).T.sort_values( by=\"unseen\", ascending=False).iloc[0]"
},
{
"code": null,
"e": 5385,
"s": 5300,
"text": "Next, we’ll find and save a list of all the W users that this M user has yet to see:"
},
{
"code": null,
"e": 5445,
"s": 5385,
"text": "m_nrate = ratings.T[ratings.T[m_user.name]==\"unseen\"].index"
},
{
"code": null,
"e": 5718,
"s": 5445,
"text": "Now we can find all the similar M users by using the variables we created above. But first, we’ll have to do some light data preprocessing. We’ll need to categorize the answers in the Men’s Table so we can use their corresponding numerical values to calculate correlation:"
},
{
"code": null,
"e": 5759,
"s": 5718,
"text": "n_men = men.apply(lambda x: x.cat.codes)"
},
{
"code": null,
"e": 5799,
"s": 5759,
"text": "Resulting in the transformed DataFrame:"
},
{
"code": null,
"e": 5869,
"s": 5799,
"text": "With this table, we can calculate the correlation scores with Pandas."
},
{
"code": null,
"e": 5959,
"s": 5869,
"text": "m_sim = n_men.T.corrwith( n_men.T[m_user.name]).sort_values( ascending=False)[1:11]"
},
{
"code": null,
"e": 6245,
"s": 5959,
"text": "Running this code will result in the table on the left showing the most similar users to our chosen M user. The most similar users have a correlation score of 1.0 and the least similar users will have a score of 0. By default, Pandas uses the “Pearson” method to calculate correlation."
},
{
"code": null,
"e": 6377,
"s": 6245,
"text": "With the Top 10 similar users known, let’s find their interaction values for each of the W users our chosen M user hasn’t yet seen:"
},
{
"code": null,
"e": 6429,
"s": 6377,
"text": "msim_rate = ratings.loc[list(m_sim.index)][m_nrate]"
},
{
"code": null,
"e": 6712,
"s": 6429,
"text": "So it appears that even with the top 10 similar users, there are still some “unseen” values. This can be a future issue that can be potentially resolved by adding more similar users than just the top 10. However, for the purposes of this project, we will continue with what we have."
},
{
"code": null,
"e": 6951,
"s": 6712,
"text": "We can now aggregate these values to find what the overall value was for each W user. To do so, there are multiple ways we can calculate the cumulative values. Let’s keep it simple and just find the average, frequency, and median results:"
},
{
"code": null,
"e": 7264,
"s": 6951,
"text": "# Man predictionsm_predict = pd.DataFrame()# Replacing the unseen values with NaNs for calculation purposesmsim_rate.replace( \"unseen\", np.nan, inplace=True)# Averagem_predict['avg'] = msim_rate.mean()# Frequencym_predict['freq'] = msim_rate.mode().T[0]# Medianm_predict['median'] = msim_rate.median()"
},
{
"code": null,
"e": 7375,
"s": 7264,
"text": "On the left, you should see the resulting DF of values from the cumulation of the Top 10’s interaction values."
},
{
"code": null,
"e": 7523,
"s": 7375,
"text": "From here, we can choose which calculation best represents the overall sentiment from the top 10 similar users — the average, frequency, or median?"
},
{
"code": null,
"e": 7788,
"s": 7523,
"text": "The average appears to be the best because of its wide range of values. We can use this to sort the W users to find which ones were the most consistently liked amongst the top 10. It can also serve as a match/compatibility score for our chosen M user. For example:"
},
{
"code": null,
"e": 7971,
"s": 7788,
"text": "Let’s say you were the chosen user. If the value is 0.80, then there is an 80% chance you will like this profile because 8 out of the 10 users most similar to you liked this profile."
},
{
"code": null,
"e": 8185,
"s": 7971,
"text": "With the decision to use the average value, we now have our finished dating algorithm! In this instance, we only applied the algorithm to an existing user. But, how would we apply it to a new user on the platform?"
},
{
"code": null,
"e": 8421,
"s": 8185,
"text": "Now that we have laid out the code for our dating algorithm, let’s apply it to a new user! This new user will be onboarded with the same questionnaire as the existing users. So we are basically just adding them to the existing dataset."
},
{
"code": null,
"e": 8531,
"s": 8421,
"text": "I’ve already constructed a function that uses the code and sequence of our recently created dating algorithm:"
},
{
"code": null,
"e": 8789,
"s": 8531,
"text": "Given that our new user will be introduced to the platform by answering a few questions, we’ll just use random answers for them. Afterwards, we’ll run the above function and then our new user will be able to see which users they will most likely match with:"
},
{
"code": null,
"e": 9053,
"s": 8789,
"text": "ans = ['A', 'B', 'C', 'D', 'E']# Randomly picking answersnew_man_answers = random.choices(ans, k=5)# Running the functionrecs = matchMan( men, women, ratings, new_man_answers, num_sim=10)# Finding the top 20 most potentially compatiblerecs[:20]"
},
{
"code": null,
"e": 9299,
"s": 9053,
"text": "Running the function above and using the same tables as before, the new user will be presented with these recommended W users sorted by the average score. We can see the score decrease further down the list, which means the algorithm is working."
},
{
"code": null,
"e": 9645,
"s": 9299,
"text": "Now these W users can be shown with the scores to inform the new M user of their potential match compatibility. Or, they can be shown without the scores and the new user will just see these profiles as their top recommended matches. The decision of how these W users are presented is ultimately up to the people in charge of the dating platform."
},
{
"code": null,
"e": 10117,
"s": 9645,
"text": "We have successfully constructed a simple dating algorithm without the use of any machine learning models. However, there are steps we can take to potentially improve this dating algorithm. For instance, we’ll need to validate our results by comparing predicted scores with the actual scores for the existing users. From there we can make changes to improve the algorithm such as including more similar users than just the top 10 or even weighting the interaction values."
},
{
"code": null,
"e": 10296,
"s": 10117,
"text": "I’ve completed some basic validation processes in my code on Github — see below. However, any validation done here will be pointless because our existing datasets are all random."
},
{
"code": null,
"e": 10610,
"s": 10296,
"text": "Another potential issue to be aware of is the scale. What happens when the amount of users on the platform (or even the onboarding questions) increases to a point where the algorithm begins to slow down? How do we compensate for that? These are things that need to be considered as we improve upon this algorithm."
}
] |
How to check if a string contains a specific sub string?
|
To check if a string contains a specific substring, the ‘strlen’ and ‘strpos’ functions can be used. The ‘strlen’ gives the entire length of the string. The function ‘strpos’ finds the position wherein the substring occurs first in the string.
Live Demo
<?php
$str_1 = "thisisasample";
$str_2 = "asample";
if (strpos($str_1, $str_2) >= 0 && strpos($str_1, $str_2) < strlen($str_1))
echo("The substring is present within the string.");
else
echo("The substring is not present within the string.");
?>
The substring is present within the string.
Two strings are defined and the position of the second string in the first string is checked with the help of the ‘strpos’ function and compared with the length of the first string. Relevant message is displayed on the console.
|
[
{
"code": null,
"e": 1306,
"s": 1062,
"text": "To check if a string contains a specific substring, the ‘strlen’ and ‘strpos’ functions can be used. The ‘strlen’ gives the entire length of the string. The function ‘strpos’ finds the position wherein the substring occurs first in the string."
},
{
"code": null,
"e": 1317,
"s": 1306,
"text": " Live Demo"
},
{
"code": null,
"e": 1587,
"s": 1317,
"text": "<?php\n $str_1 = \"thisisasample\";\n $str_2 = \"asample\";\n if (strpos($str_1, $str_2) >= 0 && strpos($str_1, $str_2) < strlen($str_1))\n echo(\"The substring is present within the string.\");\n else\n echo(\"The substring is not present within the string.\");\n?>"
},
{
"code": null,
"e": 1631,
"s": 1587,
"text": "The substring is present within the string."
},
{
"code": null,
"e": 1859,
"s": 1631,
"text": "Two strings are defined and the position of the second string in the first string is checked with the help of the ‘strpos’ function and compared with the length of the first string. Relevant message is displayed on the console."
}
] |
Adjust gap size for CSS Grid
|
To adjust the gap size, use grid-column-gap, grid-row-gap or grid-gap property in CSS.
Set gap between Grid columns with CSS. You can try to run the following code to implement the grid-column-gap property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: green;
grid-template-columns: auto auto;
padding: 20px;
grid-column-gap: 20px;
}
.ele {
background-color: orange;
border: 2px solid gray;
padding: 35px;
font-size: 30px;
text-align: center;
}
</style>
</head>
<body>
<h1>Game Board</h1>
<div class = "container">
<div class = "ele">1</div>
<div class = "ele">2</div>
<div class = "ele">3</div>
<div class = "ele">4</div>
<div class = "ele">5</div>
<div class = "ele">6</div>
</div>
</body>
</html>
Set gap between Grid rows with CSS. You can try to run the following code to implement the grid-row-gap property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: green;
grid-template-columns: auto auto;
padding: 20px;
grid-column-gap: 20px;
grid-row-gap: 20px;
}
.ele {
background-color: orange;
border: 2px solid gray;
padding: 35px;
font-size: 30px;
text-align: center;
}
</style>
</head>
<body>
<h1>Game Board</h1>
<div class = "container">
<div class = "ele">1</div>
<div class = "ele">2</div>
<div class = "ele">3</div>
<div class = "ele">4</div>
<div class = "ele">5</div>
<div class = "ele">6</div>
</div>
</body>
</html>
Set gap between Grid rows and columns with CSS. You can try to run the following code to implement the grid-gap property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: green;
grid-template-columns: auto auto;
padding: 20px;
grid-gap: 20px 20px;
}
.ele {
background-color: orange;
border: 2px solid gray;
padding: 35px;
font-size: 30px;
text-align: center;
}
</style>
</head>
<body>
<h1>Game Board</h1>
<div class = "container">
<div class = "ele">1</div>
<div class = "ele">2</div>
<div class = "ele">3</div>
<div class = "ele">4</div>
<div class = "ele">5</div>
<div class = "ele">6</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To adjust the gap size, use grid-column-gap, grid-row-gap or grid-gap property in CSS."
},
{
"code": null,
"e": 1269,
"s": 1149,
"text": "Set gap between Grid columns with CSS. You can try to run the following code to implement the grid-column-gap property."
},
{
"code": null,
"e": 1279,
"s": 1269,
"text": "Live Demo"
},
{
"code": null,
"e": 2062,
"s": 1279,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .container {\n display: grid;\n background-color: green;\n grid-template-columns: auto auto;\n padding: 20px;\n grid-column-gap: 20px;\n }\n .ele {\n background-color: orange;\n border: 2px solid gray;\n padding: 35px;\n font-size: 30px;\n text-align: center;\n }\n </style>\n </head>\n <body>\n <h1>Game Board</h1>\n <div class = \"container\">\n <div class = \"ele\">1</div>\n <div class = \"ele\">2</div>\n <div class = \"ele\">3</div>\n <div class = \"ele\">4</div>\n <div class = \"ele\">5</div>\n <div class = \"ele\">6</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 2176,
"s": 2062,
"text": "Set gap between Grid rows with CSS. You can try to run the following code to implement the grid-row-gap property."
},
{
"code": null,
"e": 2186,
"s": 2176,
"text": "Live Demo"
},
{
"code": null,
"e": 3001,
"s": 2186,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .container {\n display: grid;\n background-color: green;\n grid-template-columns: auto auto;\n padding: 20px;\n grid-column-gap: 20px;\n grid-row-gap: 20px;\n }\n .ele {\n background-color: orange;\n border: 2px solid gray;\n padding: 35px;\n font-size: 30px;\n text-align: center;\n }\n </style>\n </head>\n <body>\n <h1>Game Board</h1>\n <div class = \"container\">\n <div class = \"ele\">1</div>\n <div class = \"ele\">2</div>\n <div class = \"ele\">3</div>\n <div class = \"ele\">4</div>\n <div class = \"ele\">5</div>\n <div class = \"ele\">6</div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3123,
"s": 3001,
"text": "Set gap between Grid rows and columns with CSS. You can try to run the following code to implement the grid-gap property."
},
{
"code": null,
"e": 3133,
"s": 3123,
"text": "Live Demo"
},
{
"code": null,
"e": 3914,
"s": 3133,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .container {\n display: grid;\n background-color: green;\n grid-template-columns: auto auto;\n padding: 20px;\n grid-gap: 20px 20px;\n }\n .ele {\n background-color: orange;\n border: 2px solid gray;\n padding: 35px;\n font-size: 30px;\n text-align: center;\n }\n </style>\n </head>\n <body>\n <h1>Game Board</h1>\n <div class = \"container\">\n <div class = \"ele\">1</div>\n <div class = \"ele\">2</div>\n <div class = \"ele\">3</div>\n <div class = \"ele\">4</div>\n <div class = \"ele\">5</div>\n <div class = \"ele\">6</div>\n </div>\n </body>\n</html>"
}
] |
Visualizing the composition two of graph using networkx - GeeksforGeeks
|
24 Jan, 2021
In this article, we are going to see how to visualize the composition two of the graph using networkx. If we are given two graphs A and B then their composition can be found by performing union operation on node-set and edge-set of A and B.
Simply if an edge is contained between any two vertices in any of the initial graphs it will be contained in the composition of those graphs.
Example:
Initial Graph G:
G
Initial Graph H:
H
Result of Composition of G and H:
Composition(G,H)
Explanation: If we name nodes in both graphs G and H using integers then we will clearly observe that node and edge set of G will be superset of H and hence their union gives G in return.
Example 2:
Initial Graph G:
G
Initial Graph H:
H
Result of Composition of G and H:
R
Explanation: We can see that all the edges which are in graph G are present in graph H except the node between first and third node from right therefore doing composition of G and H adds all edges from G and H into the result.
Important points about Compose function:
H attributes take precedent over G attributes.
The graph returned is of the same type as G.
G and H should either be both directed or both undirected.
G and H must both be graphs or multigraphs
Realizing Composition using Python :
We will use networkx.compose() function for our task to do composition of 2 graphs.
Syntax: compose(G, H)
G: It is a networkx Graph object which is passed as an argument to compose function.
H: It is also an networkx Graph object which is passed as an argument to compose function.
Result of compose function will be union of edge and vertices set of G and H.
Approach:
We will import networkx with an alias nx.
Create a sample graph object G using path_graph() function.
Create second sample graph object H using path_graph() function.
We will then call compose function passing G as an argument.
We will capture the object returned by compose function in another object R.
We will then call draw() function passing R as an argument which will display the complement graph.
Code:
Python3
# importing networkx module import networkx as nx # creating sample graph object G = nx.path_graph(7) # creating sample graph object H = nx.path_graph(3) # compose of G and H saving in RR = nx.compose(G,H) # calling draw() to visualize the complement graph nx.draw(R)
Output:
OUTPUT
Python Networx-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24533,
"s": 24292,
"text": "In this article, we are going to see how to visualize the composition two of the graph using networkx. If we are given two graphs A and B then their composition can be found by performing union operation on node-set and edge-set of A and B."
},
{
"code": null,
"e": 24675,
"s": 24533,
"text": "Simply if an edge is contained between any two vertices in any of the initial graphs it will be contained in the composition of those graphs."
},
{
"code": null,
"e": 24684,
"s": 24675,
"text": "Example:"
},
{
"code": null,
"e": 24701,
"s": 24684,
"text": "Initial Graph G:"
},
{
"code": null,
"e": 24703,
"s": 24701,
"text": "G"
},
{
"code": null,
"e": 24720,
"s": 24703,
"text": "Initial Graph H:"
},
{
"code": null,
"e": 24722,
"s": 24720,
"text": "H"
},
{
"code": null,
"e": 24756,
"s": 24722,
"text": "Result of Composition of G and H:"
},
{
"code": null,
"e": 24773,
"s": 24756,
"text": "Composition(G,H)"
},
{
"code": null,
"e": 24961,
"s": 24773,
"text": "Explanation: If we name nodes in both graphs G and H using integers then we will clearly observe that node and edge set of G will be superset of H and hence their union gives G in return."
},
{
"code": null,
"e": 24972,
"s": 24961,
"text": "Example 2:"
},
{
"code": null,
"e": 24989,
"s": 24972,
"text": "Initial Graph G:"
},
{
"code": null,
"e": 24991,
"s": 24989,
"text": "G"
},
{
"code": null,
"e": 25008,
"s": 24991,
"text": "Initial Graph H:"
},
{
"code": null,
"e": 25010,
"s": 25008,
"text": "H"
},
{
"code": null,
"e": 25044,
"s": 25010,
"text": "Result of Composition of G and H:"
},
{
"code": null,
"e": 25046,
"s": 25044,
"text": "R"
},
{
"code": null,
"e": 25273,
"s": 25046,
"text": "Explanation: We can see that all the edges which are in graph G are present in graph H except the node between first and third node from right therefore doing composition of G and H adds all edges from G and H into the result."
},
{
"code": null,
"e": 25314,
"s": 25273,
"text": "Important points about Compose function:"
},
{
"code": null,
"e": 25361,
"s": 25314,
"text": "H attributes take precedent over G attributes."
},
{
"code": null,
"e": 25406,
"s": 25361,
"text": "The graph returned is of the same type as G."
},
{
"code": null,
"e": 25465,
"s": 25406,
"text": "G and H should either be both directed or both undirected."
},
{
"code": null,
"e": 25508,
"s": 25465,
"text": "G and H must both be graphs or multigraphs"
},
{
"code": null,
"e": 25545,
"s": 25508,
"text": "Realizing Composition using Python :"
},
{
"code": null,
"e": 25629,
"s": 25545,
"text": "We will use networkx.compose() function for our task to do composition of 2 graphs."
},
{
"code": null,
"e": 25651,
"s": 25629,
"text": "Syntax: compose(G, H)"
},
{
"code": null,
"e": 25736,
"s": 25651,
"text": "G: It is a networkx Graph object which is passed as an argument to compose function."
},
{
"code": null,
"e": 25827,
"s": 25736,
"text": "H: It is also an networkx Graph object which is passed as an argument to compose function."
},
{
"code": null,
"e": 25905,
"s": 25827,
"text": "Result of compose function will be union of edge and vertices set of G and H."
},
{
"code": null,
"e": 25915,
"s": 25905,
"text": "Approach:"
},
{
"code": null,
"e": 25957,
"s": 25915,
"text": "We will import networkx with an alias nx."
},
{
"code": null,
"e": 26017,
"s": 25957,
"text": "Create a sample graph object G using path_graph() function."
},
{
"code": null,
"e": 26082,
"s": 26017,
"text": "Create second sample graph object H using path_graph() function."
},
{
"code": null,
"e": 26143,
"s": 26082,
"text": "We will then call compose function passing G as an argument."
},
{
"code": null,
"e": 26220,
"s": 26143,
"text": "We will capture the object returned by compose function in another object R."
},
{
"code": null,
"e": 26320,
"s": 26220,
"text": "We will then call draw() function passing R as an argument which will display the complement graph."
},
{
"code": null,
"e": 26326,
"s": 26320,
"text": "Code:"
},
{
"code": null,
"e": 26334,
"s": 26326,
"text": "Python3"
},
{
"code": "# importing networkx module import networkx as nx # creating sample graph object G = nx.path_graph(7) # creating sample graph object H = nx.path_graph(3) # compose of G and H saving in RR = nx.compose(G,H) # calling draw() to visualize the complement graph nx.draw(R) ",
"e": 26610,
"s": 26334,
"text": null
},
{
"code": null,
"e": 26618,
"s": 26610,
"text": "Output:"
},
{
"code": null,
"e": 26625,
"s": 26618,
"text": "OUTPUT"
},
{
"code": null,
"e": 26647,
"s": 26625,
"text": "Python Networx-module"
},
{
"code": null,
"e": 26654,
"s": 26647,
"text": "Python"
},
{
"code": null,
"e": 26752,
"s": 26654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26784,
"s": 26752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26840,
"s": 26784,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26882,
"s": 26840,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26924,
"s": 26882,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26946,
"s": 26924,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26985,
"s": 26946,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27016,
"s": 26985,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27071,
"s": 27016,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27100,
"s": 27071,
"text": "Create a directory in Python"
}
] |
SAP HANA - Calculation View
|
Calculation Views are used to consume other Analytic, Attribute and other Calculation views and base column tables. These are used to perform complex calculations, which are not possible with other type of Views.
Below given are few characteristics of Calculation Views −
Calculation Views are used to consume Analytic, Attribute and other Calculation Views.
Calculation Views are used to consume Analytic, Attribute and other Calculation Views.
They are used to perform complex calculations, which are not possible with other Views.
They are used to perform complex calculations, which are not possible with other Views.
There are two ways to create Calculation Views- SQL Editor or Graphical Editor.
There are two ways to create Calculation Views- SQL Editor or Graphical Editor.
Built-in Union, Join, Projection & Aggregation nodes.
Built-in Union, Join, Projection & Aggregation nodes.
Choose the Package name under which you want to create a Calculation View. Right Click on Package → Go to New → Calculation View. When you click on Calculation View, New Window will open.
Enter View name, Description and choose view type as Calculation View, Subtype Standard or Time (this is special kind of View which adds time dimension). You can use two types of Calculation View − Graphical and SQL Script.
It has default nodes like aggregation, Projection, Join and Union. It is used to consume other Attribute, Analytic and other Calculation views.
It is written in SQL scripts that are built on SQL commands or HANA defined functions.
Cube, in this default node, is Aggregation. You can choose Star join with Cube dimension.
Dimension, in this default node is Projection.
It does not allow base column tables, Attribute Views or Analytic views to add at data foundation. All Dimension tables must be changed to Dimension Calculation views to use in Star Join. All Fact tables can be added and can use default nodes in Calculation View.
The following example shows how we can use Calculation View with Star join −
You have four tables, two Dim tables, and two Fact tables. You have to find list of all employees with their Joining date, Emp Name, empId, Salary and Bonus.
Copy and paste the below script in SQL editor and execute.
Dim Tables − Empdim and Empdate
Create column table Empdim (empId nvarchar(3),Empname nvarchar(100));
Insert into Empdim values('AA1','John');
Insert into Empdim values('BB1','Anand');
Insert into Empdim values('CC1','Jason');
Create column table Empdate (caldate date, CALMONTH nvarchar(4) ,CALYEAR nvarchar(4));
Insert into Empdate values('20100101','04','2010');
Insert into Empdate values('20110101','05','2011');
Insert into Empdate values('20120101','06','2012');
Fact Tables − Empfact1, Empfact2
Create column table Empfact1 (empId nvarchar(3), Empdate date, Sal integer );
Insert into Empfact1 values('AA1','20100101',5000);
Insert into Empfact1 values('BB1','20110101',10000);
Insert into Empfact1 values('CC1','20120101',12000);
Create column table Empfact2 (empId nvarchar(3), deptName nvarchar(20), Bonus integer );
Insert into Empfact2 values ('AA1','SAP', 2000);
Insert into Empfact2 values ('BB1','Oracle', 2500);
Insert into Empfact2 values ('CC1','JAVA', 1500);
Now we have to implement Calculation View with Star Join. First change both Dim tables to Dimension Calculation View.
Create a Calculation View with Star Join. In Graphical pane, add 2 Projections for 2 Fact tables. Add both fact tables to both Projections and add attributes of these Projections to Output pane.
Add a join from default node and join both the fact tables. Add parameters of Fact Join to output pane.
In Star Join, add both- Dimension Calculation views and add Fact Join to Star Join as shown below. Choose parameters in Output pane and active the View.
Once view is activated successfully, right click on view name and click on Data Preview. Add attributes and measures to values and labels axis and do the analysis.
It simplifies the design process. You need not to create Analytical views and Attribute Views and directly Fact tables can be used as Projections.
3NF is possible with Star Join.
Create 2 Attribute Views on 2 Dim tables-Add output and activate both the views.
Create 2 Analytical Views on Fact Tables → Add both Attribute views and Fact1/Fact2 at Data Foundation in Analytic view.
Now Create a Calculation View → Dimension (Projection). Create Projections of both Analytical Views and Join them. Add attributes of this Join to output pane. Now Join to Projection and add output again.
Activate the view successful and go to Data preview for analysis.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3320,
"s": 3107,
"text": "Calculation Views are used to consume other Analytic, Attribute and other Calculation views and base column tables. These are used to perform complex calculations, which are not possible with other type of Views."
},
{
"code": null,
"e": 3379,
"s": 3320,
"text": "Below given are few characteristics of Calculation Views −"
},
{
"code": null,
"e": 3466,
"s": 3379,
"text": "Calculation Views are used to consume Analytic, Attribute and other Calculation Views."
},
{
"code": null,
"e": 3553,
"s": 3466,
"text": "Calculation Views are used to consume Analytic, Attribute and other Calculation Views."
},
{
"code": null,
"e": 3641,
"s": 3553,
"text": "They are used to perform complex calculations, which are not possible with other Views."
},
{
"code": null,
"e": 3729,
"s": 3641,
"text": "They are used to perform complex calculations, which are not possible with other Views."
},
{
"code": null,
"e": 3809,
"s": 3729,
"text": "There are two ways to create Calculation Views- SQL Editor or Graphical Editor."
},
{
"code": null,
"e": 3889,
"s": 3809,
"text": "There are two ways to create Calculation Views- SQL Editor or Graphical Editor."
},
{
"code": null,
"e": 3943,
"s": 3889,
"text": "Built-in Union, Join, Projection & Aggregation nodes."
},
{
"code": null,
"e": 3997,
"s": 3943,
"text": "Built-in Union, Join, Projection & Aggregation nodes."
},
{
"code": null,
"e": 4185,
"s": 3997,
"text": "Choose the Package name under which you want to create a Calculation View. Right Click on Package → Go to New → Calculation View. When you click on Calculation View, New Window will open."
},
{
"code": null,
"e": 4409,
"s": 4185,
"text": "Enter View name, Description and choose view type as Calculation View, Subtype Standard or Time (this is special kind of View which adds time dimension). You can use two types of Calculation View − Graphical and SQL Script."
},
{
"code": null,
"e": 4553,
"s": 4409,
"text": "It has default nodes like aggregation, Projection, Join and Union. It is used to consume other Attribute, Analytic and other Calculation views."
},
{
"code": null,
"e": 4640,
"s": 4553,
"text": "It is written in SQL scripts that are built on SQL commands or HANA defined functions."
},
{
"code": null,
"e": 4730,
"s": 4640,
"text": "Cube, in this default node, is Aggregation. You can choose Star join with Cube dimension."
},
{
"code": null,
"e": 4777,
"s": 4730,
"text": "Dimension, in this default node is Projection."
},
{
"code": null,
"e": 5041,
"s": 4777,
"text": "It does not allow base column tables, Attribute Views or Analytic views to add at data foundation. All Dimension tables must be changed to Dimension Calculation views to use in Star Join. All Fact tables can be added and can use default nodes in Calculation View."
},
{
"code": null,
"e": 5118,
"s": 5041,
"text": "The following example shows how we can use Calculation View with Star join −"
},
{
"code": null,
"e": 5276,
"s": 5118,
"text": "You have four tables, two Dim tables, and two Fact tables. You have to find list of all employees with their Joining date, Emp Name, empId, Salary and Bonus."
},
{
"code": null,
"e": 5335,
"s": 5276,
"text": "Copy and paste the below script in SQL editor and execute."
},
{
"code": null,
"e": 5367,
"s": 5335,
"text": "Dim Tables − Empdim and Empdate"
},
{
"code": null,
"e": 5562,
"s": 5367,
"text": "Create column table Empdim (empId nvarchar(3),Empname nvarchar(100));\nInsert into Empdim values('AA1','John');\nInsert into Empdim values('BB1','Anand');\nInsert into Empdim values('CC1','Jason');"
},
{
"code": null,
"e": 5805,
"s": 5562,
"text": "Create column table Empdate (caldate date, CALMONTH nvarchar(4) ,CALYEAR nvarchar(4));\nInsert into Empdate values('20100101','04','2010');\nInsert into Empdate values('20110101','05','2011');\nInsert into Empdate values('20120101','06','2012');"
},
{
"code": null,
"e": 5838,
"s": 5805,
"text": "Fact Tables − Empfact1, Empfact2"
},
{
"code": null,
"e": 6074,
"s": 5838,
"text": "Create column table Empfact1 (empId nvarchar(3), Empdate date, Sal integer );\nInsert into Empfact1 values('AA1','20100101',5000);\nInsert into Empfact1 values('BB1','20110101',10000);\nInsert into Empfact1 values('CC1','20120101',12000);"
},
{
"code": null,
"e": 6314,
"s": 6074,
"text": "Create column table Empfact2 (empId nvarchar(3), deptName nvarchar(20), Bonus integer );\nInsert into Empfact2 values ('AA1','SAP', 2000);\nInsert into Empfact2 values ('BB1','Oracle', 2500);\nInsert into Empfact2 values ('CC1','JAVA', 1500);"
},
{
"code": null,
"e": 6432,
"s": 6314,
"text": "Now we have to implement Calculation View with Star Join. First change both Dim tables to Dimension Calculation View."
},
{
"code": null,
"e": 6627,
"s": 6432,
"text": "Create a Calculation View with Star Join. In Graphical pane, add 2 Projections for 2 Fact tables. Add both fact tables to both Projections and add attributes of these Projections to Output pane."
},
{
"code": null,
"e": 6731,
"s": 6627,
"text": "Add a join from default node and join both the fact tables. Add parameters of Fact Join to output pane."
},
{
"code": null,
"e": 6884,
"s": 6731,
"text": "In Star Join, add both- Dimension Calculation views and add Fact Join to Star Join as shown below. Choose parameters in Output pane and active the View."
},
{
"code": null,
"e": 7048,
"s": 6884,
"text": "Once view is activated successfully, right click on view name and click on Data Preview. Add attributes and measures to values and labels axis and do the analysis."
},
{
"code": null,
"e": 7195,
"s": 7048,
"text": "It simplifies the design process. You need not to create Analytical views and Attribute Views and directly Fact tables can be used as Projections."
},
{
"code": null,
"e": 7227,
"s": 7195,
"text": "3NF is possible with Star Join."
},
{
"code": null,
"e": 7308,
"s": 7227,
"text": "Create 2 Attribute Views on 2 Dim tables-Add output and activate both the views."
},
{
"code": null,
"e": 7429,
"s": 7308,
"text": "Create 2 Analytical Views on Fact Tables → Add both Attribute views and Fact1/Fact2 at Data Foundation in Analytic view."
},
{
"code": null,
"e": 7633,
"s": 7429,
"text": "Now Create a Calculation View → Dimension (Projection). Create Projections of both Analytical Views and Join them. Add attributes of this Join to output pane. Now Join to Projection and add output again."
},
{
"code": null,
"e": 7699,
"s": 7633,
"text": "Activate the view successful and go to Data preview for analysis."
},
{
"code": null,
"e": 7732,
"s": 7699,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7746,
"s": 7732,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 7779,
"s": 7746,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7791,
"s": 7779,
"text": " Neha Gupta"
},
{
"code": null,
"e": 7826,
"s": 7791,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7841,
"s": 7826,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 7874,
"s": 7841,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7889,
"s": 7874,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 7924,
"s": 7889,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7936,
"s": 7924,
"text": " Neha Malik"
},
{
"code": null,
"e": 7971,
"s": 7936,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7983,
"s": 7971,
"text": " Neha Malik"
},
{
"code": null,
"e": 7990,
"s": 7983,
"text": " Print"
},
{
"code": null,
"e": 8001,
"s": 7990,
"text": " Add Notes"
}
] |
Difference between app.use() and app.get() in Express.js - GeeksforGeeks
|
26 May, 2021
Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features
Perquisites: Follow these steps for project setup and module installation.
Step 1: Create a directory using the below-given command. After creating a directory add the location of the created directory in a terminal.
mkdir <folder_name>
Step 2: Now initialize the npm (node package manager) using the below given command.
npm init
Step 3: Now Install Express in the present directory and save it in the dependencies list.
npm install express --save
1. app.use(): The app.use() function is used to mount the specified middleware function (are the functions that have access to the request object and response object, or we can call it a response-request cycle) at the path which is being specified. The middleware function is executed when the base of the requested path matches the path.
Syntax:
app.use([path,],callback[,callback...])
index.js
// Requiring moduleconst express = require('express')const app = express() app.use(function(req, res, next) { console.log('hello world') next()}) app.use(function(req, res, next) { console.log('happy holidays') next()}) // Server setupvar server = app.listen(8080, function () { var port = server.address().port console.log("Listening at", port) })
Run the index.js file using the following command:
node index.js
Output:
2. app.get(): This function tells the server what to do when get requests at a given route.
index.js
// Requiring modulevar express = require('express');var app = express(); app.get('/', function (req, res) { res.send('Hello Geek');}) // Server setupvar server = app.listen(8080, function () { var host = server.address().address var port = server.address().port console.log(" Listening : ", port)})
Run the index.js file using the following command:
node index.js
Output:
Difference between app.use() and app.get() methods:
app.use() method
app.get() method
Reference:
https://www.geeksforgeeks.org/express-js-app-use-function/
https://www.geeksforgeeks.org/express-js-app-get-function/
Express.js
Node.js-Methods
NodeJS-Questions
Picked
Difference Between
Node.js
Web Technologies
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
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
|
[
{
"code": null,
"e": 25120,
"s": 25092,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 25254,
"s": 25120,
"text": "Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features"
},
{
"code": null,
"e": 25329,
"s": 25254,
"text": "Perquisites: Follow these steps for project setup and module installation."
},
{
"code": null,
"e": 25471,
"s": 25329,
"text": "Step 1: Create a directory using the below-given command. After creating a directory add the location of the created directory in a terminal."
},
{
"code": null,
"e": 25492,
"s": 25471,
"text": " mkdir <folder_name>"
},
{
"code": null,
"e": 25577,
"s": 25492,
"text": "Step 2: Now initialize the npm (node package manager) using the below given command."
},
{
"code": null,
"e": 25588,
"s": 25579,
"text": "npm init"
},
{
"code": null,
"e": 25679,
"s": 25588,
"text": "Step 3: Now Install Express in the present directory and save it in the dependencies list."
},
{
"code": null,
"e": 25707,
"s": 25679,
"text": "npm install express --save "
},
{
"code": null,
"e": 26046,
"s": 25707,
"text": "1. app.use(): The app.use() function is used to mount the specified middleware function (are the functions that have access to the request object and response object, or we can call it a response-request cycle) at the path which is being specified. The middleware function is executed when the base of the requested path matches the path."
},
{
"code": null,
"e": 26054,
"s": 26046,
"text": "Syntax:"
},
{
"code": null,
"e": 26094,
"s": 26054,
"text": "app.use([path,],callback[,callback...])"
},
{
"code": null,
"e": 26103,
"s": 26094,
"text": "index.js"
},
{
"code": "// Requiring moduleconst express = require('express')const app = express() app.use(function(req, res, next) { console.log('hello world') next()}) app.use(function(req, res, next) { console.log('happy holidays') next()}) // Server setupvar server = app.listen(8080, function () { var port = server.address().port console.log(\"Listening at\", port) })",
"e": 26465,
"s": 26103,
"text": null
},
{
"code": null,
"e": 26516,
"s": 26465,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 26530,
"s": 26516,
"text": "node index.js"
},
{
"code": null,
"e": 26539,
"s": 26530,
"text": "Output: "
},
{
"code": null,
"e": 26631,
"s": 26539,
"text": "2. app.get(): This function tells the server what to do when get requests at a given route."
},
{
"code": null,
"e": 26640,
"s": 26631,
"text": "index.js"
},
{
"code": "// Requiring modulevar express = require('express');var app = express(); app.get('/', function (req, res) { res.send('Hello Geek');}) // Server setupvar server = app.listen(8080, function () { var host = server.address().address var port = server.address().port console.log(\" Listening : \", port)})",
"e": 26949,
"s": 26640,
"text": null
},
{
"code": null,
"e": 27000,
"s": 26949,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 27014,
"s": 27000,
"text": "node index.js"
},
{
"code": null,
"e": 27023,
"s": 27014,
"text": "Output: "
},
{
"code": null,
"e": 27075,
"s": 27023,
"text": "Difference between app.use() and app.get() methods:"
},
{
"code": null,
"e": 27092,
"s": 27075,
"text": "app.use() method"
},
{
"code": null,
"e": 27109,
"s": 27092,
"text": "app.get() method"
},
{
"code": null,
"e": 27121,
"s": 27109,
"text": "Reference: "
},
{
"code": null,
"e": 27180,
"s": 27121,
"text": "https://www.geeksforgeeks.org/express-js-app-use-function/"
},
{
"code": null,
"e": 27239,
"s": 27180,
"text": "https://www.geeksforgeeks.org/express-js-app-get-function/"
},
{
"code": null,
"e": 27250,
"s": 27239,
"text": "Express.js"
},
{
"code": null,
"e": 27266,
"s": 27250,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 27283,
"s": 27266,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 27290,
"s": 27283,
"text": "Picked"
},
{
"code": null,
"e": 27309,
"s": 27290,
"text": "Difference Between"
},
{
"code": null,
"e": 27317,
"s": 27309,
"text": "Node.js"
},
{
"code": null,
"e": 27334,
"s": 27317,
"text": "Web Technologies"
},
{
"code": null,
"e": 27432,
"s": 27334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27441,
"s": 27432,
"text": "Comments"
},
{
"code": null,
"e": 27454,
"s": 27441,
"text": "Old Comments"
},
{
"code": null,
"e": 27515,
"s": 27454,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27583,
"s": 27515,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27639,
"s": 27583,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 27697,
"s": 27639,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27752,
"s": 27697,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27785,
"s": 27752,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27833,
"s": 27785,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27866,
"s": 27833,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 27895,
"s": 27866,
"text": "Node.js fs.readFile() Method"
}
] |
What is a string? Declare and initialize the strings in C language
|
An array of characters (or) collection of characters is called a string.
Refer to the declaration given below −
char stringname [size];
For example - char a[50]; a string of length 50 characters.
The initialization is as follows −
Using single character constant −
Using single character constant −
char string[20] = { ‘H’, ‘i’, ‘l’, ‘l’, ‘s’ ,‘\0’}
Using string constants −
Using string constants −
char string[20] = "Hello":;
‘\0’ is called a null character. It marks the end of the string.
‘\0’ is called a null character. It marks the end of the string.
‘\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\0’ at the end if a single character is given.
‘\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\0’ at the end if a single character is given.
Accessing − There is a control string "%s" used for accessing the string, till it encounters ‘\0’.
Following is the C program for a string −
#include<stdio.h>
main ( ){
char a[10] = "Hello";
clrscr ( );
printf ( " given string is %s",a)
getch ( );
}
When the above program is executed, it produces the following result −
Given string is Hello
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "An array of characters (or) collection of characters is called a string."
},
{
"code": null,
"e": 1174,
"s": 1135,
"text": "Refer to the declaration given below −"
},
{
"code": null,
"e": 1198,
"s": 1174,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1258,
"s": 1198,
"text": "For example - char a[50]; a string of length 50 characters."
},
{
"code": null,
"e": 1293,
"s": 1258,
"text": "The initialization is as follows −"
},
{
"code": null,
"e": 1327,
"s": 1293,
"text": "Using single character constant −"
},
{
"code": null,
"e": 1361,
"s": 1327,
"text": "Using single character constant −"
},
{
"code": null,
"e": 1412,
"s": 1361,
"text": "char string[20] = { ‘H’, ‘i’, ‘l’, ‘l’, ‘s’ ,‘\\0’}"
},
{
"code": null,
"e": 1437,
"s": 1412,
"text": "Using string constants −"
},
{
"code": null,
"e": 1462,
"s": 1437,
"text": "Using string constants −"
},
{
"code": null,
"e": 1490,
"s": 1462,
"text": "char string[20] = \"Hello\":;"
},
{
"code": null,
"e": 1555,
"s": 1490,
"text": "‘\\0’ is called a null character. It marks the end of the string."
},
{
"code": null,
"e": 1620,
"s": 1555,
"text": "‘\\0’ is called a null character. It marks the end of the string."
},
{
"code": null,
"e": 1782,
"s": 1620,
"text": "‘\\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\\0’ at the end if a single character is given."
},
{
"code": null,
"e": 1944,
"s": 1782,
"text": "‘\\0’ is automatically placed by the compiler, if a string is given as input. The user has to take care of placing ‘\\0’ at the end if a single character is given."
},
{
"code": null,
"e": 2043,
"s": 1944,
"text": "Accessing − There is a control string \"%s\" used for accessing the string, till it encounters ‘\\0’."
},
{
"code": null,
"e": 2085,
"s": 2043,
"text": "Following is the C program for a string −"
},
{
"code": null,
"e": 2206,
"s": 2085,
"text": "#include<stdio.h>\nmain ( ){\n char a[10] = \"Hello\";\n clrscr ( );\n printf ( \" given string is %s\",a)\n getch ( );\n}"
},
{
"code": null,
"e": 2277,
"s": 2206,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2299,
"s": 2277,
"text": "Given string is Hello"
}
] |
Cluster-based Image Segmentation -Python | by Mathanraj Sharma | Towards Data Science
|
Recently I was working on an Image classification task where first I wanted to capture the region of interest from the image before feeding it into the model. I tried a technique called cluster-based image segmentation which helped me to improve my model performance by a certain level. Let us see what it is and some sample codes to do cluster segmentation, you can find the Jupyter Notebook at the bottom.
Imagine that you are going to cross the road, what you do before you cross the road?
First, you see both sides of the road to determine the approaching vehicles and other environmental objects, then you do some amazing estimation of approaching speed and decide on when and how to cross the road. All these happens within a fraction of time, how amazing isn’t it.
Our brain captures the Images of both sides of the roadIt detects the vehicles and other objects on the road == Object DetectionNot only detect before that it determines the shape of every object it detects == Image Segmentation
Our brain captures the Images of both sides of the road
It detects the vehicles and other objects on the road == Object Detection
Not only detect before that it determines the shape of every object it detects == Image Segmentation
How amazing our brain is, by determining the shapes of different objects, it able to detect the multiple objects in the same snapshot.
Let me explain furthermore, assume we have our Image Classification model which is able to classify the apple and orange with more than 95% accuracy. When we input an Image that contains both apple and orange the prediction accuracy will go down. As the number of objects in the image increases the classification models' performances will go down. That is where the object localization comes into play.
Before we detect objects in an image and classify it, the model needs to understand what is in the image, this is where Image Segmentation helps. It creates a pixel-wise mask for the objects in an image which helps models to understand the shape of objects and their position in the image at a more granular level.
Image segmentation is broadly categorized into two main categories.
Semantic SegmentationInstance Segmentation
Semantic Segmentation
Instance Segmentation
In the first image, we can see that detected objects all are men. In semantic segmentation, we consider all those pixels belong to one class, so we represent them all by one color. On the other hand in instance segmentation, those pixels belong to the same class but we represent different instances of the same class with different colors.
Based on the approach we use segmentation can be divided into many narrower categories.
Region-Based Segmentation
Edge Detection based Segmentation
Cluster-based segmentation
CNN based Segmentation and etc.
I am only going to give an example of cluster-based segmentation in this article as I promised at the top.
Recall your understanding of clustering algorithms. Clustering algorithms are used to group closer the data points that are more similar to each other, from other group data points.
Now think of an image that holds apple and orange. Most of the pixel points in apple should be red/green, which is different from the pixel values of orange. If we can cluster these points we can distinguish each object from one another right. That’s how the cluster-based segmentation works. Let’s see some code samples now.
from skimage.io import imreadfrom skimage.color import rgb2grayimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom scipy import ndimage# Scaling the image pixels values within 0-1img = imread('./apple-orange.jpg') / 255plt.imshow(img)plt.title('Original')plt.show()
As it is visible to our naked eye there are five color segments in the Image
The green part of ApplesThe orange part of OrangesGray Shadows at bottom of the Apples and orangesBright Yellowish part of Apple’s top and right partsWhite Background
The green part of Apples
The orange part of Oranges
Gray Shadows at bottom of the Apples and oranges
Bright Yellowish part of Apple’s top and right parts
White Background
Let us see whether we can cluster them using our KMeans algorithm from scikit-learn
# For clustering the image using k-means, we first need to convert it into a 2-dimensional arrayimage_2D = img.reshape(img.shape[0]*img.shape[1], img.shape[2])# Use KMeans clustering algorithm from sklearn.cluster to cluster pixels in imagefrom sklearn.cluster import KMeans# tweak the cluster size and see what happens to the Outputkmeans = KMeans(n_clusters=5, random_state=0).fit(image_2D)clustered = kmeans.cluster_centers_[kmeans.labels_]# Reshape back the image from 2D to 3D imageclustered_3D = clustered.reshape(img.shape[0], img.shape[1], img.shape[2])plt.imshow(clustered_3D)plt.title('Clustered Image')plt.show()
Wow, that works!!! We are able to cluster all five parts. This is how the cluster segmentation works.
There are many advanced techniques like Mask R-CNN to do more granular level segmentation. Let us see those topics in some other article. I hope you now have some level of Understanding of Image Segmentation.
You can find the notebook for the above example at https://github.com/Mathanraj-Sharma/sample-for-medium-article/blob/master/cluster-based-segmentation-skimage/cluster-based-segmentation.ipynb
|
[
{
"code": null,
"e": 579,
"s": 171,
"text": "Recently I was working on an Image classification task where first I wanted to capture the region of interest from the image before feeding it into the model. I tried a technique called cluster-based image segmentation which helped me to improve my model performance by a certain level. Let us see what it is and some sample codes to do cluster segmentation, you can find the Jupyter Notebook at the bottom."
},
{
"code": null,
"e": 664,
"s": 579,
"text": "Imagine that you are going to cross the road, what you do before you cross the road?"
},
{
"code": null,
"e": 943,
"s": 664,
"text": "First, you see both sides of the road to determine the approaching vehicles and other environmental objects, then you do some amazing estimation of approaching speed and decide on when and how to cross the road. All these happens within a fraction of time, how amazing isn’t it."
},
{
"code": null,
"e": 1172,
"s": 943,
"text": "Our brain captures the Images of both sides of the roadIt detects the vehicles and other objects on the road == Object DetectionNot only detect before that it determines the shape of every object it detects == Image Segmentation"
},
{
"code": null,
"e": 1228,
"s": 1172,
"text": "Our brain captures the Images of both sides of the road"
},
{
"code": null,
"e": 1302,
"s": 1228,
"text": "It detects the vehicles and other objects on the road == Object Detection"
},
{
"code": null,
"e": 1403,
"s": 1302,
"text": "Not only detect before that it determines the shape of every object it detects == Image Segmentation"
},
{
"code": null,
"e": 1538,
"s": 1403,
"text": "How amazing our brain is, by determining the shapes of different objects, it able to detect the multiple objects in the same snapshot."
},
{
"code": null,
"e": 1942,
"s": 1538,
"text": "Let me explain furthermore, assume we have our Image Classification model which is able to classify the apple and orange with more than 95% accuracy. When we input an Image that contains both apple and orange the prediction accuracy will go down. As the number of objects in the image increases the classification models' performances will go down. That is where the object localization comes into play."
},
{
"code": null,
"e": 2257,
"s": 1942,
"text": "Before we detect objects in an image and classify it, the model needs to understand what is in the image, this is where Image Segmentation helps. It creates a pixel-wise mask for the objects in an image which helps models to understand the shape of objects and their position in the image at a more granular level."
},
{
"code": null,
"e": 2325,
"s": 2257,
"text": "Image segmentation is broadly categorized into two main categories."
},
{
"code": null,
"e": 2368,
"s": 2325,
"text": "Semantic SegmentationInstance Segmentation"
},
{
"code": null,
"e": 2390,
"s": 2368,
"text": "Semantic Segmentation"
},
{
"code": null,
"e": 2412,
"s": 2390,
"text": "Instance Segmentation"
},
{
"code": null,
"e": 2753,
"s": 2412,
"text": "In the first image, we can see that detected objects all are men. In semantic segmentation, we consider all those pixels belong to one class, so we represent them all by one color. On the other hand in instance segmentation, those pixels belong to the same class but we represent different instances of the same class with different colors."
},
{
"code": null,
"e": 2841,
"s": 2753,
"text": "Based on the approach we use segmentation can be divided into many narrower categories."
},
{
"code": null,
"e": 2867,
"s": 2841,
"text": "Region-Based Segmentation"
},
{
"code": null,
"e": 2901,
"s": 2867,
"text": "Edge Detection based Segmentation"
},
{
"code": null,
"e": 2928,
"s": 2901,
"text": "Cluster-based segmentation"
},
{
"code": null,
"e": 2960,
"s": 2928,
"text": "CNN based Segmentation and etc."
},
{
"code": null,
"e": 3067,
"s": 2960,
"text": "I am only going to give an example of cluster-based segmentation in this article as I promised at the top."
},
{
"code": null,
"e": 3249,
"s": 3067,
"text": "Recall your understanding of clustering algorithms. Clustering algorithms are used to group closer the data points that are more similar to each other, from other group data points."
},
{
"code": null,
"e": 3575,
"s": 3249,
"text": "Now think of an image that holds apple and orange. Most of the pixel points in apple should be red/green, which is different from the pixel values of orange. If we can cluster these points we can distinguish each object from one another right. That’s how the cluster-based segmentation works. Let’s see some code samples now."
},
{
"code": null,
"e": 3861,
"s": 3575,
"text": "from skimage.io import imreadfrom skimage.color import rgb2grayimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinefrom scipy import ndimage# Scaling the image pixels values within 0-1img = imread('./apple-orange.jpg') / 255plt.imshow(img)plt.title('Original')plt.show()"
},
{
"code": null,
"e": 3938,
"s": 3861,
"text": "As it is visible to our naked eye there are five color segments in the Image"
},
{
"code": null,
"e": 4105,
"s": 3938,
"text": "The green part of ApplesThe orange part of OrangesGray Shadows at bottom of the Apples and orangesBright Yellowish part of Apple’s top and right partsWhite Background"
},
{
"code": null,
"e": 4130,
"s": 4105,
"text": "The green part of Apples"
},
{
"code": null,
"e": 4157,
"s": 4130,
"text": "The orange part of Oranges"
},
{
"code": null,
"e": 4206,
"s": 4157,
"text": "Gray Shadows at bottom of the Apples and oranges"
},
{
"code": null,
"e": 4259,
"s": 4206,
"text": "Bright Yellowish part of Apple’s top and right parts"
},
{
"code": null,
"e": 4276,
"s": 4259,
"text": "White Background"
},
{
"code": null,
"e": 4360,
"s": 4276,
"text": "Let us see whether we can cluster them using our KMeans algorithm from scikit-learn"
},
{
"code": null,
"e": 4984,
"s": 4360,
"text": "# For clustering the image using k-means, we first need to convert it into a 2-dimensional arrayimage_2D = img.reshape(img.shape[0]*img.shape[1], img.shape[2])# Use KMeans clustering algorithm from sklearn.cluster to cluster pixels in imagefrom sklearn.cluster import KMeans# tweak the cluster size and see what happens to the Outputkmeans = KMeans(n_clusters=5, random_state=0).fit(image_2D)clustered = kmeans.cluster_centers_[kmeans.labels_]# Reshape back the image from 2D to 3D imageclustered_3D = clustered.reshape(img.shape[0], img.shape[1], img.shape[2])plt.imshow(clustered_3D)plt.title('Clustered Image')plt.show()"
},
{
"code": null,
"e": 5086,
"s": 4984,
"text": "Wow, that works!!! We are able to cluster all five parts. This is how the cluster segmentation works."
},
{
"code": null,
"e": 5295,
"s": 5086,
"text": "There are many advanced techniques like Mask R-CNN to do more granular level segmentation. Let us see those topics in some other article. I hope you now have some level of Understanding of Image Segmentation."
}
] |
How to make the Tkinter text widget read only?
|
In Tkinter, sometimes, we may want to make a text widget disabled. To achieve
this, we can set the text configuration as DISABLED. This will freeze the text widget
and will make it read-only.
In this example, we will create a text widget and a button which will allow users to
disable or freeze the text widget instantly.
#Import the library
from tkinter import *
#Create an instance of window
win= Tk()
#Set the geometry of the window
win.geometry("700x400")
def disable_button():
text.config(state= DISABLED)
#Label
Label(win,text="Type Something",font=('Helvetica bold', 25),
fg="green").pack(pady=20)
#Create a Text widget
text= Text(win, height= 10,width= 40)
text.pack()
#Create a Disable Button
Button(win, text= "Disable", command= disable_button,fg= "white",
bg="black", width= 20).pack(pady=20)
win.mainloop()
Running the above code will create a text widget and a button which can be used
to disable or freeze the widget.
After you click the “Disable” button, the text widget will be disabled and you won’t
be able to type anything else inside it.
|
[
{
"code": null,
"e": 1254,
"s": 1062,
"text": "In Tkinter, sometimes, we may want to make a text widget disabled. To achieve\nthis, we can set the text configuration as DISABLED. This will freeze the text widget\nand will make it read-only."
},
{
"code": null,
"e": 1384,
"s": 1254,
"text": "In this example, we will create a text widget and a button which will allow users to\ndisable or freeze the text widget instantly."
},
{
"code": null,
"e": 1892,
"s": 1384,
"text": "#Import the library\nfrom tkinter import *\n\n#Create an instance of window\nwin= Tk()\n\n#Set the geometry of the window\nwin.geometry(\"700x400\")\n\ndef disable_button():\n text.config(state= DISABLED)\n\n#Label\nLabel(win,text=\"Type Something\",font=('Helvetica bold', 25),\nfg=\"green\").pack(pady=20)\n\n#Create a Text widget\ntext= Text(win, height= 10,width= 40)\ntext.pack()\n\n#Create a Disable Button\nButton(win, text= \"Disable\", command= disable_button,fg= \"white\",\nbg=\"black\", width= 20).pack(pady=20)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2005,
"s": 1892,
"text": "Running the above code will create a text widget and a button which can be used\nto disable or freeze the widget."
},
{
"code": null,
"e": 2131,
"s": 2005,
"text": "After you click the “Disable” button, the text widget will be disabled and you won’t\nbe able to type anything else inside it."
}
] |
Setup the format of DATETIME to 'DDMM- YYYY HH:MM:SS' with MySQL SELECT?
|
Whenever you retrieve datetime from a table, the datetime gives ‘YYYY-MM-DD’ format. If you want to change the output, then you need to use in-built date_format() from MySQL.
The syntax is as follows −
SELECT DATE_FORMAT(yourDatetimeColumnName,yourFormat) as anyVariableName from
yourTableName;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table UserDateFormat
-> (
-> ProductId int,
-> ProductDeliverDate datetime
-> );
Query OK, 0 rows affected (0.93 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into UserDateFormat values(100,date_add(now(),interval 1 year));
Query OK, 1 row affected (0.10 sec)
mysql> insert into UserDateFormat values(101,date_add(now(),interval -1 year));
Query OK, 1 row affected (0.48 sec)
mysql> insert into UserDateFormat values(102,date_add(now(),interval -3 year));
Query OK, 1 row affected (0.17 sec)
mysql> insert into UserDateFormat values(103,date_add(now(),interval -2 year));
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select command. The query is as follows −
mysql> select *from UserDateFormat;
+-----------+---------------------+
| ProductId | ProductDeliverDate |
+-----------+---------------------+
| 100 | 2019-12-24 13:32:47 |
| 101 | 2017-12-24 13:32:58 |
| 102 | 2015-12-24 13:33:08 |
| 103 | 2016-12-24 13:33:17 |
+-----------+---------------------+
4 rows in set (0.00 sec)
The above datetime format is from MySQL datetime. Now you can format datetime accordingly, which includes the ‘DD-MM-YYYY’ format as well.
The query is as follows −
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %h:%i:%s') as UserFormat from
UserDateFormat;
The following is the output displaying date in the DD-MM-YYYY format −
+----------------------+
| UserFormat |
+----------------------+
| 24-12-2019 01:32:47 |
| 24-12-2017 01:32:58 |
| 24-12-2015 01:33:08 |
| 24-12-2016 01:33:17 |
+----------------------+
4 rows in set (0.00 sec)
You can get the above time format in 24 hours. The query is as follows −
mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %H:%i:%S') as UserFormat
from UserDateFormat;
+----------------------+
| UserFormat |
+----------------------+
| 24-12-2019 13:32:47 |
| 24-12-2017 13:32:58 |
| 24-12-2015 13:33:08 |
| 24-12-2016 13:33:17 |
+----------------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "Whenever you retrieve datetime from a table, the datetime gives ‘YYYY-MM-DD’ format. If you want to change the output, then you need to use in-built date_format() from MySQL."
},
{
"code": null,
"e": 1264,
"s": 1237,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1357,
"s": 1264,
"text": "SELECT DATE_FORMAT(yourDatetimeColumnName,yourFormat) as anyVariableName from\nyourTableName;"
},
{
"code": null,
"e": 1462,
"s": 1357,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1606,
"s": 1462,
"text": "mysql> create table UserDateFormat\n -> (\n -> ProductId int,\n -> ProductDeliverDate datetime\n -> );\nQuery OK, 0 rows affected (0.93 sec)"
},
{
"code": null,
"e": 1687,
"s": 1606,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2153,
"s": 1687,
"text": "mysql> insert into UserDateFormat values(100,date_add(now(),interval 1 year));\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into UserDateFormat values(101,date_add(now(),interval -1 year));\nQuery OK, 1 row affected (0.48 sec)\n\nmysql> insert into UserDateFormat values(102,date_add(now(),interval -3 year));\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into UserDateFormat values(103,date_add(now(),interval -2 year));\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2236,
"s": 2153,
"text": "Display all records from the table using select command. The query is as follows −"
},
{
"code": null,
"e": 2272,
"s": 2236,
"text": "mysql> select *from UserDateFormat;"
},
{
"code": null,
"e": 2585,
"s": 2272,
"text": "+-----------+---------------------+\n| ProductId | ProductDeliverDate |\n+-----------+---------------------+\n| 100 | 2019-12-24 13:32:47 |\n| 101 | 2017-12-24 13:32:58 |\n| 102 | 2015-12-24 13:33:08 |\n| 103 | 2016-12-24 13:33:17 |\n+-----------+---------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2724,
"s": 2585,
"text": "The above datetime format is from MySQL datetime. Now you can format datetime accordingly, which includes the ‘DD-MM-YYYY’ format as well."
},
{
"code": null,
"e": 2750,
"s": 2724,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2851,
"s": 2750,
"text": "mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %h:%i:%s') as UserFormat from\nUserDateFormat;"
},
{
"code": null,
"e": 2922,
"s": 2851,
"text": "The following is the output displaying date in the DD-MM-YYYY format −"
},
{
"code": null,
"e": 3147,
"s": 2922,
"text": "+----------------------+\n| UserFormat |\n+----------------------+\n| 24-12-2019 01:32:47 |\n| 24-12-2017 01:32:58 |\n| 24-12-2015 01:33:08 |\n| 24-12-2016 01:33:17 |\n+----------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3220,
"s": 3147,
"text": "You can get the above time format in 24 hours. The query is as follows −"
},
{
"code": null,
"e": 3321,
"s": 3220,
"text": "mysql> select date_format(ProductDeliverDate,'%d-%m-%Y %H:%i:%S') as UserFormat\nfrom UserDateFormat;"
},
{
"code": null,
"e": 3546,
"s": 3321,
"text": "+----------------------+\n| UserFormat |\n+----------------------+\n| 24-12-2019 13:32:47 |\n| 24-12-2017 13:32:58 |\n| 24-12-2015 13:33:08 |\n| 24-12-2016 13:33:17 |\n+----------------------+\n4 rows in set (0.00 sec)"
}
] |
MongoDB query to get date records in a range
|
To get date records in a range, use gtalongwithlt. Let us create a collection with documents −
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-11 12:30:10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2863fecfb11e5c34d89927")
}
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-10-12 03:10:00")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e28641acfb11e5c34d89928")
}
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-14 05:11:20")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e28642acfb11e5c34d89929")
}
Display all documents from a collection with the help of find() method −
> db.demo60.find();
This will produce the following output −
{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") }
{ "_id" : ObjectId("5e28641acfb11e5c34d89928"), "ArrivalDate" : ISODate("2019-10-12T03:10:00Z") }
{ "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
Following is the query to get date records in a range −
> db.demo60.find({"ArrivalDate": {"$gt":ISODate("2019-01-09T12:30:10Z"), "$lt": ISODate("2019-01-16T12:30:10Z")}});
This will produce the following output −
{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") }
{ "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "To get date records in a range, use gtalongwithlt. Let us create a collection with documents −"
},
{
"code": null,
"e": 1637,
"s": 1157,
"text": "> db.demo60.insertOne({\"ArrivalDate\":new ISODate(\"2019-01-11 12:30:10\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2863fecfb11e5c34d89927\")\n}\n> db.demo60.insertOne({\"ArrivalDate\":new ISODate(\"2019-10-12 03:10:00\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e28641acfb11e5c34d89928\")\n}\n> db.demo60.insertOne({\"ArrivalDate\":new ISODate(\"2019-01-14 05:11:20\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e28642acfb11e5c34d89929\")\n}"
},
{
"code": null,
"e": 1710,
"s": 1637,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1730,
"s": 1710,
"text": "> db.demo60.find();"
},
{
"code": null,
"e": 1771,
"s": 1730,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2065,
"s": 1771,
"text": "{ \"_id\" : ObjectId(\"5e2863fecfb11e5c34d89927\"), \"ArrivalDate\" : ISODate(\"2019-01-11T12:30:10Z\") }\n{ \"_id\" : ObjectId(\"5e28641acfb11e5c34d89928\"), \"ArrivalDate\" : ISODate(\"2019-10-12T03:10:00Z\") }\n{ \"_id\" : ObjectId(\"5e28642acfb11e5c34d89929\"), \"ArrivalDate\" : ISODate(\"2019-01-14T05:11:20Z\") }"
},
{
"code": null,
"e": 2121,
"s": 2065,
"text": "Following is the query to get date records in a range −"
},
{
"code": null,
"e": 2237,
"s": 2121,
"text": "> db.demo60.find({\"ArrivalDate\": {\"$gt\":ISODate(\"2019-01-09T12:30:10Z\"), \"$lt\": ISODate(\"2019-01-16T12:30:10Z\")}});"
},
{
"code": null,
"e": 2278,
"s": 2237,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2474,
"s": 2278,
"text": "{ \"_id\" : ObjectId(\"5e2863fecfb11e5c34d89927\"), \"ArrivalDate\" : ISODate(\"2019-01-11T12:30:10Z\") }\n{ \"_id\" : ObjectId(\"5e28642acfb11e5c34d89929\"), \"ArrivalDate\" : ISODate(\"2019-01-14T05:11:20Z\") }"
}
] |
JSF - h:messages
|
The h:messages tag shows all the messages at one place corresponding to UI elements.
<h:messages style = "color:red;margin:8px;" />
Case: Username entered is more than 20 characters and password entered is less than 5 characters.
<ul style = "color:red;margin:8px;">
<li> UserName: Validation Error:
Length is greater than allowable maximum of '20' </li>
<li> Password: Validation Error:
Length is less than allowable minimum of '5' </li>
</ul>
id
Identifier for a component
binding
Reference to the component that can be used in a backing bean
rendered
A boolean; false suppresses rendering
styleClass
Cascading stylesheet (CSS) class name
for
The ID of the component whose message is displayed, applicable only to h:message
errorClass
CSS class applied to error messages
errorStyle
CSS style applied to error messages
fatalClass
CSS class applied to fatal messages
fatalStyle
CSS style applied to fatal messages
globalOnly
Instruction to display only global messages, applicable only to h:messages. Default: false
infoClass
CSS class applied to information messages
infoStyle
CSS style applied to information messages
layout
Specification for message layout: table or list, applicable only to h:messages
showDetail
A boolean that determines whether message details are shown. Defaults are false for h:messages, true for h:message
showSummary
A boolean that determines whether message summaries are shown. Defaults are true for h:messages, false for h:message
tooltip
A boolean that determines whether message details are rendered in a tooltip; the tooltip is only rendered if showDetail and showSummary are true
warnClass
CSS class for warning messages
warnStyle
CSS style for warning messages
style
Inline style information
title
A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value
Let us create a test JSF application to test the above tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
<h2>h:messages example</h2>
<hr />
<h:form>
<h:panelGrid id = "panel" columns = "2" border = "0" cellpadding = "10"
cellspacing = "1">
<h:outputLabel value = "Enter Username" />
<h:inputText id = "username" size = "20" label = "UserName"
required = "true">
<f:validateLength for = "username" minimum = "5" maximum = "20" />
</h:inputText>
<h:outputLabel value = "Enter Password" />
<h:inputSecret id = "password" size = "20" label = "Password"
required = "true" redisplay = "true" >
<f:validateLength for = "password" minimum = "5" maximum = "10" />
</h:inputSecret>
<h:commandButton id = "submit" value = "Submit" action = "result"/>
</h:panelGrid>
<h:messages style = "color:red;margin:8px;" />
</h:form>
</body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2037,
"s": 1952,
"text": "The h:messages tag shows all the messages at one place corresponding to UI elements."
},
{
"code": null,
"e": 2085,
"s": 2037,
"text": "<h:messages style = \"color:red;margin:8px;\" /> "
},
{
"code": null,
"e": 2183,
"s": 2085,
"text": "Case: Username entered is more than 20 characters and password entered is less than 5 characters."
},
{
"code": null,
"e": 2424,
"s": 2183,
"text": "<ul style = \"color:red;margin:8px;\"> \n <li> UserName: Validation Error: \n Length is greater than allowable maximum of '20' </li> \n <li> Password: Validation Error: \n Length is less than allowable minimum of '5' </li> \n</ul> "
},
{
"code": null,
"e": 2427,
"s": 2424,
"text": "id"
},
{
"code": null,
"e": 2454,
"s": 2427,
"text": "Identifier for a component"
},
{
"code": null,
"e": 2462,
"s": 2454,
"text": "binding"
},
{
"code": null,
"e": 2524,
"s": 2462,
"text": "Reference to the component that can be used in a backing bean"
},
{
"code": null,
"e": 2533,
"s": 2524,
"text": "rendered"
},
{
"code": null,
"e": 2571,
"s": 2533,
"text": "A boolean; false suppresses rendering"
},
{
"code": null,
"e": 2582,
"s": 2571,
"text": "styleClass"
},
{
"code": null,
"e": 2620,
"s": 2582,
"text": "Cascading stylesheet (CSS) class name"
},
{
"code": null,
"e": 2624,
"s": 2620,
"text": "for"
},
{
"code": null,
"e": 2705,
"s": 2624,
"text": "The ID of the component whose message is displayed, applicable only to h:message"
},
{
"code": null,
"e": 2716,
"s": 2705,
"text": "errorClass"
},
{
"code": null,
"e": 2752,
"s": 2716,
"text": "CSS class applied to error messages"
},
{
"code": null,
"e": 2763,
"s": 2752,
"text": "errorStyle"
},
{
"code": null,
"e": 2799,
"s": 2763,
"text": "CSS style applied to error messages"
},
{
"code": null,
"e": 2810,
"s": 2799,
"text": "fatalClass"
},
{
"code": null,
"e": 2846,
"s": 2810,
"text": "CSS class applied to fatal messages"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": "fatalStyle"
},
{
"code": null,
"e": 2893,
"s": 2857,
"text": "CSS style applied to fatal messages"
},
{
"code": null,
"e": 2904,
"s": 2893,
"text": "globalOnly"
},
{
"code": null,
"e": 2995,
"s": 2904,
"text": "Instruction to display only global messages, applicable only to h:messages. Default: false"
},
{
"code": null,
"e": 3005,
"s": 2995,
"text": "infoClass"
},
{
"code": null,
"e": 3047,
"s": 3005,
"text": "CSS class applied to information messages"
},
{
"code": null,
"e": 3057,
"s": 3047,
"text": "infoStyle"
},
{
"code": null,
"e": 3099,
"s": 3057,
"text": "CSS style applied to information messages"
},
{
"code": null,
"e": 3106,
"s": 3099,
"text": "layout"
},
{
"code": null,
"e": 3185,
"s": 3106,
"text": "Specification for message layout: table or list, applicable only to h:messages"
},
{
"code": null,
"e": 3196,
"s": 3185,
"text": "showDetail"
},
{
"code": null,
"e": 3311,
"s": 3196,
"text": "A boolean that determines whether message details are shown. Defaults are false for h:messages, true for h:message"
},
{
"code": null,
"e": 3323,
"s": 3311,
"text": "showSummary"
},
{
"code": null,
"e": 3440,
"s": 3323,
"text": "A boolean that determines whether message summaries are shown. Defaults are true for h:messages, false for h:message"
},
{
"code": null,
"e": 3448,
"s": 3440,
"text": "tooltip"
},
{
"code": null,
"e": 3593,
"s": 3448,
"text": "A boolean that determines whether message details are rendered in a tooltip; the tooltip is only rendered if showDetail and showSummary are true"
},
{
"code": null,
"e": 3603,
"s": 3593,
"text": "warnClass"
},
{
"code": null,
"e": 3634,
"s": 3603,
"text": "CSS class for warning messages"
},
{
"code": null,
"e": 3644,
"s": 3634,
"text": "warnStyle"
},
{
"code": null,
"e": 3675,
"s": 3644,
"text": "CSS style for warning messages"
},
{
"code": null,
"e": 3681,
"s": 3675,
"text": "style"
},
{
"code": null,
"e": 3706,
"s": 3681,
"text": "Inline style information"
},
{
"code": null,
"e": 3712,
"s": 3706,
"text": "title"
},
{
"code": null,
"e": 3836,
"s": 3712,
"text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value"
},
{
"code": null,
"e": 3896,
"s": 3836,
"text": "Let us create a test JSF application to test the above tag."
},
{
"code": null,
"e": 5159,
"s": 3896,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <title>JSF Tutorial!</title> \n </head>\n \n <body> \n <h2>h:messages example</h2> \n <hr /> \n \n <h:form> \n <h:panelGrid id = \"panel\" columns = \"2\" border = \"0\" cellpadding = \"10\" \n cellspacing = \"1\"> \n <h:outputLabel value = \"Enter Username\" /> \n \n <h:inputText id = \"username\" size = \"20\" label = \"UserName\" \n required = \"true\"> \n <f:validateLength for = \"username\" minimum = \"5\" maximum = \"20\" /> \n </h:inputText> \n <h:outputLabel value = \"Enter Password\" /> \n \n <h:inputSecret id = \"password\" size = \"20\" label = \"Password\" \n required = \"true\" redisplay = \"true\" > \n <f:validateLength for = \"password\" minimum = \"5\" maximum = \"10\" /> \n </h:inputSecret> \n <h:commandButton id = \"submit\" value = \"Submit\" action = \"result\"/> \n </h:panelGrid> \n <h:messages style = \"color:red;margin:8px;\" /> \n </h:form> \n \n </body> \n</html> "
},
{
"code": null,
"e": 5371,
"s": 5159,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:"
},
{
"code": null,
"e": 5406,
"s": 5371,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5421,
"s": 5406,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5428,
"s": 5421,
"text": " Print"
},
{
"code": null,
"e": 5439,
"s": 5428,
"text": " Add Notes"
}
] |
Count number of triplets in an array having sum in the range [a, b] - GeeksforGeeks
|
11 Aug, 2021
Given an array of distinct integers and a range [a, b], the task is to count the number of triplets having a sum in the range [a, b].Examples:
Input : arr[] = {8, 3, 5, 2}
range = [7, 11]
Output : 1
There is only one triplet {2, 3, 5}
having sum 10 in range [7, 11].
Input : arr[] = {2, 7, 5, 3, 8, 4, 1, 9}
range = [8, 16]
Output : 36
A naive approach is to run three loops to consider all the triplets one by one. Find the sum of each triplet and increment the count if the sum lies in a given range [a, b].Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count triplets with// sum that lies in given range [a, b].#include <bits/stdc++.h> using namespace std; // Function to count tripletsint countTriplets(int arr[], int n, int a, int b){ // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for the third number for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) ans++; } } return ans;} // Driver Codeint main(){ int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 }; int n = sizeof arr / sizeof arr[0]; int a = 8, b = 16; cout << countTriplets(arr, n, a, b) << endl; return 0;}
// Java program to count triplets// with sum that lies in given// range [a, b].import java.util.*; class GFG{ // Function to count tripletspublic static int countTriplets(int []arr, int n, int a, int b){ // Initialize result int ans = 0; // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for the // third number for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) {ans++;} } } } return ans;} // Driver Codepublic static void main(String[] args){ int[] arr = { 2, 7, 5, 3, 8, 4, 1, 9 }; int n = arr.length; int a = 8, b = 16; System.out.println("" + countTriplets(arr, n, a, b));}} // This code is contributed// by Harshit Saini
# Python3 program to count# triplets with sum that# lies in given range [a, b]. # Function to count tripletsdef countTriplets(arr, n, a, b): # Initialize result ans = 0 # Fix the first # element as A[i] for i in range(0, n - 2): # Fix the second # element as A[j] for j in range(i + 1, n - 1): # Now look for # the third number for k in range(j + 1, n): if ((arr[i] + arr[j] + arr[k] >= a) and (arr[i] + arr[j] + arr[k] <= b)): ans += 1 return ans # Driver codeif __name__ == "__main__": arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ] n = len(arr) a = 8; b = 16 print(countTriplets(arr, n, a, b)) # This code is contributed# by Harshit Saini
// C# program to count triplets// with sum that lies in given// range [a, b].using System; class GFG{ // Function to count tripletspublic static int countTriplets(int []arr, int n, int a, int b){ // Initialize result int ans = 0; // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for the // third number for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) {ans++;} } } } return ans;} // Driver Codepublic static void Main(){ int[] arr = {2, 7, 5, 3, 8, 4, 1, 9}; int n = arr.Length; int a = 8, b = 16; Console.WriteLine("" + countTriplets(arr, n, a, b));}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to count triplets with// sum that lies in given range [a, b]. // Function to count tripletsfunction countTriplets($arr, $n, $a, $b){ // Initialize result $ans = 0; // Fix the first element as A[i] for ($i = 0; $i < $n - 2; $i++) { // Fix the second element as A[j] for ($j = $i + 1; $j < $n - 1; $j++) { // Now look for the third number for ($k = $j + 1; $k < $n; $k++) if ($arr[$i] + $arr[$j] + $arr[$k] >= $a && $arr[$i] + $arr[$j] + $arr[$k] <= $b) $ans++; } } return $ans;} // Driver Code$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );$n = sizeof($arr);$a = 8; $b = 16;echo countTriplets($arr, $n, $a, $b) . "\n"; // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // Javascript program to count triplets with// sum that lies in given range [a, b]. // Function to count tripletsfunction countTriplets( arr, n, a, b){ // Initialize result var ans = 0; // Fix the first element as A[i] for (var i = 0; i < n - 2; i++) { // Fix the second element as A[j] for (var j = i + 1; j < n - 1; j++) { // Now look for the third number for (var k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) ans++; } } return ans;} // Driver Codevar arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ];var n = arr.length;var a = 8, b = 16;document.write( countTriplets(arr, n, a, b) ); </script>
36
Time complexity: O(n3)Auxiliary Space: O(1)
An efficient solution is to first find the count of triplets having a sum less than or equal to upper limit b in the range [a, b]. This count of triplets will also include triplets having a sum less than the lower limit a. Subtract the count of triplets having a sum less than a. The final result is the count of triplets having a sum in the range [a, b]. The algorithm is as follows:
Find count of triplets having a sum less than or equal to b. Let this count be x.
Find count of triplets having a sum less than a. Let this count be y.
Final result is x-y.
To find the count of triplets having a sum less than or equal to the given value, refer Count triplets with sum smaller than a given value Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count triplets with// sum that lies in given range [a, b].#include <bits/stdc++.h> using namespace std; // Function to find count of triplets having// sum less than or equal to val.int countTripletsLessThan(int arr[], int n, int val){ // sort the input array. sort(arr, arr + n); // Initialize result int ans = 0; int j, k; // to store sum int sum; // Fix the first element for (int i = 0; i < n - 2; i++) { // Initialize other two elements as // corner elements of subarray arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or equal // to given value, then add // possible triplets (k-j) to result. else { ans += (k - j); j++; } } } return ans;} // Function to return count of triplets having// sum in range [a, b].int countTriplets(int arr[], int n, int a, int b){ // to store count of triplets. int res; // Find count of triplets having sum less // than or equal to b and subtract count // of triplets having sum less than or // equal to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res;} // Driver Codeint main(){ int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 }; int n = sizeof arr / sizeof arr[0]; int a = 8, b = 16; cout << countTriplets(arr, n, a, b) << endl; return 0;}
// Java program to count triplets// with sum that lies in given// range [a, b].import java.util.*; class GFG{// Function to find count of// triplets having sum less// than or equal to val.public static int countTripletsLessThan(int []arr, int n, int val){ // sort the input array. Arrays.sort(arr); // Initialize result int ans = 0; int j, k; // to store sum int sum; // Fix the first element for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the // Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or // equal to given value, // then add possible // triplets (k-j) to result. else { ans += (k - j); j++; } } } return ans;} // Function to return count // of triplets having sum // in range [a, b]. public static int countTriplets(int arr[], int n, int a, int b) { // to store count // of triplets. int res; // Find count of triplets // having sum less than or // equal to b and subtract // count of triplets having // sum less than or equal // to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res; } // Driver Codepublic static void main(String[] args){ int[] arr = {2, 7, 5, 3, 8, 4, 1, 9}; int n = arr.length; int a = 8, b = 16; System.out.println("" + countTriplets(arr, n, a, b));}} // This code is contributed// by Harshit Saini
# Python program to count# triplets with sum that# lies in given range [a, b]. # Function to find count of# triplets having sum less# than or equal to val.def countTripletsLessThan(arr, n, val): # sort the input array. arr.sort() # Initialize result ans = 0 j = 0; k = 0 # to store sum sum = 0 # Fix the first element for i in range(0,n-2): # Initialize other two # elements as corner # elements of subarray # arr[j+1..k] j = i + 1 k = n - 1 # Use Meet in the # Middle concept. while j != k : sum = arr[i] + arr[j] + arr[k] # If sum of current triplet # is greater, then to reduce it # decrease k. if sum > val: k-=1 # If sum is less than or # equal to given value, # then add possible # triplets (k-j) to result. else : ans += (k - j) j += 1 return ans # Function to return# count of triplets having# sum in range [a, b].def countTriplets(arr, n, a, b): # to store count of triplets. res = 0 # Find count of triplets # having sum less than or # equal to b and subtract # count of triplets having # sum less than or equal to a-1. res = (countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1)) return res # Driver codeif __name__ == "__main__": arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ] n = len(arr) a = 8; b = 16 print(countTriplets(arr, n, a, b)) # This code is contributed by# Harshit Saini
// C# program to count triplets// with sum that lies in given// range [a, b].using System; class GFG{// Function to find count of// triplets having sum less// than or equal to val.public static int countTripletsLessThan(int[] arr, int n, int val){ // sort the input array. Array.Sort(arr); // Initialize result int ans = 0; int j, k; // to store sum int sum; // Fix the first element for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the // Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or // equal to given value, // then add possible // triplets (k-j) to result. else { ans += (k - j); j++; } } } return ans;} // Function to return count // of triplets having sum // in range [a, b]. public static int countTriplets(int[] arr, int n, int a, int b) { // to store count // of triplets. int res; // Find count of triplets // having sum less than or // equal to b and subtract // count of triplets having // sum less than or equal // to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res; } // Driver Codepublic static void Main(){ int[] arr = {2, 7, 5, 3, 8, 4, 1, 9}; int n = arr.Length; int a = 8, b = 16; Console.WriteLine("" + countTriplets(arr, n, a, b));}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to count triplets with// sum that lies in given range [a, b]. // Function to find count of triplets// having sum less than or equal to val.function countTripletsLessThan($arr, $n, $val){ // sort the input array. sort($arr); // Initialize result $ans = 0; // to store sum $sum; // Fix the first element for ($i = 0; $i < $n - 2; $i++) { // Initialize other two elements as // corner elements of subarray arr[j+1..k] $j = $i + 1; $k = $n - 1; // Use Meet in the Middle concept. while ($j != $k) { $sum = $arr[$i] + $arr[$j] + $arr[$k]; // If sum of current triplet is greater, // then to reduce it decrease k. if ($sum > $val) $k--; // If sum is less than or equal // to given value, then add possible // triplets (k-j) to result. else { $ans += ($k - $j); $j++; } } } return $ans;} // Function to return count of triplets// having sum in range [a, b].function countTriplets($arr, $n, $a, $b){ // to store count of triplets. $res; // Find count of triplets having sum less // than or equal to b and subtract count // of triplets having sum less than or // equal to a-1. $res = countTripletsLessThan($arr, $n, $b) - countTripletsLessThan($arr, $n, $a - 1); return $res;} // Driver Code$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );$n = sizeof($arr);$a = 8;$b = 16;echo countTriplets($arr, $n, $a, $b), "\n"; // This code is contributed by Sachin?>
<script> // JavaScript program to count triplets // with sum that lies in given // range [a, b]. // Function to find count of // triplets having sum less // than or equal to val. function countTripletsLessThan(arr, n, val) { // sort the input array. arr.sort(); // Initialize result var ans = 0; var j, k; // to store sum var sum; // Fix the first element for (var i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the // Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or // equal to given value, // then add possible // triplets (k-j) to result. else { ans += k - j; j++; } } } return ans; } // Function to return count // of triplets having sum // in range [a, b]. function countTriplets(arr, n, a, b) { // to store count // of triplets. var res; // Find count of triplets // having sum less than or // equal to b and subtract // count of triplets having // sum less than or equal // to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res; } // Driver Code var arr = [2, 7, 5, 3, 8, 4, 1, 9]; var n = arr.length; var a = 8, b = 16; document.write("" + countTriplets(arr, n, a, b)); </script>
36
Time complexity: O(n2) Auxiliary space: O(1)
Harshit Saini
Akanksha_Rai
Sach_Code
noob2000
rdtank
pankajsharmagfg
Arrays
Sorting Quiz
STL
Algorithms
Sorting
Arrays
Sorting
STL
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to write a Pseudo Code?
|
[
{
"code": null,
"e": 25172,
"s": 25144,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25317,
"s": 25172,
"text": "Given an array of distinct integers and a range [a, b], the task is to count the number of triplets having a sum in the range [a, b].Examples: "
},
{
"code": null,
"e": 25527,
"s": 25317,
"text": "Input : arr[] = {8, 3, 5, 2}\n range = [7, 11]\nOutput : 1\nThere is only one triplet {2, 3, 5}\nhaving sum 10 in range [7, 11].\n\nInput : arr[] = {2, 7, 5, 3, 8, 4, 1, 9}\n range = [8, 16]\nOutput : 36"
},
{
"code": null,
"e": 25754,
"s": 25529,
"text": "A naive approach is to run three loops to consider all the triplets one by one. Find the sum of each triplet and increment the count if the sum lies in a given range [a, b].Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25758,
"s": 25754,
"text": "C++"
},
{
"code": null,
"e": 25763,
"s": 25758,
"text": "Java"
},
{
"code": null,
"e": 25771,
"s": 25763,
"text": "Python3"
},
{
"code": null,
"e": 25774,
"s": 25771,
"text": "C#"
},
{
"code": null,
"e": 25778,
"s": 25774,
"text": "PHP"
},
{
"code": null,
"e": 25789,
"s": 25778,
"text": "Javascript"
},
{
"code": "// C++ program to count triplets with// sum that lies in given range [a, b].#include <bits/stdc++.h> using namespace std; // Function to count tripletsint countTriplets(int arr[], int n, int a, int b){ // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for the third number for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) ans++; } } return ans;} // Driver Codeint main(){ int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 }; int n = sizeof arr / sizeof arr[0]; int a = 8, b = 16; cout << countTriplets(arr, n, a, b) << endl; return 0;}",
"e": 26632,
"s": 25789,
"text": null
},
{
"code": "// Java program to count triplets// with sum that lies in given// range [a, b].import java.util.*; class GFG{ // Function to count tripletspublic static int countTriplets(int []arr, int n, int a, int b){ // Initialize result int ans = 0; // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for the // third number for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) {ans++;} } } } return ans;} // Driver Codepublic static void main(String[] args){ int[] arr = { 2, 7, 5, 3, 8, 4, 1, 9 }; int n = arr.length; int a = 8, b = 16; System.out.println(\"\" + countTriplets(arr, n, a, b));}} // This code is contributed// by Harshit Saini",
"e": 27674,
"s": 26632,
"text": null
},
{
"code": "# Python3 program to count# triplets with sum that# lies in given range [a, b]. # Function to count tripletsdef countTriplets(arr, n, a, b): # Initialize result ans = 0 # Fix the first # element as A[i] for i in range(0, n - 2): # Fix the second # element as A[j] for j in range(i + 1, n - 1): # Now look for # the third number for k in range(j + 1, n): if ((arr[i] + arr[j] + arr[k] >= a) and (arr[i] + arr[j] + arr[k] <= b)): ans += 1 return ans # Driver codeif __name__ == \"__main__\": arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ] n = len(arr) a = 8; b = 16 print(countTriplets(arr, n, a, b)) # This code is contributed# by Harshit Saini",
"e": 28486,
"s": 27674,
"text": null
},
{
"code": "// C# program to count triplets// with sum that lies in given// range [a, b].using System; class GFG{ // Function to count tripletspublic static int countTriplets(int []arr, int n, int a, int b){ // Initialize result int ans = 0; // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for the // third number for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) {ans++;} } } } return ans;} // Driver Codepublic static void Main(){ int[] arr = {2, 7, 5, 3, 8, 4, 1, 9}; int n = arr.Length; int a = 8, b = 16; Console.WriteLine(\"\" + countTriplets(arr, n, a, b));}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 29559,
"s": 28486,
"text": null
},
{
"code": "<?php// PHP program to count triplets with// sum that lies in given range [a, b]. // Function to count tripletsfunction countTriplets($arr, $n, $a, $b){ // Initialize result $ans = 0; // Fix the first element as A[i] for ($i = 0; $i < $n - 2; $i++) { // Fix the second element as A[j] for ($j = $i + 1; $j < $n - 1; $j++) { // Now look for the third number for ($k = $j + 1; $k < $n; $k++) if ($arr[$i] + $arr[$j] + $arr[$k] >= $a && $arr[$i] + $arr[$j] + $arr[$k] <= $b) $ans++; } } return $ans;} // Driver Code$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );$n = sizeof($arr);$a = 8; $b = 16;echo countTriplets($arr, $n, $a, $b) . \"\\n\"; // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 30377,
"s": 29559,
"text": null
},
{
"code": "<script> // Javascript program to count triplets with// sum that lies in given range [a, b]. // Function to count tripletsfunction countTriplets( arr, n, a, b){ // Initialize result var ans = 0; // Fix the first element as A[i] for (var i = 0; i < n - 2; i++) { // Fix the second element as A[j] for (var j = i + 1; j < n - 1; j++) { // Now look for the third number for (var k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] >= a && arr[i] + arr[j] + arr[k] <= b) ans++; } } return ans;} // Driver Codevar arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ];var n = arr.length;var a = 8, b = 16;document.write( countTriplets(arr, n, a, b) ); </script>",
"e": 31134,
"s": 30377,
"text": null
},
{
"code": null,
"e": 31137,
"s": 31134,
"text": "36"
},
{
"code": null,
"e": 31184,
"s": 31139,
"text": "Time complexity: O(n3)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31571,
"s": 31184,
"text": "An efficient solution is to first find the count of triplets having a sum less than or equal to upper limit b in the range [a, b]. This count of triplets will also include triplets having a sum less than the lower limit a. Subtract the count of triplets having a sum less than a. The final result is the count of triplets having a sum in the range [a, b]. The algorithm is as follows: "
},
{
"code": null,
"e": 31653,
"s": 31571,
"text": "Find count of triplets having a sum less than or equal to b. Let this count be x."
},
{
"code": null,
"e": 31723,
"s": 31653,
"text": "Find count of triplets having a sum less than a. Let this count be y."
},
{
"code": null,
"e": 31744,
"s": 31723,
"text": "Final result is x-y."
},
{
"code": null,
"e": 31936,
"s": 31744,
"text": "To find the count of triplets having a sum less than or equal to the given value, refer Count triplets with sum smaller than a given value Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31940,
"s": 31936,
"text": "C++"
},
{
"code": null,
"e": 31945,
"s": 31940,
"text": "Java"
},
{
"code": null,
"e": 31953,
"s": 31945,
"text": "Python3"
},
{
"code": null,
"e": 31956,
"s": 31953,
"text": "C#"
},
{
"code": null,
"e": 31960,
"s": 31956,
"text": "PHP"
},
{
"code": null,
"e": 31971,
"s": 31960,
"text": "Javascript"
},
{
"code": "// C++ program to count triplets with// sum that lies in given range [a, b].#include <bits/stdc++.h> using namespace std; // Function to find count of triplets having// sum less than or equal to val.int countTripletsLessThan(int arr[], int n, int val){ // sort the input array. sort(arr, arr + n); // Initialize result int ans = 0; int j, k; // to store sum int sum; // Fix the first element for (int i = 0; i < n - 2; i++) { // Initialize other two elements as // corner elements of subarray arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or equal // to given value, then add // possible triplets (k-j) to result. else { ans += (k - j); j++; } } } return ans;} // Function to return count of triplets having// sum in range [a, b].int countTriplets(int arr[], int n, int a, int b){ // to store count of triplets. int res; // Find count of triplets having sum less // than or equal to b and subtract count // of triplets having sum less than or // equal to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res;} // Driver Codeint main(){ int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 }; int n = sizeof arr / sizeof arr[0]; int a = 8, b = 16; cout << countTriplets(arr, n, a, b) << endl; return 0;}",
"e": 33687,
"s": 31971,
"text": null
},
{
"code": "// Java program to count triplets// with sum that lies in given// range [a, b].import java.util.*; class GFG{// Function to find count of// triplets having sum less// than or equal to val.public static int countTripletsLessThan(int []arr, int n, int val){ // sort the input array. Arrays.sort(arr); // Initialize result int ans = 0; int j, k; // to store sum int sum; // Fix the first element for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the // Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or // equal to given value, // then add possible // triplets (k-j) to result. else { ans += (k - j); j++; } } } return ans;} // Function to return count // of triplets having sum // in range [a, b]. public static int countTriplets(int arr[], int n, int a, int b) { // to store count // of triplets. int res; // Find count of triplets // having sum less than or // equal to b and subtract // count of triplets having // sum less than or equal // to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res; } // Driver Codepublic static void main(String[] args){ int[] arr = {2, 7, 5, 3, 8, 4, 1, 9}; int n = arr.length; int a = 8, b = 16; System.out.println(\"\" + countTriplets(arr, n, a, b));}} // This code is contributed// by Harshit Saini",
"e": 35759,
"s": 33687,
"text": null
},
{
"code": "# Python program to count# triplets with sum that# lies in given range [a, b]. # Function to find count of# triplets having sum less# than or equal to val.def countTripletsLessThan(arr, n, val): # sort the input array. arr.sort() # Initialize result ans = 0 j = 0; k = 0 # to store sum sum = 0 # Fix the first element for i in range(0,n-2): # Initialize other two # elements as corner # elements of subarray # arr[j+1..k] j = i + 1 k = n - 1 # Use Meet in the # Middle concept. while j != k : sum = arr[i] + arr[j] + arr[k] # If sum of current triplet # is greater, then to reduce it # decrease k. if sum > val: k-=1 # If sum is less than or # equal to given value, # then add possible # triplets (k-j) to result. else : ans += (k - j) j += 1 return ans # Function to return# count of triplets having# sum in range [a, b].def countTriplets(arr, n, a, b): # to store count of triplets. res = 0 # Find count of triplets # having sum less than or # equal to b and subtract # count of triplets having # sum less than or equal to a-1. res = (countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1)) return res # Driver codeif __name__ == \"__main__\": arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ] n = len(arr) a = 8; b = 16 print(countTriplets(arr, n, a, b)) # This code is contributed by# Harshit Saini",
"e": 37391,
"s": 35759,
"text": null
},
{
"code": "// C# program to count triplets// with sum that lies in given// range [a, b].using System; class GFG{// Function to find count of// triplets having sum less// than or equal to val.public static int countTripletsLessThan(int[] arr, int n, int val){ // sort the input array. Array.Sort(arr); // Initialize result int ans = 0; int j, k; // to store sum int sum; // Fix the first element for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the // Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or // equal to given value, // then add possible // triplets (k-j) to result. else { ans += (k - j); j++; } } } return ans;} // Function to return count // of triplets having sum // in range [a, b]. public static int countTriplets(int[] arr, int n, int a, int b) { // to store count // of triplets. int res; // Find count of triplets // having sum less than or // equal to b and subtract // count of triplets having // sum less than or equal // to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res; } // Driver Codepublic static void Main(){ int[] arr = {2, 7, 5, 3, 8, 4, 1, 9}; int n = arr.Length; int a = 8, b = 16; Console.WriteLine(\"\" + countTriplets(arr, n, a, b));}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 39450,
"s": 37391,
"text": null
},
{
"code": "<?php// PHP program to count triplets with// sum that lies in given range [a, b]. // Function to find count of triplets// having sum less than or equal to val.function countTripletsLessThan($arr, $n, $val){ // sort the input array. sort($arr); // Initialize result $ans = 0; // to store sum $sum; // Fix the first element for ($i = 0; $i < $n - 2; $i++) { // Initialize other two elements as // corner elements of subarray arr[j+1..k] $j = $i + 1; $k = $n - 1; // Use Meet in the Middle concept. while ($j != $k) { $sum = $arr[$i] + $arr[$j] + $arr[$k]; // If sum of current triplet is greater, // then to reduce it decrease k. if ($sum > $val) $k--; // If sum is less than or equal // to given value, then add possible // triplets (k-j) to result. else { $ans += ($k - $j); $j++; } } } return $ans;} // Function to return count of triplets// having sum in range [a, b].function countTriplets($arr, $n, $a, $b){ // to store count of triplets. $res; // Find count of triplets having sum less // than or equal to b and subtract count // of triplets having sum less than or // equal to a-1. $res = countTripletsLessThan($arr, $n, $b) - countTripletsLessThan($arr, $n, $a - 1); return $res;} // Driver Code$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );$n = sizeof($arr);$a = 8;$b = 16;echo countTriplets($arr, $n, $a, $b), \"\\n\"; // This code is contributed by Sachin?>",
"e": 41101,
"s": 39450,
"text": null
},
{
"code": "<script> // JavaScript program to count triplets // with sum that lies in given // range [a, b]. // Function to find count of // triplets having sum less // than or equal to val. function countTripletsLessThan(arr, n, val) { // sort the input array. arr.sort(); // Initialize result var ans = 0; var j, k; // to store sum var sum; // Fix the first element for (var i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] j = i + 1; k = n - 1; // Use Meet in the // Middle concept. while (j != k) { sum = arr[i] + arr[j] + arr[k]; // If sum of current triplet // is greater, then to reduce it // decrease k. if (sum > val) k--; // If sum is less than or // equal to given value, // then add possible // triplets (k-j) to result. else { ans += k - j; j++; } } } return ans; } // Function to return count // of triplets having sum // in range [a, b]. function countTriplets(arr, n, a, b) { // to store count // of triplets. var res; // Find count of triplets // having sum less than or // equal to b and subtract // count of triplets having // sum less than or equal // to a-1. res = countTripletsLessThan(arr, n, b) - countTripletsLessThan(arr, n, a - 1); return res; } // Driver Code var arr = [2, 7, 5, 3, 8, 4, 1, 9]; var n = arr.length; var a = 8, b = 16; document.write(\"\" + countTriplets(arr, n, a, b)); </script>",
"e": 42994,
"s": 41101,
"text": null
},
{
"code": null,
"e": 42997,
"s": 42994,
"text": "36"
},
{
"code": null,
"e": 43045,
"s": 42999,
"text": "Time complexity: O(n2) Auxiliary space: O(1) "
},
{
"code": null,
"e": 43059,
"s": 43045,
"text": "Harshit Saini"
},
{
"code": null,
"e": 43072,
"s": 43059,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 43082,
"s": 43072,
"text": "Sach_Code"
},
{
"code": null,
"e": 43091,
"s": 43082,
"text": "noob2000"
},
{
"code": null,
"e": 43098,
"s": 43091,
"text": "rdtank"
},
{
"code": null,
"e": 43114,
"s": 43098,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 43121,
"s": 43114,
"text": "Arrays"
},
{
"code": null,
"e": 43134,
"s": 43121,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 43138,
"s": 43134,
"text": "STL"
},
{
"code": null,
"e": 43149,
"s": 43138,
"text": "Algorithms"
},
{
"code": null,
"e": 43157,
"s": 43149,
"text": "Sorting"
},
{
"code": null,
"e": 43164,
"s": 43157,
"text": "Arrays"
},
{
"code": null,
"e": 43172,
"s": 43164,
"text": "Sorting"
},
{
"code": null,
"e": 43176,
"s": 43172,
"text": "STL"
},
{
"code": null,
"e": 43187,
"s": 43176,
"text": "Algorithms"
},
{
"code": null,
"e": 43285,
"s": 43187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43334,
"s": 43285,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 43359,
"s": 43334,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 43410,
"s": 43359,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 43437,
"s": 43410,
"text": "Introduction to Algorithms"
}
] |
MYBATIS - Delete Operation
|
This chapter describes how to delete records from a table using MyBatis.
We have the following STUDENT table in MySQL −
CREATE TABLE details.student(
ID int(10) NOT NULL AUTO_INCREMENT,
NAME varchar(100) NOT NULL,
BRANCH varchar(255) NOT NULL,
PERCENTAGE int(3) NOT NULL,
PHONE int(11) NOT NULL,
EMAIL varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
);
Assume, this table has two records as −
mysql> select * from STUDENT;
+----+----------+--------+------------+-----------+----------------------+
| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |
+----+----------+--------+------------+-----------+----------------------+
| 1 | Mohammad | It | 80 | 900000000 | mohamad123@yahoo.com |
| 2 | shyam | It | 75 | 984800000 | shyam@gmail.com |
+----+----------+--------+------------+-----------+----------------------+
2 rows in set (0.00 sec)
To perform delete operation, you do not need to modify Student.java file. Let us keep it as it was in the last chapter.
public class Student {
private int id;
private String name;
private String branch;
private int percentage;
private int phone;
private String email;
public Student(int id, String name, String branch, int percentage, int phone, String email) {
super();
this.id = id;
this.name = name;
this.setBranch(branch);
this.setPercentage(percentage);
this.phone = phone;
this.email = email;
}
public Student() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public int getPercentage() {
return percentage;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("Id = ").append(id).append(" - ");
sb.append("Name = ").append(name).append(" - ");
sb.append("Branch = ").append(branch).append(" - ");
sb.append("Percentage = ").append(percentage).append(" - ");
sb.append("Phone = ").append(phone).append(" - ");
sb.append("Email = ").append(email);
return sb.toString();
}
}
To define SQL mapping statement using MyBatis, we would use <delete> tag in Student.xml and inside this tag definition, we would define an "id" which will be used in mybatisDelete.java file for executing SQL DELETE query on database.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace = "Student">
<resultMap id = "result" type = "Student">
<result property = "id" column = "ID"/>
</resultMap>
<delete id = "deleteById" parameterType = "int">
DELETE from STUDENT WHERE ID = #{id};
</delete>
</mapper>
This file has application level logic to delete records from the Student table −
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class mybatisDelete {
public static void main(String args[]) throws IOException{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
//Delete operation
session.delete("Student.deleteById", 2);
session.commit();
session.close();
System.out.println("Record deleted successfully");
}
}
Here are the steps to compile and run mybatisDelete.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Student.xml as shown above.
Create Student.xml as shown above.
Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial.
Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial.
Create Student.java as shown above and compile it.
Create Student.java as shown above and compile it.
Create mybatisDelete.java as shown above and compile it.
Create mybatisDelete.java as shown above and compile it.
Execute mybatisDelete binary to run the program.
Execute mybatisDelete binary to run the program.
You would get the following result, and a record with ID = 1 would be deleted from the STUDENT.
Records Read Successfully
If you check the STUDENT table, it should display the following result −
mysql> select * from student;
+----+----------+--------+------------+----------+----------------------+
| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |
+----+----------+--------+------------+----------+----------------------+
| 1 | Mohammad | It | 80 | 90000000 | mohamad123@yahoo.com |
+----+----------+--------+------------+----------+----------------------+
1 row in set (0.00 sec)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1944,
"s": 1871,
"text": "This chapter describes how to delete records from a table using MyBatis."
},
{
"code": null,
"e": 1991,
"s": 1944,
"text": "We have the following STUDENT table in MySQL −"
},
{
"code": null,
"e": 2240,
"s": 1991,
"text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n"
},
{
"code": null,
"e": 2280,
"s": 2240,
"text": "Assume, this table has two records as −"
},
{
"code": null,
"e": 2786,
"s": 2280,
"text": "mysql> select * from STUDENT;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 900000000 | mohamad123@yahoo.com |\n| 2 | shyam | It | 75 | 984800000 | shyam@gmail.com |\n+----+----------+--------+------------+-----------+----------------------+\n2 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 2906,
"s": 2786,
"text": "To perform delete operation, you do not need to modify Student.java file. Let us keep it as it was in the last chapter."
},
{
"code": null,
"e": 4601,
"s": 2906,
"text": "public class Student {\n\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.setBranch(branch);\n this.setPercentage(percentage);\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\n\t\n public String toString(){\n StringBuilder sb = new StringBuilder();\n\t\t\n sb.append(\"Id = \").append(id).append(\" - \");\n sb.append(\"Name = \").append(name).append(\" - \");\n sb.append(\"Branch = \").append(branch).append(\" - \");\n sb.append(\"Percentage = \").append(percentage).append(\" - \");\n sb.append(\"Phone = \").append(phone).append(\" - \");\n sb.append(\"Email = \").append(email);\n\t\t\n return sb.toString();\n }\n\t\n}"
},
{
"code": null,
"e": 4835,
"s": 4601,
"text": "To define SQL mapping statement using MyBatis, we would use <delete> tag in Student.xml and inside this tag definition, we would define an \"id\" which will be used in mybatisDelete.java file for executing SQL DELETE query on database."
},
{
"code": null,
"e": 5261,
"s": 4835,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\t \n </resultMap>\n\t\n <delete id = \"deleteById\" parameterType = \"int\">\n DELETE from STUDENT WHERE ID = #{id};\n </delete>\n \t\n</mapper>"
},
{
"code": null,
"e": 5342,
"s": 5261,
"text": "This file has application level logic to delete records from the Student table −"
},
{
"code": null,
"e": 6122,
"s": 5342,
"text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisDelete { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession(); \n\t \n //Delete operation\n session.delete(\"Student.deleteById\", 2); \n session.commit();\n session.close(); \n System.out.println(\"Record deleted successfully\");\n\t\t\t\n }\n \n}"
},
{
"code": null,
"e": 6286,
"s": 6122,
"text": "Here are the steps to compile and run mybatisDelete.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 6321,
"s": 6286,
"text": "Create Student.xml as shown above."
},
{
"code": null,
"e": 6356,
"s": 6321,
"text": "Create Student.xml as shown above."
},
{
"code": null,
"e": 6450,
"s": 6356,
"text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial."
},
{
"code": null,
"e": 6544,
"s": 6450,
"text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial."
},
{
"code": null,
"e": 6595,
"s": 6544,
"text": "Create Student.java as shown above and compile it."
},
{
"code": null,
"e": 6646,
"s": 6595,
"text": "Create Student.java as shown above and compile it."
},
{
"code": null,
"e": 6703,
"s": 6646,
"text": "Create mybatisDelete.java as shown above and compile it."
},
{
"code": null,
"e": 6760,
"s": 6703,
"text": "Create mybatisDelete.java as shown above and compile it."
},
{
"code": null,
"e": 6809,
"s": 6760,
"text": "Execute mybatisDelete binary to run the program."
},
{
"code": null,
"e": 6858,
"s": 6809,
"text": "Execute mybatisDelete binary to run the program."
},
{
"code": null,
"e": 6954,
"s": 6858,
"text": "You would get the following result, and a record with ID = 1 would be deleted from the STUDENT."
},
{
"code": null,
"e": 6981,
"s": 6954,
"text": "Records Read Successfully\n"
},
{
"code": null,
"e": 7054,
"s": 6981,
"text": "If you check the STUDENT table, it should display the following result −"
},
{
"code": null,
"e": 7479,
"s": 7054,
"text": "mysql> select * from student;\n+----+----------+--------+------------+----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+----------+----------------------+\n| 1 | Mohammad | It | 80 | 90000000 | mohamad123@yahoo.com |\n+----+----------+--------+------------+----------+----------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 7486,
"s": 7479,
"text": " Print"
},
{
"code": null,
"e": 7497,
"s": 7486,
"text": " Add Notes"
}
] |
How to find leap year or not in android using year API class?
|
This example demonstrate about How to find leap year or not in android using year API class.
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"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Local Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show current year is leap year or not.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.Year;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Year year = Year.now();
String leap;
if(year.isLeap()) {
leap = " is leap year";
} else {
leap = " is not leap year";
}
textView.setText(String.valueOf(year+leap));
}
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it is showing current local year is not a leap year.
Click here to download the project code
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrate about How to find leap year or not in android using year API class."
},
{
"code": null,
"e": 1284,
"s": 1155,
"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": 1349,
"s": 1284,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2126,
"s": 1349,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Local Date\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2210,
"s": 2126,
"text": "In the above code, we have taken textview to show current year is leap year or not."
},
{
"code": null,
"e": 2267,
"s": 2210,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3037,
"s": 2267,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\nimport java.time.Year;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = findViewById(R.id.date);\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n Year year = Year.now();\n String leap;\n if(year.isLeap()) {\n leap = \" is leap year\";\n } else {\n leap = \" is not leap year\";\n }\n textView.setText(String.valueOf(year+leap));\n }\n }\n}"
},
{
"code": null,
"e": 3384,
"s": 3037,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3458,
"s": 3384,
"text": "In the above result, it is showing current local year is not a leap year."
},
{
"code": null,
"e": 3498,
"s": 3458,
"text": "Click here to download the project code"
}
] |
HTTP headers | Strict-Transport-Security
|
05 Nov, 2019
HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps protect websites from malicious activities and informs user agents and web browsers how to handle its connection through a response header. Whenever a website connects through HTTP and then redirects to HTTPS, an opportunity for a man-in-the-middle attack is created and the redirect can lead the users to a malicious website because users first have to communicate with the non-encrypted version of the website. A server implements the HSTS policy by supplying a header over an HTTPS connection which informs the browser to load a site using HTTPS rather than HTTP.
Syntax:
Strict-Transport-Security: max-age=<expire-time>
Strict-Transport-Security: max-age=<expire-time>; includeSubDomains
Strict-Transport-Security: max-age=<expire-time>; preload
Directives:
<expire-time>: This mentions the time in seconds for which the user agent or browser should only access the server in a secure fashion by using HTTP.
includeSubDomains: This directs the browser to apply the rule to all pages and sub-domains of the site as well.
preload: This is necessary for inclusion in most major web browsers’ HSTS preload lists.
Explanation: If a user type in an address bar http://www.geeksforgeeks.com/ or geeksforgeeks.com this will create a chance for a man-in-the-middle attack. The redirect could be exploited to direct visitors to a malicious site instead of the secure version of the original site.
Examples:
Strict-Transport-Security: max-age=3600; includeSubDomains
All pages and subdomains will be HTTPS for a max-age of 1 hour. This blocks access to pages or sub domains that cannot be served over HTTPS.
Strict-Transport-Security: max-age=7200; includeSubDomains; preload
All present and future sub-domains will be HTTPS for a max-age of 2 hour. It also has preload as the suffix which is necessary in most major web browsers’ HSTS pre-load lists.
To check this Strict-Transport-Security in action go to Inspect Element -> Network check the response header for Strict-Transport-Security like below, Strict-Transport-Security is highlighted you can see.Supported Browsers: The following browsers are compatible with HTTP Strict-Transport-Security.
Google Chrome 4.0
Internet Explorer 11.0
Firefox 4.0
Safari 7.0
Opera 12.0
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Nov, 2019"
},
{
"code": null,
"e": 679,
"s": 28,
"text": "HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps protect websites from malicious activities and informs user agents and web browsers how to handle its connection through a response header. Whenever a website connects through HTTP and then redirects to HTTPS, an opportunity for a man-in-the-middle attack is created and the redirect can lead the users to a malicious website because users first have to communicate with the non-encrypted version of the website. A server implements the HSTS policy by supplying a header over an HTTPS connection which informs the browser to load a site using HTTPS rather than HTTP."
},
{
"code": null,
"e": 687,
"s": 679,
"text": "Syntax:"
},
{
"code": null,
"e": 736,
"s": 687,
"text": "Strict-Transport-Security: max-age=<expire-time>"
},
{
"code": null,
"e": 804,
"s": 736,
"text": "Strict-Transport-Security: max-age=<expire-time>; includeSubDomains"
},
{
"code": null,
"e": 862,
"s": 804,
"text": "Strict-Transport-Security: max-age=<expire-time>; preload"
},
{
"code": null,
"e": 874,
"s": 862,
"text": "Directives:"
},
{
"code": null,
"e": 1024,
"s": 874,
"text": "<expire-time>: This mentions the time in seconds for which the user agent or browser should only access the server in a secure fashion by using HTTP."
},
{
"code": null,
"e": 1136,
"s": 1024,
"text": "includeSubDomains: This directs the browser to apply the rule to all pages and sub-domains of the site as well."
},
{
"code": null,
"e": 1225,
"s": 1136,
"text": "preload: This is necessary for inclusion in most major web browsers’ HSTS preload lists."
},
{
"code": null,
"e": 1503,
"s": 1225,
"text": "Explanation: If a user type in an address bar http://www.geeksforgeeks.com/ or geeksforgeeks.com this will create a chance for a man-in-the-middle attack. The redirect could be exploited to direct visitors to a malicious site instead of the secure version of the original site."
},
{
"code": null,
"e": 1513,
"s": 1503,
"text": "Examples:"
},
{
"code": null,
"e": 1572,
"s": 1513,
"text": "Strict-Transport-Security: max-age=3600; includeSubDomains"
},
{
"code": null,
"e": 1713,
"s": 1572,
"text": "All pages and subdomains will be HTTPS for a max-age of 1 hour. This blocks access to pages or sub domains that cannot be served over HTTPS."
},
{
"code": null,
"e": 1782,
"s": 1713,
"text": "Strict-Transport-Security: max-age=7200; includeSubDomains; preload\n"
},
{
"code": null,
"e": 1958,
"s": 1782,
"text": "All present and future sub-domains will be HTTPS for a max-age of 2 hour. It also has preload as the suffix which is necessary in most major web browsers’ HSTS pre-load lists."
},
{
"code": null,
"e": 2257,
"s": 1958,
"text": "To check this Strict-Transport-Security in action go to Inspect Element -> Network check the response header for Strict-Transport-Security like below, Strict-Transport-Security is highlighted you can see.Supported Browsers: The following browsers are compatible with HTTP Strict-Transport-Security."
},
{
"code": null,
"e": 2275,
"s": 2257,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 2298,
"s": 2275,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 2310,
"s": 2298,
"text": "Firefox 4.0"
},
{
"code": null,
"e": 2321,
"s": 2310,
"text": "Safari 7.0"
},
{
"code": null,
"e": 2332,
"s": 2321,
"text": "Opera 12.0"
},
{
"code": null,
"e": 2345,
"s": 2332,
"text": "HTTP-headers"
},
{
"code": null,
"e": 2352,
"s": 2345,
"text": "Picked"
},
{
"code": null,
"e": 2369,
"s": 2352,
"text": "Web Technologies"
}
] |
How do I copy items from list to list without foreach in C#?
|
The List<T> is a collection of strongly typed objects that can be accessed by index
and having methods for sorting, searching, and modifying list.
It is the generic version of the ArrayList that comes under System.Collection.Generic
namespace.
List<T> equivalent of the ArrayList, which implements IList<T>.
It comes under System.Collection.Generic namespace.
List<T>can contain elements of the specified type. It provides compile-time type
checking and doesn't perform boxing-unboxing because it is generic.
Elements can be added using the Add(), AddRange() methods or collection-initializer
syntax.
Elements can be accessed by passing an index e.g. myList[0]. Indexes start from zero.
List<T> performs faster and less error-prone than the ArrayList.
A list can be accessed by an index, a for/foreach loop, and using LINQ queries.
Indexes of a list start from zero.
Pass an index in the square brackets to access individual list items, same as array. Use
a foreach or for loop to iterate a List<T> collection.
class Program{
public static void Main(){
List<int>originalList=new List<int>(){1,2,3,4,5,7,8,9};
List<Int32>copy = new List<Int32>(originalList);
foreach (var item in copy){
System.Console.WriteLine(item);
}
Console.ReadLine();
}
}
1
2
3
4
5
7
8
9
class Program{
public static void Main(){
List<int>originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 };
List<Int32> copy = originalList.ToList();
foreach (var item in copy){
System.Console.WriteLine(item);
}
Console.ReadLine();
}
}
1
2
3
4
5
7
8
9
class Program{
public static void Main(){
List<int> originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 };
List<Int32> copy = originalList.GetRange(0, 3);
foreach (var item in copy){
System.Console.WriteLine(item);
}
Console.ReadLine();
}
}
1
2
3
|
[
{
"code": null,
"e": 1431,
"s": 1187,
"text": "The List<T> is a collection of strongly typed objects that can be accessed by index\nand having methods for sorting, searching, and modifying list.\nIt is the generic version of the ArrayList that comes under System.Collection.Generic\nnamespace."
},
{
"code": null,
"e": 1495,
"s": 1431,
"text": "List<T> equivalent of the ArrayList, which implements IList<T>."
},
{
"code": null,
"e": 1547,
"s": 1495,
"text": "It comes under System.Collection.Generic namespace."
},
{
"code": null,
"e": 1696,
"s": 1547,
"text": "List<T>can contain elements of the specified type. It provides compile-time type\nchecking and doesn't perform boxing-unboxing because it is generic."
},
{
"code": null,
"e": 1788,
"s": 1696,
"text": "Elements can be added using the Add(), AddRange() methods or collection-initializer\nsyntax."
},
{
"code": null,
"e": 1939,
"s": 1788,
"text": "Elements can be accessed by passing an index e.g. myList[0]. Indexes start from zero.\nList<T> performs faster and less error-prone than the ArrayList."
},
{
"code": null,
"e": 2054,
"s": 1939,
"text": "A list can be accessed by an index, a for/foreach loop, and using LINQ queries.\nIndexes of a list start from zero."
},
{
"code": null,
"e": 2198,
"s": 2054,
"text": "Pass an index in the square brackets to access individual list items, same as array. Use\na foreach or for loop to iterate a List<T> collection."
},
{
"code": null,
"e": 2476,
"s": 2198,
"text": "class Program{\n public static void Main(){\n List<int>originalList=new List<int>(){1,2,3,4,5,7,8,9};\n List<Int32>copy = new List<Int32>(originalList);\n foreach (var item in copy){\n System.Console.WriteLine(item);\n }\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 2492,
"s": 2476,
"text": "1\n2\n3\n4\n5\n7\n8\n9"
},
{
"code": null,
"e": 2775,
"s": 2492,
"text": "class Program{\n public static void Main(){\n List<int>originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 };\n List<Int32> copy = originalList.ToList();\n foreach (var item in copy){\n System.Console.WriteLine(item);\n }\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 2791,
"s": 2775,
"text": "1\n2\n3\n4\n5\n7\n8\n9"
},
{
"code": null,
"e": 3081,
"s": 2791,
"text": "class Program{\n public static void Main(){\n List<int> originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 };\n List<Int32> copy = originalList.GetRange(0, 3);\n foreach (var item in copy){\n System.Console.WriteLine(item);\n }\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 3087,
"s": 3081,
"text": "1\n2\n3"
}
] |
Bash shell script to find out the largest value from given command line arguments
|
05 Sep, 2019
Write a shell script to find out the largest value from the given number of command-line arguments.
Example:
Special variables in bash:
$@- All arguments.
$#- Number of arguments.
$0- Filename.
$1, $2, $3, $4 ... - Specific arguments.
Approach
If the number of arguments is 0, end the program.
If not zero, thenInitialize a variable maxEle with first argument.Loop over all the arguments. Compare each argument with maxEle and update it if the argument is greater.
Initialize a variable maxEle with first argument.
Loop over all the arguments. Compare each argument with maxEle and update it if the argument is greater.
#Check if the number of arguments passed is zeroif [ "$#" = 0 ]then #Script exits if no #arguments passed echo "No arguments passed." exit 1fi #Initialize maxEle with #the first argumentmaxEle=$1 #Loop that compares maxEle with the #passed arguments and updates itfor arg in "$@"do if [ "$arg" -gt "$maxEle" ] then maxEle=$arg fidoneecho "Largest value among the arguments passed is: $maxEle"
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "Write a shell script to find out the largest value from the given number of command-line arguments."
},
{
"code": null,
"e": 137,
"s": 128,
"text": "Example:"
},
{
"code": null,
"e": 164,
"s": 137,
"text": "Special variables in bash:"
},
{
"code": null,
"e": 264,
"s": 164,
"text": "$@- All arguments.\n$#- Number of arguments.\n$0- Filename.\n$1, $2, $3, $4 ... - Specific arguments.\n"
},
{
"code": null,
"e": 273,
"s": 264,
"text": "Approach"
},
{
"code": null,
"e": 323,
"s": 273,
"text": "If the number of arguments is 0, end the program."
},
{
"code": null,
"e": 494,
"s": 323,
"text": "If not zero, thenInitialize a variable maxEle with first argument.Loop over all the arguments. Compare each argument with maxEle and update it if the argument is greater."
},
{
"code": null,
"e": 544,
"s": 494,
"text": "Initialize a variable maxEle with first argument."
},
{
"code": null,
"e": 649,
"s": 544,
"text": "Loop over all the arguments. Compare each argument with maxEle and update it if the argument is greater."
},
{
"code": "#Check if the number of arguments passed is zeroif [ \"$#\" = 0 ]then #Script exits if no #arguments passed echo \"No arguments passed.\" exit 1fi #Initialize maxEle with #the first argumentmaxEle=$1 #Loop that compares maxEle with the #passed arguments and updates itfor arg in \"$@\"do if [ \"$arg\" -gt \"$maxEle\" ] then maxEle=$arg fidoneecho \"Largest value among the arguments passed is: $maxEle\"",
"e": 1072,
"s": 649,
"text": null
},
{
"code": null,
"e": 1083,
"s": 1072,
"text": "Linux-Unix"
}
] |
JavaScript | Timer
|
19 Feb, 2019
Prerequisites:
GetMinutes()
GetSeconds()
SetInterval() Method
In this post, a timer has been shown that shows the countdown and its colour/message gets changed after every specific period of time.
Syntax:
setTimeout(function, milliseconds, parameter1, ...)
Parameter: It accept some parameters which are specified below-
function: It is the function that will be executed.
milliseconds: It is the number of milliseconds to wait before executing the code. It is optional and its default value is zero(0).
parameter1: It is additional parameters to pass to the function and it is optional.
Return Value: It returns a number representing the ID value of the timer that is set.
JavaScript code that set the timer of 2 minutes and when the times up the Page alert “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
JavaScript code to implement the timer:
<html> <head> <script> //set minutes var mins = 2; //calculate the seconds var secs = mins * 60; //countdown function is evoked when page is loaded function countdown() { setTimeout('Decrement()', 60); } //Decrement function decrement the value. function Decrement() { if (document.getElementById) { minutes = document.getElementById("minutes"); seconds = document.getElementById("seconds"); //if less than a minute remaining //Display only seconds value. if (seconds < 59) { seconds.value = secs; } //Display both minutes and seconds //getminutes and getseconds is used to //get minutes and seconds else { minutes.value = getminutes(); seconds.value = getseconds(); } //when less than a minute remaining //colour of the minutes and seconds //changes to red if (mins < 1) { minutes.style.color = "red"; seconds.style.color = "red"; } //if seconds becomes zero, //then page alert time up if (mins < 0) { alert('time up'); minutes.value = 0; seconds.value = 0; } //if seconds > 0 then seconds is decremented else { secs--; setTimeout('Decrement()', 1000); } } } function getminutes() { //minutes is seconds divided by 60, rounded down mins = Math.floor(secs / 60); return mins; } function getseconds() { //take minutes remaining (as seconds) away //from total seconds remaining return secs - Math.round(mins * 60); } </script></head><!-- onload function is evoke when page is load --><!--countdown function is called when page is loaded --> <body onload="countdown();"> <div> Time Left :: <input id="minutes" type="text" style="width: 10px; border: none; font-size: 16px; font-weight: bold; color: black;"><font size="5"> : </font> <input id="seconds" type="text" style="width: 20px; border: none; font-size: 16px; font-weight: bold; color: black;"> </div></body> </html>
Output:After clicking on the run button-After some time-When Less than 1 minute is left-When timer is up-
javascript-basics
javascript-functions
JavaScript-Misc
JavaScript
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
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 69,
"s": 54,
"text": "Prerequisites:"
},
{
"code": null,
"e": 82,
"s": 69,
"text": "GetMinutes()"
},
{
"code": null,
"e": 95,
"s": 82,
"text": "GetSeconds()"
},
{
"code": null,
"e": 116,
"s": 95,
"text": "SetInterval() Method"
},
{
"code": null,
"e": 251,
"s": 116,
"text": "In this post, a timer has been shown that shows the countdown and its colour/message gets changed after every specific period of time."
},
{
"code": null,
"e": 259,
"s": 251,
"text": "Syntax:"
},
{
"code": null,
"e": 312,
"s": 259,
"text": "setTimeout(function, milliseconds, parameter1, ...)\n"
},
{
"code": null,
"e": 376,
"s": 312,
"text": "Parameter: It accept some parameters which are specified below-"
},
{
"code": null,
"e": 428,
"s": 376,
"text": "function: It is the function that will be executed."
},
{
"code": null,
"e": 559,
"s": 428,
"text": "milliseconds: It is the number of milliseconds to wait before executing the code. It is optional and its default value is zero(0)."
},
{
"code": null,
"e": 643,
"s": 559,
"text": "parameter1: It is additional parameters to pass to the function and it is optional."
},
{
"code": null,
"e": 729,
"s": 643,
"text": "Return Value: It returns a number representing the ID value of the timer that is set."
},
{
"code": null,
"e": 936,
"s": 729,
"text": "JavaScript code that set the timer of 2 minutes and when the times up the Page alert “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds."
},
{
"code": null,
"e": 976,
"s": 936,
"text": "JavaScript code to implement the timer:"
},
{
"code": "<html> <head> <script> //set minutes var mins = 2; //calculate the seconds var secs = mins * 60; //countdown function is evoked when page is loaded function countdown() { setTimeout('Decrement()', 60); } //Decrement function decrement the value. function Decrement() { if (document.getElementById) { minutes = document.getElementById(\"minutes\"); seconds = document.getElementById(\"seconds\"); //if less than a minute remaining //Display only seconds value. if (seconds < 59) { seconds.value = secs; } //Display both minutes and seconds //getminutes and getseconds is used to //get minutes and seconds else { minutes.value = getminutes(); seconds.value = getseconds(); } //when less than a minute remaining //colour of the minutes and seconds //changes to red if (mins < 1) { minutes.style.color = \"red\"; seconds.style.color = \"red\"; } //if seconds becomes zero, //then page alert time up if (mins < 0) { alert('time up'); minutes.value = 0; seconds.value = 0; } //if seconds > 0 then seconds is decremented else { secs--; setTimeout('Decrement()', 1000); } } } function getminutes() { //minutes is seconds divided by 60, rounded down mins = Math.floor(secs / 60); return mins; } function getseconds() { //take minutes remaining (as seconds) away //from total seconds remaining return secs - Math.round(mins * 60); } </script></head><!-- onload function is evoke when page is load --><!--countdown function is called when page is loaded --> <body onload=\"countdown();\"> <div> Time Left :: <input id=\"minutes\" type=\"text\" style=\"width: 10px; border: none; font-size: 16px; font-weight: bold; color: black;\"><font size=\"5\"> : </font> <input id=\"seconds\" type=\"text\" style=\"width: 20px; border: none; font-size: 16px; font-weight: bold; color: black;\"> </div></body> </html>",
"e": 3622,
"s": 976,
"text": null
},
{
"code": null,
"e": 3728,
"s": 3622,
"text": "Output:After clicking on the run button-After some time-When Less than 1 minute is left-When timer is up-"
},
{
"code": null,
"e": 3746,
"s": 3728,
"text": "javascript-basics"
},
{
"code": null,
"e": 3767,
"s": 3746,
"text": "javascript-functions"
},
{
"code": null,
"e": 3783,
"s": 3767,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3794,
"s": 3783,
"text": "JavaScript"
},
{
"code": null,
"e": 3892,
"s": 3794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3953,
"s": 3892,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4025,
"s": 3953,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4065,
"s": 4025,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4106,
"s": 4065,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4158,
"s": 4106,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4204,
"s": 4158,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 4246,
"s": 4204,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4300,
"s": 4246,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 4355,
"s": 4300,
"text": "How do you run JavaScript script through the Terminal?"
}
] |
PostgreSQL – DROP COLUMN
|
28 Aug, 2020
PostgreSQL also supports the DROP COLUMN clause in the ALTER TABLE statement to remove one or more columns of a table. When you remove a column from a table, PostgreSQL will automatically remove all of its indexes and constraints involving the column.
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
Now let’s look into an example.
Example:First, we create a few tables (say, books, categories, and publishers ) for demonstration having the below depicted relationships:
We create the above tables using the below statements:
CREATE TABLE publishers (
publisher_id serial PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE categories (
category_id serial PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE books (
book_id serial PRIMARY KEY,
title VARCHAR NOT NULL,
isbn VARCHAR NOT NULL,
published_date DATE NOT NULL,
description VARCHAR,
category_id INT NOT NULL,
publisher_id INT NOT NULL,
FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id),
FOREIGN KEY (category_id) REFERENCES categories (category_id)
);
In addition, we create a view based on the books and publishers tables as follows:
CREATE VIEW book_info AS SELECT
book_id,
title,
isbn,
published_date,
name
FROM
books b
INNER JOIN publishers P ON P .publisher_id = b.publisher_id
ORDER BY
title;
If we want to remove the category_id column of the books table, we use the following statement:
ALTER TABLE books DROP COLUMN category_id;
Now we check the books table using the below statement:
SELECT * FROM books;
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "PostgreSQL also supports the DROP COLUMN clause in the ALTER TABLE statement to remove one or more columns of a table. When you remove a column from a table, PostgreSQL will automatically remove all of its indexes and constraints involving the column."
},
{
"code": null,
"e": 337,
"s": 280,
"text": "Syntax:\nALTER TABLE table_name \nDROP COLUMN column_name;"
},
{
"code": null,
"e": 369,
"s": 337,
"text": "Now let’s look into an example."
},
{
"code": null,
"e": 508,
"s": 369,
"text": "Example:First, we create a few tables (say, books, categories, and publishers ) for demonstration having the below depicted relationships:"
},
{
"code": null,
"e": 563,
"s": 508,
"text": "We create the above tables using the below statements:"
},
{
"code": null,
"e": 1114,
"s": 563,
"text": "CREATE TABLE publishers (\n publisher_id serial PRIMARY KEY,\n name VARCHAR NOT NULL\n);\n\nCREATE TABLE categories (\n category_id serial PRIMARY KEY,\n name VARCHAR NOT NULL\n);\n\nCREATE TABLE books (\n book_id serial PRIMARY KEY,\n title VARCHAR NOT NULL,\n isbn VARCHAR NOT NULL,\n published_date DATE NOT NULL,\n description VARCHAR,\n category_id INT NOT NULL,\n publisher_id INT NOT NULL,\n FOREIGN KEY (publisher_id) REFERENCES publishers (publisher_id),\n FOREIGN KEY (category_id) REFERENCES categories (category_id)\n);"
},
{
"code": null,
"e": 1197,
"s": 1114,
"text": "In addition, we create a view based on the books and publishers tables as follows:"
},
{
"code": null,
"e": 1389,
"s": 1197,
"text": "CREATE VIEW book_info AS SELECT\n book_id,\n title,\n isbn,\n published_date,\n name\nFROM\n books b\nINNER JOIN publishers P ON P .publisher_id = b.publisher_id\nORDER BY\n title;"
},
{
"code": null,
"e": 1485,
"s": 1389,
"text": "If we want to remove the category_id column of the books table, we use the following statement:"
},
{
"code": null,
"e": 1528,
"s": 1485,
"text": "ALTER TABLE books DROP COLUMN category_id;"
},
{
"code": null,
"e": 1584,
"s": 1528,
"text": "Now we check the books table using the below statement:"
},
{
"code": null,
"e": 1605,
"s": 1584,
"text": "SELECT * FROM books;"
},
{
"code": null,
"e": 1613,
"s": 1605,
"text": "Output:"
},
{
"code": null,
"e": 1639,
"s": 1613,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 1650,
"s": 1639,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1748,
"s": 1650,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1775,
"s": 1748,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 1807,
"s": 1775,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 1830,
"s": 1807,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 1868,
"s": 1830,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1908,
"s": 1868,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 1942,
"s": 1908,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 1997,
"s": 1942,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 2021,
"s": 1997,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2045,
"s": 2021,
"text": "PostgreSQL - Copy Table"
}
] |
Intuition of SpanBert
|
11 Sep, 2021
Prerequisite: BERT Model
SpanBERT vs BERT
SpanBERT is an improvement on the BERT model providing improved prediction of spans of text. Unlike BERT, we perform the following steps here i) mask random contiguous spans, rather than random individual tokens. ii) training the model based on tokens at the start and end of the boundary of span (known as Span Boundary Objective) to predict the entire marked spans.
It differs from BERT model in its masking scheme as BERT used to randomly mask tokens in a sequence but here in SpanBERT we mask random contiguous spans of text.
Another difference is that of the training objective. BERT was trained on two objectives (2 loss functions) :
Masked Language Modeling (MLM) — Predicting the mask token on the output
Next Sequence Prediction (NSP) — Predicting if 2 sequences of texts followed each other.
But in SpanBERT, the only thing the model is trained on is the Span Boundary Objective which later contributes to the loss function.
SpanBERT: Implementation
To implement SpanBERT, we build a replica of the BERT model but do certain changes in it so that it can perform better than the original BERT model. It is observed that the BERT model performs much better when only trained on ‘Masked Language Modelling’ alone rather than with ‘Next Sequence Prediction’. Hence, we disregard NSP and tuned the model on Single Sequence baseline while building the replica of BERT model, thereby improving its prediction accuracy.
SpanBERT: Intuition
Fig 1 : Training SpanBERT
Fig 1 shows the training of the SpanBERT model. In the given sentence, the span of words ‘a football championship tournament‘ is masked. The Span Boundary Objective is defined by the x4 and x9 highlighted in blue. This is used to predict each token in the masked span.
Here in Fig 1, a sequence of words ‘a football championship tournament‘ is created and the whole sequence is passed through the encoder block and get the prediction of the masked tokens as output. (x5 to x8)
For example, if we were to predict for the token x6 (i.e. football), below is the equivalent loss (as shown in Eqn(1)) that we would get.
Eqn-(1)
This loss is the summation of losses given by MLM and SBO losses.
Eqn-(2)
Now, the MLM loss is the same as ‘-ve log of likelihood’ or in simpler terms what is the chances of x6 being football.
Eqn-(3)
Then, the SBO loss is depends on three parameters.
x4 - the start of the span boundary
x6 - the end of the span boundary
P2 - the position of x6 (football) from the starting point (x4)
So given these three parameters, we see how good the model is at predicting the token 'football'.
Using the above two loss functions, the BERT model is fine-tuned and is called SpanBERT.
Span Boundary Objective:
Here, we get the output as a vector encoding the tokens in the sequence represented as (x1, ....., xn). The masked span of tokens is represented by (xs, ...., xe), where xs denotes start and xe denotes the end of the masked span of tokens. SBO function is represented as:
Eqn-(4)
where P1, P2, ... are relative positions w.r.t the left boundary token xs-1.
The SBO function ‘f’ is a 2 layer feed-forward network with GeLU activation. This 2 layer network is represented as:
Eqn-(5)
where,
h0 = first hidden representation
xs-1 = starting boundary word
xe+1 = ending boundary word
Pi-s+1 = positional embedding of the word
We pass h0 to first hidden layer with weight W1.
Eqn-(6)
where,
GeLU (Gaussian Error Linear Units) = non-linear activation function
h1 = second hidden representation
W1 = weight of first hidden layer
LayerNorm = a normalization technique used to prevent interactions within the batches
Now, we pass this through another with weight W2 layer to get the output yi.
Eqn-(7)
where,
yi = vector representation for all the toxens xi
W2 = weight of second hidden layer
To generalize, SpanBERT equivalent loss of a particular token in a span of words is calculated by:
Eqn-(8)
where,
Xi = final representation of tokens
xi = original sequence of tokens
yi = output obtained by passing xi through 2-layer feed forward network.
This was a basic intuition and understanding of the SpanBERT model and how it predicts a span of words instead of the individual token, making it more powerful than the BERT Model. For any doubts/queries, comment below.
akshaysingh98088
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Types of Environments in AI
Intuition of Adam Optimizer
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 77,
"s": 52,
"text": "Prerequisite: BERT Model"
},
{
"code": null,
"e": 94,
"s": 77,
"text": "SpanBERT vs BERT"
},
{
"code": null,
"e": 464,
"s": 94,
"text": "SpanBERT is an improvement on the BERT model providing improved prediction of spans of text. Unlike BERT, we perform the following steps here i) mask random contiguous spans, rather than random individual tokens. ii) training the model based on tokens at the start and end of the boundary of span (known as Span Boundary Objective) to predict the entire marked spans. "
},
{
"code": null,
"e": 627,
"s": 464,
"text": "It differs from BERT model in its masking scheme as BERT used to randomly mask tokens in a sequence but here in SpanBERT we mask random contiguous spans of text. "
},
{
"code": null,
"e": 738,
"s": 627,
"text": "Another difference is that of the training objective. BERT was trained on two objectives (2 loss functions) : "
},
{
"code": null,
"e": 811,
"s": 738,
"text": "Masked Language Modeling (MLM) — Predicting the mask token on the output"
},
{
"code": null,
"e": 900,
"s": 811,
"text": "Next Sequence Prediction (NSP) — Predicting if 2 sequences of texts followed each other."
},
{
"code": null,
"e": 1034,
"s": 900,
"text": "But in SpanBERT, the only thing the model is trained on is the Span Boundary Objective which later contributes to the loss function. "
},
{
"code": null,
"e": 1059,
"s": 1034,
"text": "SpanBERT: Implementation"
},
{
"code": null,
"e": 1522,
"s": 1059,
"text": "To implement SpanBERT, we build a replica of the BERT model but do certain changes in it so that it can perform better than the original BERT model. It is observed that the BERT model performs much better when only trained on ‘Masked Language Modelling’ alone rather than with ‘Next Sequence Prediction’. Hence, we disregard NSP and tuned the model on Single Sequence baseline while building the replica of BERT model, thereby improving its prediction accuracy. "
},
{
"code": null,
"e": 1542,
"s": 1522,
"text": "SpanBERT: Intuition"
},
{
"code": null,
"e": 1568,
"s": 1542,
"text": "Fig 1 : Training SpanBERT"
},
{
"code": null,
"e": 1838,
"s": 1568,
"text": "Fig 1 shows the training of the SpanBERT model. In the given sentence, the span of words ‘a football championship tournament‘ is masked. The Span Boundary Objective is defined by the x4 and x9 highlighted in blue. This is used to predict each token in the masked span. "
},
{
"code": null,
"e": 2047,
"s": 1838,
"text": "Here in Fig 1, a sequence of words ‘a football championship tournament‘ is created and the whole sequence is passed through the encoder block and get the prediction of the masked tokens as output. (x5 to x8) "
},
{
"code": null,
"e": 2187,
"s": 2047,
"text": "For example, if we were to predict for the token x6 (i.e. football), below is the equivalent loss (as shown in Eqn(1)) that we would get. "
},
{
"code": null,
"e": 2195,
"s": 2187,
"text": "Eqn-(1)"
},
{
"code": null,
"e": 2262,
"s": 2195,
"text": "This loss is the summation of losses given by MLM and SBO losses. "
},
{
"code": null,
"e": 2270,
"s": 2262,
"text": "Eqn-(2)"
},
{
"code": null,
"e": 2390,
"s": 2270,
"text": "Now, the MLM loss is the same as ‘-ve log of likelihood’ or in simpler terms what is the chances of x6 being football. "
},
{
"code": null,
"e": 2398,
"s": 2390,
"text": "Eqn-(3)"
},
{
"code": null,
"e": 2687,
"s": 2398,
"text": "Then, the SBO loss is depends on three parameters. \n\nx4 - the start of the span boundary\nx6 - the end of the span boundary \nP2 - the position of x6 (football) from the starting point (x4)\n\nSo given these three parameters, we see how good the model is at predicting the token 'football'. "
},
{
"code": null,
"e": 2776,
"s": 2687,
"text": "Using the above two loss functions, the BERT model is fine-tuned and is called SpanBERT."
},
{
"code": null,
"e": 2802,
"s": 2776,
"text": "Span Boundary Objective: "
},
{
"code": null,
"e": 3074,
"s": 2802,
"text": "Here, we get the output as a vector encoding the tokens in the sequence represented as (x1, ....., xn). The masked span of tokens is represented by (xs, ...., xe), where xs denotes start and xe denotes the end of the masked span of tokens. SBO function is represented as:"
},
{
"code": null,
"e": 3082,
"s": 3074,
"text": "Eqn-(4)"
},
{
"code": null,
"e": 3159,
"s": 3082,
"text": "where P1, P2, ... are relative positions w.r.t the left boundary token xs-1."
},
{
"code": null,
"e": 3276,
"s": 3159,
"text": "The SBO function ‘f’ is a 2 layer feed-forward network with GeLU activation. This 2 layer network is represented as:"
},
{
"code": null,
"e": 3284,
"s": 3276,
"text": "Eqn-(5)"
},
{
"code": null,
"e": 3425,
"s": 3284,
"text": "where,\n\nh0 = first hidden representation\nxs-1 = starting boundary word\nxe+1 = ending boundary word\nPi-s+1 = positional embedding of the word"
},
{
"code": null,
"e": 3474,
"s": 3425,
"text": "We pass h0 to first hidden layer with weight W1."
},
{
"code": null,
"e": 3482,
"s": 3474,
"text": "Eqn-(6)"
},
{
"code": null,
"e": 3715,
"s": 3482,
"text": "where,\n\nGeLU (Gaussian Error Linear Units) = non-linear activation function\nh1 = second hidden representation\nW1 = weight of first hidden layer\nLayerNorm = a normalization technique used to prevent interactions within the batches "
},
{
"code": null,
"e": 3792,
"s": 3715,
"text": "Now, we pass this through another with weight W2 layer to get the output yi."
},
{
"code": null,
"e": 3800,
"s": 3792,
"text": "Eqn-(7)"
},
{
"code": null,
"e": 3891,
"s": 3800,
"text": "where,\nyi = vector representation for all the toxens xi\nW2 = weight of second hidden layer"
},
{
"code": null,
"e": 3990,
"s": 3891,
"text": "To generalize, SpanBERT equivalent loss of a particular token in a span of words is calculated by:"
},
{
"code": null,
"e": 3998,
"s": 3990,
"text": "Eqn-(8)"
},
{
"code": null,
"e": 4148,
"s": 3998,
"text": "where,\nXi = final representation of tokens \nxi = original sequence of tokens\nyi = output obtained by passing xi through 2-layer feed forward network."
},
{
"code": null,
"e": 4368,
"s": 4148,
"text": "This was a basic intuition and understanding of the SpanBERT model and how it predicts a span of words instead of the individual token, making it more powerful than the BERT Model. For any doubts/queries, comment below."
},
{
"code": null,
"e": 4385,
"s": 4368,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4402,
"s": 4385,
"text": "Machine Learning"
},
{
"code": null,
"e": 4419,
"s": 4402,
"text": "Machine Learning"
},
{
"code": null,
"e": 4517,
"s": 4419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4558,
"s": 4517,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4591,
"s": 4558,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4627,
"s": 4591,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4651,
"s": 4627,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4702,
"s": 4651,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 4735,
"s": 4702,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 4775,
"s": 4735,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 4816,
"s": 4775,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 4844,
"s": 4816,
"text": "Types of Environments in AI"
}
] |
How to generate Large Prime numbers for RSA Algorithm
|
27 Sep, 2021
The security of the RSA algorithm is based on the difficulty of factorizing very large numbers. The setup of an RSA cryptosystem involves the generation of two large primes, say p and q, from which, the RSA modulus is calculated as n = p * q. The greater the modulus size, the higher is the security level of the RSA system. The recommended RSA modulus size for most settings is 2048 bits to 4096 bits. Thus, the primes to be generated need to be 1024 bit to 2048 bit long. For the synthesis of such large primes, instead of depending on deterministic methods, we rely on finding numbers that are prime with a satisfactorily high level of probability.
The goal is to efficiently compute very large random prime numbers with a specified bit-size. The standard method of manually implementing a random prime number generator which can generate prime values with a satisfactory level of accuracy is given as follows: Preselect a random number with the desired bit-sizeEnsure the chosen number is not divisible by the first few hundred primes (these are pre-generated)Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime
Preselect a random number with the desired bit-sizeEnsure the chosen number is not divisible by the first few hundred primes (these are pre-generated)Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime
Preselect a random number with the desired bit-size
Ensure the chosen number is not divisible by the first few hundred primes (these are pre-generated)
Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime
Fig 1: Steps involved in Generation of Large Primes for RSA
1. Picking a Random Prime Candidate
The generation of a random number with n-bits means the random number is in the range 0 and . Some considerations when generating the random number are: Picking of small primes, such as 3, 5, 7..., must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1Since all primes (> 2) are odd, for better performance, just odd number may be picked
Picking of small primes, such as 3, 5, 7..., must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1Since all primes (> 2) are odd, for better performance, just odd number may be picked
Picking of small primes, such as 3, 5, 7..., must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1
Since all primes (> 2) are odd, for better performance, just odd number may be picked
Thus, we pick any random number in the range
Python3
def nBitRandom(n): # Returns a random number # between 2**(n-1)+1 and 2**n-1''' return(random.randrange(2**(n-1)+1, 2**n-1))
2. Division with First Primes (Low-Level Primality Test)
This step is a a low level primality test which requires the pre-calculation of the first few hundred primes (using Sieve of Eratosthenes).
The prime candidate is divided by the pre-generated primes to check for divisibility. If the prime candidate is perfectly divisible by any of these pre-generated primes, the test fails and a new prime candidate must be picked and tested. This is repeated as long as a value which is coprime to all the primes in our generated primes list is found
Python3
def getLowLevelPrime(n): '''Generate a prime candidate divisible by first primes''' # Repeat until a number satisfying # the test isn't found while True: # Obtain a random number prime_candidate = nBitRandom(n) for divisor in first_primes_list: if prime_candidate % divisor == 0 and divisor**2 <= prime_candidate: break # If no divisor found, return value else: return prime_candidate
3. Rabin Miller Primality Test (High-Level Primality Test)
A prime candidate passing the low-level test is then tested again using the Rabin Miller Primality Test.
For extremely large numbers, such as ones used in RSA, deterministic testing of whether the chosen value is prime or not is highly impractical as it requires an unreasonable amount of computing resources.
A probabilistic approach is preferred as such. If an inputted value passes a single iteration of the Rabin Miller test, the probability of the number being prime is 75%.
Thus, a candidate passing the test, an adequate number of times, can be considered to be a prime with a satisfactory level of probability.
Usually, in commercial applications, we require error probabilities to be less than .
Python3
def isMillerRabinPassed(miller_rabin_candidate): '''Run 20 iterations of Rabin Miller Primality test''' maxDivisionsByTwo = 0 evenComponent = miller_rabin_candidate-1 while evenComponent % 2 == 0: evenComponent >>= 1 maxDivisionsByTwo += 1 assert(2**maxDivisionsByTwo * evenComponent == miller_rabin_candidate-1) def trialComposite(round_tester): if pow(round_tester, evenComponent, miller_rabin_candidate) == 1: return False for i in range(maxDivisionsByTwo): if pow(round_tester, 2**i * evenComponent, miller_rabin_candidate) == miller_rabin_candidate-1: return False return True # Set number of trials here numberOfRabinTrials = 20 for i in range(numberOfRabinTrials): round_tester = random.randrange(2, miller_rabin_candidate) if trialComposite(round_tester): return False return True
4. Combining the above steps to generate the code
Finally, we can combine the above functions to create a three-step process to generate large primes. The steps would be Random number generation by calling nBitRandom(bitsize)Basic division test by calling getLowLevelPrime(prime_candidate)Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)
Random number generation by calling nBitRandom(bitsize)Basic division test by calling getLowLevelPrime(prime_candidate)Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)
Random number generation by calling nBitRandom(bitsize)
Basic division test by calling getLowLevelPrime(prime_candidate)
Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)
If the chosen random value passes all primality tests, it is returned as the n-bit prime number. Otherwise, in the case of test-failure, a new random value is picked and tested for primality. The process is repeated until the desired prime is found.
Below is the complete implementation of the above approach
Python3
# Large Prime Generation for RSAimport random # Pre generated primesfirst_primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349] def nBitRandom(n): return random.randrange(2**(n-1)+1, 2**n - 1) def getLowLevelPrime(n): '''Generate a prime candidate divisible by first primes''' while True: # Obtain a random number pc = nBitRandom(n) # Test divisibility by pre-generated # primes for divisor in first_primes_list: if pc % divisor == 0 and divisor**2 <= pc: break else: return pc def isMillerRabinPassed(mrc): '''Run 20 iterations of Rabin Miller Primality test''' maxDivisionsByTwo = 0 ec = mrc-1 while ec % 2 == 0: ec >>= 1 maxDivisionsByTwo += 1 assert(2**maxDivisionsByTwo * ec == mrc-1) def trialComposite(round_tester): if pow(round_tester, ec, mrc) == 1: return False for i in range(maxDivisionsByTwo): if pow(round_tester, 2**i * ec, mrc) == mrc-1: return False return True # Set number of trials here numberOfRabinTrials = 20 for i in range(numberOfRabinTrials): round_tester = random.randrange(2, mrc) if trialComposite(round_tester): return False return True if __name__ == '__main__': while True: n = 1024 prime_candidate = getLowLevelPrime(n) if not isMillerRabinPassed(prime_candidate): continue else: print(n, "bit prime is: \n", prime_candidate) break
Note: Library Generation of Large Primes in Python
The pycrypto library is a comprehensive collection of secure hash functions and various encryption algorithms. It also includes basic functions commonly required in encryption/decryption setups such as random number generation and random prime number generation. The goal of generating a random prime number with a specified bit-size can be achieved using the pycrypto getPrime module. The syntax for generating a random n-bit prime number is:
Python3
from Crypto.Util import numbernumber.getPrime(n)
saurabh1990aror
cryptography
large-numbers
Prime Number
Computer Networks
Mathematical
Python
Python Programs
Mathematical
Prime Number
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 706,
"s": 54,
"text": "The security of the RSA algorithm is based on the difficulty of factorizing very large numbers. The setup of an RSA cryptosystem involves the generation of two large primes, say p and q, from which, the RSA modulus is calculated as n = p * q. The greater the modulus size, the higher is the security level of the RSA system. The recommended RSA modulus size for most settings is 2048 bits to 4096 bits. Thus, the primes to be generated need to be 1024 bit to 2048 bit long. For the synthesis of such large primes, instead of depending on deterministic methods, we rely on finding numbers that are prime with a satisfactorily high level of probability."
},
{
"code": null,
"e": 1258,
"s": 706,
"text": "The goal is to efficiently compute very large random prime numbers with a specified bit-size. The standard method of manually implementing a random prime number generator which can generate prime values with a satisfactory level of accuracy is given as follows: Preselect a random number with the desired bit-sizeEnsure the chosen number is not divisible by the first few hundred primes (these are pre-generated)Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime"
},
{
"code": null,
"e": 1548,
"s": 1258,
"text": "Preselect a random number with the desired bit-sizeEnsure the chosen number is not divisible by the first few hundred primes (these are pre-generated)Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime"
},
{
"code": null,
"e": 1600,
"s": 1548,
"text": "Preselect a random number with the desired bit-size"
},
{
"code": null,
"e": 1700,
"s": 1600,
"text": "Ensure the chosen number is not divisible by the first few hundred primes (these are pre-generated)"
},
{
"code": null,
"e": 1840,
"s": 1700,
"text": "Apply a certain number of Rabin Miller Primality Test iterations, based on acceptable error rate, to get a number which is probably a prime"
},
{
"code": null,
"e": 1900,
"s": 1840,
"text": "Fig 1: Steps involved in Generation of Large Primes for RSA"
},
{
"code": null,
"e": 1937,
"s": 1900,
"text": "1. Picking a Random Prime Candidate "
},
{
"code": null,
"e": 2416,
"s": 1937,
"text": "The generation of a random number with n-bits means the random number is in the range 0 and . Some considerations when generating the random number are: Picking of small primes, such as 3, 5, 7..., must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1Since all primes (> 2) are odd, for better performance, just odd number may be picked"
},
{
"code": null,
"e": 2742,
"s": 2416,
"text": "Picking of small primes, such as 3, 5, 7..., must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1Since all primes (> 2) are odd, for better performance, just odd number may be picked"
},
{
"code": null,
"e": 2983,
"s": 2742,
"text": "Picking of small primes, such as 3, 5, 7..., must be avoided as the factorization of RSA modulus would become trivial. Thus, care must be taken to not have too many leading zeroes. This may be done by always making the highest order bit = 1"
},
{
"code": null,
"e": 3069,
"s": 2983,
"text": "Since all primes (> 2) are odd, for better performance, just odd number may be picked"
},
{
"code": null,
"e": 3115,
"s": 3069,
"text": "Thus, we pick any random number in the range "
},
{
"code": null,
"e": 3123,
"s": 3115,
"text": "Python3"
},
{
"code": "def nBitRandom(n): # Returns a random number # between 2**(n-1)+1 and 2**n-1''' return(random.randrange(2**(n-1)+1, 2**n-1))",
"e": 3260,
"s": 3123,
"text": null
},
{
"code": null,
"e": 3318,
"s": 3260,
"text": "2. Division with First Primes (Low-Level Primality Test) "
},
{
"code": null,
"e": 3458,
"s": 3318,
"text": "This step is a a low level primality test which requires the pre-calculation of the first few hundred primes (using Sieve of Eratosthenes)."
},
{
"code": null,
"e": 3806,
"s": 3458,
"text": "The prime candidate is divided by the pre-generated primes to check for divisibility. If the prime candidate is perfectly divisible by any of these pre-generated primes, the test fails and a new prime candidate must be picked and tested. This is repeated as long as a value which is coprime to all the primes in our generated primes list is found "
},
{
"code": null,
"e": 3814,
"s": 3806,
"text": "Python3"
},
{
"code": "def getLowLevelPrime(n): '''Generate a prime candidate divisible by first primes''' # Repeat until a number satisfying # the test isn't found while True: # Obtain a random number prime_candidate = nBitRandom(n) for divisor in first_primes_list: if prime_candidate % divisor == 0 and divisor**2 <= prime_candidate: break # If no divisor found, return value else: return prime_candidate",
"e": 4308,
"s": 3814,
"text": null
},
{
"code": null,
"e": 4368,
"s": 4308,
"text": "3. Rabin Miller Primality Test (High-Level Primality Test) "
},
{
"code": null,
"e": 4473,
"s": 4368,
"text": "A prime candidate passing the low-level test is then tested again using the Rabin Miller Primality Test."
},
{
"code": null,
"e": 4678,
"s": 4473,
"text": "For extremely large numbers, such as ones used in RSA, deterministic testing of whether the chosen value is prime or not is highly impractical as it requires an unreasonable amount of computing resources."
},
{
"code": null,
"e": 4848,
"s": 4678,
"text": "A probabilistic approach is preferred as such. If an inputted value passes a single iteration of the Rabin Miller test, the probability of the number being prime is 75%."
},
{
"code": null,
"e": 4987,
"s": 4848,
"text": "Thus, a candidate passing the test, an adequate number of times, can be considered to be a prime with a satisfactory level of probability."
},
{
"code": null,
"e": 5074,
"s": 4987,
"text": "Usually, in commercial applications, we require error probabilities to be less than . "
},
{
"code": null,
"e": 5082,
"s": 5074,
"text": "Python3"
},
{
"code": "def isMillerRabinPassed(miller_rabin_candidate): '''Run 20 iterations of Rabin Miller Primality test''' maxDivisionsByTwo = 0 evenComponent = miller_rabin_candidate-1 while evenComponent % 2 == 0: evenComponent >>= 1 maxDivisionsByTwo += 1 assert(2**maxDivisionsByTwo * evenComponent == miller_rabin_candidate-1) def trialComposite(round_tester): if pow(round_tester, evenComponent, miller_rabin_candidate) == 1: return False for i in range(maxDivisionsByTwo): if pow(round_tester, 2**i * evenComponent, miller_rabin_candidate) == miller_rabin_candidate-1: return False return True # Set number of trials here numberOfRabinTrials = 20 for i in range(numberOfRabinTrials): round_tester = random.randrange(2, miller_rabin_candidate) if trialComposite(round_tester): return False return True",
"e": 6077,
"s": 5082,
"text": null
},
{
"code": null,
"e": 6128,
"s": 6077,
"text": "4. Combining the above steps to generate the code "
},
{
"code": null,
"e": 6433,
"s": 6128,
"text": "Finally, we can combine the above functions to create a three-step process to generate large primes. The steps would be Random number generation by calling nBitRandom(bitsize)Basic division test by calling getLowLevelPrime(prime_candidate)Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)"
},
{
"code": null,
"e": 6618,
"s": 6433,
"text": "Random number generation by calling nBitRandom(bitsize)Basic division test by calling getLowLevelPrime(prime_candidate)Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)"
},
{
"code": null,
"e": 6674,
"s": 6618,
"text": "Random number generation by calling nBitRandom(bitsize)"
},
{
"code": null,
"e": 6739,
"s": 6674,
"text": "Basic division test by calling getLowLevelPrime(prime_candidate)"
},
{
"code": null,
"e": 6805,
"s": 6739,
"text": "Rabin Miller Test by calling isMillerRabinPassed(prime_candidate)"
},
{
"code": null,
"e": 7056,
"s": 6805,
"text": "If the chosen random value passes all primality tests, it is returned as the n-bit prime number. Otherwise, in the case of test-failure, a new random value is picked and tested for primality. The process is repeated until the desired prime is found. "
},
{
"code": null,
"e": 7116,
"s": 7056,
"text": "Below is the complete implementation of the above approach "
},
{
"code": null,
"e": 7124,
"s": 7116,
"text": "Python3"
},
{
"code": "# Large Prime Generation for RSAimport random # Pre generated primesfirst_primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349] def nBitRandom(n): return random.randrange(2**(n-1)+1, 2**n - 1) def getLowLevelPrime(n): '''Generate a prime candidate divisible by first primes''' while True: # Obtain a random number pc = nBitRandom(n) # Test divisibility by pre-generated # primes for divisor in first_primes_list: if pc % divisor == 0 and divisor**2 <= pc: break else: return pc def isMillerRabinPassed(mrc): '''Run 20 iterations of Rabin Miller Primality test''' maxDivisionsByTwo = 0 ec = mrc-1 while ec % 2 == 0: ec >>= 1 maxDivisionsByTwo += 1 assert(2**maxDivisionsByTwo * ec == mrc-1) def trialComposite(round_tester): if pow(round_tester, ec, mrc) == 1: return False for i in range(maxDivisionsByTwo): if pow(round_tester, 2**i * ec, mrc) == mrc-1: return False return True # Set number of trials here numberOfRabinTrials = 20 for i in range(numberOfRabinTrials): round_tester = random.randrange(2, mrc) if trialComposite(round_tester): return False return True if __name__ == '__main__': while True: n = 1024 prime_candidate = getLowLevelPrime(n) if not isMillerRabinPassed(prime_candidate): continue else: print(n, \"bit prime is: \\n\", prime_candidate) break",
"e": 9108,
"s": 7124,
"text": null
},
{
"code": null,
"e": 9159,
"s": 9108,
"text": "Note: Library Generation of Large Primes in Python"
},
{
"code": null,
"e": 9603,
"s": 9159,
"text": "The pycrypto library is a comprehensive collection of secure hash functions and various encryption algorithms. It also includes basic functions commonly required in encryption/decryption setups such as random number generation and random prime number generation. The goal of generating a random prime number with a specified bit-size can be achieved using the pycrypto getPrime module. The syntax for generating a random n-bit prime number is:"
},
{
"code": null,
"e": 9611,
"s": 9603,
"text": "Python3"
},
{
"code": "from Crypto.Util import numbernumber.getPrime(n)",
"e": 9660,
"s": 9611,
"text": null
},
{
"code": null,
"e": 9676,
"s": 9660,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 9689,
"s": 9676,
"text": "cryptography"
},
{
"code": null,
"e": 9703,
"s": 9689,
"text": "large-numbers"
},
{
"code": null,
"e": 9716,
"s": 9703,
"text": "Prime Number"
},
{
"code": null,
"e": 9734,
"s": 9716,
"text": "Computer Networks"
},
{
"code": null,
"e": 9747,
"s": 9734,
"text": "Mathematical"
},
{
"code": null,
"e": 9754,
"s": 9747,
"text": "Python"
},
{
"code": null,
"e": 9770,
"s": 9754,
"text": "Python Programs"
},
{
"code": null,
"e": 9783,
"s": 9770,
"text": "Mathematical"
},
{
"code": null,
"e": 9796,
"s": 9783,
"text": "Prime Number"
},
{
"code": null,
"e": 9809,
"s": 9796,
"text": "cryptography"
},
{
"code": null,
"e": 9827,
"s": 9809,
"text": "Computer Networks"
},
{
"code": null,
"e": 9925,
"s": 9827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9955,
"s": 9925,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 9981,
"s": 9955,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 10011,
"s": 9981,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 10051,
"s": 10011,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 10097,
"s": 10051,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 10127,
"s": 10097,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10170,
"s": 10127,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10230,
"s": 10170,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10245,
"s": 10230,
"text": "C++ Data Types"
}
] |
java.time.Duration Class in Java
|
24 Jan, 2022
Duration is the value-based Class present in the Java time library. It’s used to get time-based amount of time. This class is immutable and thread-safe. This article describes all the methods present in this class and some basic examples using class methods.
This class implements Serializable, Comparable<Duration>, TemporalAmount interfaces.
Field present in Class:
Methods present in Class:
Example 1: This example illustrates simple use of Duration class.
Java
// Importing required classesimport java.time.Duration;import java.time.LocalTime;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // Initializing Duration variable Duration duration = Duration.between(LocalTime.NOON,LocalTime.MIDNIGHT); // Printing difference between time in seconds System.out.println(duration.get(ChronoUnit.SECONDS)); // Finding absolute difference Duration absDuration = duration.abs(); // Printing absolute time difference in seconds System.out.println(absDuration.get(ChronoUnit.SECONDS)); }}
-43200
43200
Example 2:
Java
// Importing required classesimport java.time.Duration;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // Getting duration in an hour Duration duration = Duration.from(ChronoUnit.HOURS.getDuration()); // Printing duration in minutes System.out.println(duration.toMinutes()); }}
Output:
60
simmytarika5
varshagumber28
Java-Duration
Java-time package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "Duration is the value-based Class present in the Java time library. It’s used to get time-based amount of time. This class is immutable and thread-safe. This article describes all the methods present in this class and some basic examples using class methods. "
},
{
"code": null,
"e": 373,
"s": 288,
"text": "This class implements Serializable, Comparable<Duration>, TemporalAmount interfaces."
},
{
"code": null,
"e": 397,
"s": 373,
"text": "Field present in Class:"
},
{
"code": null,
"e": 423,
"s": 397,
"text": "Methods present in Class:"
},
{
"code": null,
"e": 489,
"s": 423,
"text": "Example 1: This example illustrates simple use of Duration class."
},
{
"code": null,
"e": 494,
"s": 489,
"text": "Java"
},
{
"code": "// Importing required classesimport java.time.Duration;import java.time.LocalTime;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // Initializing Duration variable Duration duration = Duration.between(LocalTime.NOON,LocalTime.MIDNIGHT); // Printing difference between time in seconds System.out.println(duration.get(ChronoUnit.SECONDS)); // Finding absolute difference Duration absDuration = duration.abs(); // Printing absolute time difference in seconds System.out.println(absDuration.get(ChronoUnit.SECONDS)); }}",
"e": 1139,
"s": 494,
"text": null
},
{
"code": null,
"e": 1152,
"s": 1139,
"text": "-43200\n43200"
},
{
"code": null,
"e": 1164,
"s": 1152,
"text": "Example 2: "
},
{
"code": null,
"e": 1169,
"s": 1164,
"text": "Java"
},
{
"code": "// Importing required classesimport java.time.Duration;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // Getting duration in an hour Duration duration = Duration.from(ChronoUnit.HOURS.getDuration()); // Printing duration in minutes System.out.println(duration.toMinutes()); }}",
"e": 1535,
"s": 1169,
"text": null
},
{
"code": null,
"e": 1544,
"s": 1535,
"text": "Output: "
},
{
"code": null,
"e": 1547,
"s": 1544,
"text": "60"
},
{
"code": null,
"e": 1562,
"s": 1549,
"text": "simmytarika5"
},
{
"code": null,
"e": 1577,
"s": 1562,
"text": "varshagumber28"
},
{
"code": null,
"e": 1591,
"s": 1577,
"text": "Java-Duration"
},
{
"code": null,
"e": 1609,
"s": 1591,
"text": "Java-time package"
},
{
"code": null,
"e": 1616,
"s": 1609,
"text": "Picked"
},
{
"code": null,
"e": 1621,
"s": 1616,
"text": "Java"
},
{
"code": null,
"e": 1626,
"s": 1621,
"text": "Java"
},
{
"code": null,
"e": 1724,
"s": 1626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1739,
"s": 1724,
"text": "Stream In Java"
},
{
"code": null,
"e": 1760,
"s": 1739,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1781,
"s": 1760,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1800,
"s": 1781,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1817,
"s": 1800,
"text": "Generics in Java"
},
{
"code": null,
"e": 1847,
"s": 1817,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1873,
"s": 1847,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1889,
"s": 1873,
"text": "Strings in Java"
},
{
"code": null,
"e": 1926,
"s": 1889,
"text": "Differences between JDK, JRE and JVM"
}
] |
Java Program to locate a character in a string
|
To locate a character in a string, use the indexOf() method.
Let’s say the following is our string.
String str = "testdemo";
Find a character ‘d’ in a string and get the index.
int index = str.indexOf( 'd');
Live Demo
public class Demo {
public static void main(String []args) {
String str = "testdemo";
System.out.println("String: "+str);
int index = str.indexOf( 'd' );
System.out.printf("'d' is at index %d\n", index);
}
}
String: testdemo
'd' is at index 4
Let us see another example. The method returns -1, if the character isn’t found −
Live Demo
public class Demo {
public static void main(String []args) {
String str = "testdemo";
System.out.println("String: "+str);
int index = str.indexOf( 'h' );
System.out.printf("'h' is at index %d\n", index);
}
}
String: testdemo
'h' is at index -1
|
[
{
"code": null,
"e": 1123,
"s": 1062,
"text": "To locate a character in a string, use the indexOf() method."
},
{
"code": null,
"e": 1162,
"s": 1123,
"text": "Let’s say the following is our string."
},
{
"code": null,
"e": 1187,
"s": 1162,
"text": "String str = \"testdemo\";"
},
{
"code": null,
"e": 1239,
"s": 1187,
"text": "Find a character ‘d’ in a string and get the index."
},
{
"code": null,
"e": 1270,
"s": 1239,
"text": "int index = str.indexOf( 'd');"
},
{
"code": null,
"e": 1281,
"s": 1270,
"text": " Live Demo"
},
{
"code": null,
"e": 1519,
"s": 1281,
"text": "public class Demo {\n public static void main(String []args) {\n String str = \"testdemo\";\n System.out.println(\"String: \"+str);\n int index = str.indexOf( 'd' );\n System.out.printf(\"'d' is at index %d\\n\", index);\n }\n}"
},
{
"code": null,
"e": 1554,
"s": 1519,
"text": "String: testdemo\n'd' is at index 4"
},
{
"code": null,
"e": 1636,
"s": 1554,
"text": "Let us see another example. The method returns -1, if the character isn’t found −"
},
{
"code": null,
"e": 1647,
"s": 1636,
"text": " Live Demo"
},
{
"code": null,
"e": 1885,
"s": 1647,
"text": "public class Demo {\n public static void main(String []args) {\n String str = \"testdemo\";\n System.out.println(\"String: \"+str);\n int index = str.indexOf( 'h' );\n System.out.printf(\"'h' is at index %d\\n\", index);\n }\n}"
},
{
"code": null,
"e": 1921,
"s": 1885,
"text": "String: testdemo\n'h' is at index -1"
}
] |
Besides Word Embedding, why you need to know Character Embedding? | by Edward Ma | Towards Data Science
|
In 2013, Tomas Mikolov [1] introduced word embedding to learn a better quality of word. At that time word embedding is state of the art on dealing with text. Later on, doc2vec is introduced as well. What if we think in another angel? Instead of aggregate from word to document, is it possible to aggregate from character to word.
In this article, you will go through what, why, when and how on Character Embedding.
Xiang and Yann [2] introduced character CNN. They found that character includes key signal to improve model performance. In the paper, a list of character are defined 70 characters which including 26 English letters, 10 digits, 33 special characters and new line character.
# Copy from Char CNN paperabcdefghijklmnopqrstuvwxyz0123456789 -,;.!?:’’’/\|_@#$%ˆ&* ̃‘+-=()[]{}
On the other hand, Google Brain team introduced Exploring the Limits of Language Modeling and released the lm_1b model which includes 256 vectors (including 52 characters, special characters) and the dimension is just 16. By comparing to word embedding, the dimension can increase up to 300 while the number of vectors is huge.
In english, all words are formed by 26 (or 52 if including both upper and lower case character, or even more if including special characters). Having the character embedding, every single word’s vector can be formed even it is out-of-vocabulary words (optional). On the other hand, word embedding can only handle those seen words.
Another benefit is that it good fits for misspelling words, emoticons, new words (e.g. In 2018, Oxford English Dictionary introduced new word which is boba tea 波霸奶茶. Before that we do not have any pre-trained word embedding for that).
It handles infrequent words better than word2vec embedding as later one suffers from lack of enough training opportunity for those rare words.
Third reason is that as there are only small amount of vector, it reduces model complexity and improving the performance (in terms of speed)
In NLP, we can apply character embedding on:
Text Classification
Language Model
Named Entity Recognition
Character Embedding
Define a list a characters (i.e. m). For example, can use alphanumeric and some special characters. For my example, English characters (52), number (10), special characters (20) and one unknown character, UNK. Total 83 characters.Transfer characters as 1-hot encoding and got a sequence for vectors. For unknown characters and blank characters, use all-zero vector to replace it. If exceeding pre-defined maximum length of characters (i.e. l), ignoring it. The output is 16 dimensions vector per every single character.Using 3 1D CNN layers (configurable) to learn the sequence
Define a list a characters (i.e. m). For example, can use alphanumeric and some special characters. For my example, English characters (52), number (10), special characters (20) and one unknown character, UNK. Total 83 characters.
Transfer characters as 1-hot encoding and got a sequence for vectors. For unknown characters and blank characters, use all-zero vector to replace it. If exceeding pre-defined maximum length of characters (i.e. l), ignoring it. The output is 16 dimensions vector per every single character.
Using 3 1D CNN layers (configurable) to learn the sequence
Sentence Embedding
Bi-directional LSTM followed CNN layersSome dropout layers are added after LSTM.
Bi-directional LSTM followed CNN layers
Some dropout layers are added after LSTM.
This sample code will demonstrate how to use Character Embedding to do classification. Testing dataset can be found in the UCI ML Repository.
Preprocess
First of all, we need to prepare meta information including character dictionary and converting label from text to numeric (as keras support numeric input only).
preporcess(labels=df['category'].unique())
Output
-----> Stage: preprocessTotoal number of chars: 83First 3 char_indices sample: {';': 0, '"': 1, 'A': 2}First 3 indices_char sample: {0: ';', 1: '"', 2: 'A'}Label to Index: {'b': 0, 'e': 2, 'm': 3, 't': 1}Index to Label: {0: 'b', 1: 't', 2: 'e', 3: 'm'}
Process
We have to transform raw input training data and testing to numpy format for keras input
x_train, y_train = char_cnn.process( df=train_df, x_col='headline', y_col='category')x_test, y_test = char_cnn.process( df=test_df, x_col='headline', y_col='category')
Output
-----> Stage: processNumber of news: 100Actual max sentence: 3Train Shape: (100, 5, 256) (100,)-----> Stage: processNumber of news: 10Actual max sentence: 1Train Shape: (10, 5, 256) (10,)
Build Model
Leveraging CNN layer and bidirectional LSTM to build a Character CNN text classifier. First of all, using 1 dimension CNN to build character block
def _build_character_block( self, block, dropout=0.3, filters=[64, 100], kernel_size=[3, 3], pool_size=[2, 2], padding='valid', activation='relu', kernel_initializer='glorot_normal'): for i in range(len(filters)): block = Conv1D( filters=filters[i], kernel_size=kernel_size[i], padding=padding, activation=activation, kernel_initializer=kernel_initializer)(block) block = Dropout(dropout)(block) block = MaxPooling1D(pool_size=pool_size[i])(block) block = GlobalMaxPool1D()(block) block = Dense(128, activation='relu')(block) return block
Sentence level block will be built by using 3 character blocks
def _build_sentence_block( self, max_len_of_sentence, max_num_of_setnence, filters=[[100, 200, 200], [200, 300, 300], [300, 400, 400]], kernel_sizes=[[4, 3, 3], [5, 3, 3], [6, 3, 3]], pool_sizes=[[2, 2, 2], [2, 2, 2], [2, 2, 2]], dropout=0.4): sent_input = Input(shape=(max_len_of_sentence, ), dtype='int64') embedded = Embedding(self.num_of_char, char_dimension, input_length=max_len_of_sentence)(sent_input) blocks = [] for i, filter_layers in enumerate(filters): blocks.append( self._build_character_block( block=embedded, filters=filter_layers, kernel_size=kernel_sizes[i], pool_size=pool_sizes[i]) ) sent_output = concatenate(blocks, axis=-1) sent_output = Dropout(dropout)(sent_output) sent_encoder = Model(inputs=sent_input, outputs=sent_output) return sent_encoder
Finally, we will build document block according to sentences
def _build_document_block( self, sent_encoder, max_len_of_sentence, max_num_of_setnence, num_of_label, dropout=0.3, loss='sparse_categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']): doc_input = Input(shape=( max_num_of_setnence, max_len_of_sentence), dtype='int64') doc_output = TimeDistributed(sent_encoder)(doc_input) doc_output = Bidirectional(LSTM( 128, return_sequences=False, dropout=dropout))(doc_output) doc_output = Dropout(dropout)(doc_output) doc_output = Dense(128, activation='relu')(doc_output) doc_output = Dropout(dropout)(doc_output) doc_output = Dense( num_of_label, activation='sigmoid')(doc_output) doc_encoder = Model(inputs=doc_input, outputs=doc_output) doc_encoder.compile( loss=loss, optimizer=optimizer, metrics=metrics) return doc_encoder
Output
Training
train(x_train, y_train, x_test, y_test, epochs=10)
Output
You can found out all code from github.
Character Embedding is a brilliant design for solving lots of text classification. It resolved some word embedding. Difference between Character Embedding and Word Embedding is that Character Embedding can build any word as long as those character are included.
Facebook AI Research (FAIR) did a further step. Team use subword to train the model. Taking “Facebook” as an example, they use “F”, “Fa”, “Fac” etc to train the word. For detail of fasttext, you may visit their website for better understanding.
This is some comment on Character Embedding as it does not include any word meaning but just using characters. We may include both Character Embedding and Word Embedding together to solve our NLP problem.
A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval
Learning Character-level Representations for Part-of-Speech Tagging
Character-level Convolutional Networks for Text Classification
Character Level Deep Learning in Sentiment Analysis
I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github.
[1] Tomas Mikolov, Greg Corrado, Kai Chen & Jeffrey Dean. Efficient Estimation of Word Representations in Vector Space. September 2013. https://arxiv.org/pdf/1301.3781.pdf
[2] Xiang Zhang, Yann LeCun. Text Understanding from Scratch. 2016. https://arxiv.org/pdf/1502.01710v5.pdf
[3] Kim Y., Jernite Y., Sontag D., Rush A. M.. Character-Aware Neural Language Models. 2015. https://arxiv.org/pdf/1508.06615.pdf
|
[
{
"code": null,
"e": 502,
"s": 172,
"text": "In 2013, Tomas Mikolov [1] introduced word embedding to learn a better quality of word. At that time word embedding is state of the art on dealing with text. Later on, doc2vec is introduced as well. What if we think in another angel? Instead of aggregate from word to document, is it possible to aggregate from character to word."
},
{
"code": null,
"e": 587,
"s": 502,
"text": "In this article, you will go through what, why, when and how on Character Embedding."
},
{
"code": null,
"e": 861,
"s": 587,
"text": "Xiang and Yann [2] introduced character CNN. They found that character includes key signal to improve model performance. In the paper, a list of character are defined 70 characters which including 26 English letters, 10 digits, 33 special characters and new line character."
},
{
"code": null,
"e": 958,
"s": 861,
"text": "# Copy from Char CNN paperabcdefghijklmnopqrstuvwxyz0123456789 -,;.!?:’’’/\\|_@#$%ˆ&* ̃‘+-=()[]{}"
},
{
"code": null,
"e": 1286,
"s": 958,
"text": "On the other hand, Google Brain team introduced Exploring the Limits of Language Modeling and released the lm_1b model which includes 256 vectors (including 52 characters, special characters) and the dimension is just 16. By comparing to word embedding, the dimension can increase up to 300 while the number of vectors is huge."
},
{
"code": null,
"e": 1617,
"s": 1286,
"text": "In english, all words are formed by 26 (or 52 if including both upper and lower case character, or even more if including special characters). Having the character embedding, every single word’s vector can be formed even it is out-of-vocabulary words (optional). On the other hand, word embedding can only handle those seen words."
},
{
"code": null,
"e": 1852,
"s": 1617,
"text": "Another benefit is that it good fits for misspelling words, emoticons, new words (e.g. In 2018, Oxford English Dictionary introduced new word which is boba tea 波霸奶茶. Before that we do not have any pre-trained word embedding for that)."
},
{
"code": null,
"e": 1995,
"s": 1852,
"text": "It handles infrequent words better than word2vec embedding as later one suffers from lack of enough training opportunity for those rare words."
},
{
"code": null,
"e": 2136,
"s": 1995,
"text": "Third reason is that as there are only small amount of vector, it reduces model complexity and improving the performance (in terms of speed)"
},
{
"code": null,
"e": 2181,
"s": 2136,
"text": "In NLP, we can apply character embedding on:"
},
{
"code": null,
"e": 2201,
"s": 2181,
"text": "Text Classification"
},
{
"code": null,
"e": 2216,
"s": 2201,
"text": "Language Model"
},
{
"code": null,
"e": 2241,
"s": 2216,
"text": "Named Entity Recognition"
},
{
"code": null,
"e": 2261,
"s": 2241,
"text": "Character Embedding"
},
{
"code": null,
"e": 2839,
"s": 2261,
"text": "Define a list a characters (i.e. m). For example, can use alphanumeric and some special characters. For my example, English characters (52), number (10), special characters (20) and one unknown character, UNK. Total 83 characters.Transfer characters as 1-hot encoding and got a sequence for vectors. For unknown characters and blank characters, use all-zero vector to replace it. If exceeding pre-defined maximum length of characters (i.e. l), ignoring it. The output is 16 dimensions vector per every single character.Using 3 1D CNN layers (configurable) to learn the sequence"
},
{
"code": null,
"e": 3070,
"s": 2839,
"text": "Define a list a characters (i.e. m). For example, can use alphanumeric and some special characters. For my example, English characters (52), number (10), special characters (20) and one unknown character, UNK. Total 83 characters."
},
{
"code": null,
"e": 3360,
"s": 3070,
"text": "Transfer characters as 1-hot encoding and got a sequence for vectors. For unknown characters and blank characters, use all-zero vector to replace it. If exceeding pre-defined maximum length of characters (i.e. l), ignoring it. The output is 16 dimensions vector per every single character."
},
{
"code": null,
"e": 3419,
"s": 3360,
"text": "Using 3 1D CNN layers (configurable) to learn the sequence"
},
{
"code": null,
"e": 3438,
"s": 3419,
"text": "Sentence Embedding"
},
{
"code": null,
"e": 3519,
"s": 3438,
"text": "Bi-directional LSTM followed CNN layersSome dropout layers are added after LSTM."
},
{
"code": null,
"e": 3559,
"s": 3519,
"text": "Bi-directional LSTM followed CNN layers"
},
{
"code": null,
"e": 3601,
"s": 3559,
"text": "Some dropout layers are added after LSTM."
},
{
"code": null,
"e": 3743,
"s": 3601,
"text": "This sample code will demonstrate how to use Character Embedding to do classification. Testing dataset can be found in the UCI ML Repository."
},
{
"code": null,
"e": 3754,
"s": 3743,
"text": "Preprocess"
},
{
"code": null,
"e": 3916,
"s": 3754,
"text": "First of all, we need to prepare meta information including character dictionary and converting label from text to numeric (as keras support numeric input only)."
},
{
"code": null,
"e": 3959,
"s": 3916,
"text": "preporcess(labels=df['category'].unique())"
},
{
"code": null,
"e": 3966,
"s": 3959,
"text": "Output"
},
{
"code": null,
"e": 4221,
"s": 3966,
"text": "-----> Stage: preprocessTotoal number of chars: 83First 3 char_indices sample: {';': 0, '\"': 1, 'A': 2}First 3 indices_char sample: {0: ';', 1: '\"', 2: 'A'}Label to Index: {'b': 0, 'e': 2, 'm': 3, 't': 1}Index to Label: {0: 'b', 1: 't', 2: 'e', 3: 'm'}"
},
{
"code": null,
"e": 4229,
"s": 4221,
"text": "Process"
},
{
"code": null,
"e": 4318,
"s": 4229,
"text": "We have to transform raw input training data and testing to numpy format for keras input"
},
{
"code": null,
"e": 4492,
"s": 4318,
"text": "x_train, y_train = char_cnn.process( df=train_df, x_col='headline', y_col='category')x_test, y_test = char_cnn.process( df=test_df, x_col='headline', y_col='category')"
},
{
"code": null,
"e": 4499,
"s": 4492,
"text": "Output"
},
{
"code": null,
"e": 4689,
"s": 4499,
"text": "-----> Stage: processNumber of news: 100Actual max sentence: 3Train Shape: (100, 5, 256) (100,)-----> Stage: processNumber of news: 10Actual max sentence: 1Train Shape: (10, 5, 256) (10,)"
},
{
"code": null,
"e": 4701,
"s": 4689,
"text": "Build Model"
},
{
"code": null,
"e": 4848,
"s": 4701,
"text": "Leveraging CNN layer and bidirectional LSTM to build a Character CNN text classifier. First of all, using 1 dimension CNN to build character block"
},
{
"code": null,
"e": 5476,
"s": 4848,
"text": "def _build_character_block( self, block, dropout=0.3, filters=[64, 100], kernel_size=[3, 3], pool_size=[2, 2], padding='valid', activation='relu', kernel_initializer='glorot_normal'): for i in range(len(filters)): block = Conv1D( filters=filters[i], kernel_size=kernel_size[i], padding=padding, activation=activation, kernel_initializer=kernel_initializer)(block) block = Dropout(dropout)(block) block = MaxPooling1D(pool_size=pool_size[i])(block) block = GlobalMaxPool1D()(block) block = Dense(128, activation='relu')(block) return block"
},
{
"code": null,
"e": 5539,
"s": 5476,
"text": "Sentence level block will be built by using 3 character blocks"
},
{
"code": null,
"e": 6463,
"s": 5539,
"text": "def _build_sentence_block( self, max_len_of_sentence, max_num_of_setnence, filters=[[100, 200, 200], [200, 300, 300], [300, 400, 400]], kernel_sizes=[[4, 3, 3], [5, 3, 3], [6, 3, 3]], pool_sizes=[[2, 2, 2], [2, 2, 2], [2, 2, 2]], dropout=0.4): sent_input = Input(shape=(max_len_of_sentence, ), dtype='int64') embedded = Embedding(self.num_of_char, char_dimension, input_length=max_len_of_sentence)(sent_input) blocks = [] for i, filter_layers in enumerate(filters): blocks.append( self._build_character_block( block=embedded, filters=filter_layers, kernel_size=kernel_sizes[i], pool_size=pool_sizes[i]) ) sent_output = concatenate(blocks, axis=-1) sent_output = Dropout(dropout)(sent_output) sent_encoder = Model(inputs=sent_input, outputs=sent_output) return sent_encoder"
},
{
"code": null,
"e": 6524,
"s": 6463,
"text": "Finally, we will build document block according to sentences"
},
{
"code": null,
"e": 7392,
"s": 6524,
"text": "def _build_document_block( self, sent_encoder, max_len_of_sentence, max_num_of_setnence, num_of_label, dropout=0.3, loss='sparse_categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']): doc_input = Input(shape=( max_num_of_setnence, max_len_of_sentence), dtype='int64') doc_output = TimeDistributed(sent_encoder)(doc_input) doc_output = Bidirectional(LSTM( 128, return_sequences=False, dropout=dropout))(doc_output) doc_output = Dropout(dropout)(doc_output) doc_output = Dense(128, activation='relu')(doc_output) doc_output = Dropout(dropout)(doc_output) doc_output = Dense( num_of_label, activation='sigmoid')(doc_output) doc_encoder = Model(inputs=doc_input, outputs=doc_output) doc_encoder.compile( loss=loss, optimizer=optimizer, metrics=metrics) return doc_encoder"
},
{
"code": null,
"e": 7399,
"s": 7392,
"text": "Output"
},
{
"code": null,
"e": 7408,
"s": 7399,
"text": "Training"
},
{
"code": null,
"e": 7459,
"s": 7408,
"text": "train(x_train, y_train, x_test, y_test, epochs=10)"
},
{
"code": null,
"e": 7466,
"s": 7459,
"text": "Output"
},
{
"code": null,
"e": 7506,
"s": 7466,
"text": "You can found out all code from github."
},
{
"code": null,
"e": 7768,
"s": 7506,
"text": "Character Embedding is a brilliant design for solving lots of text classification. It resolved some word embedding. Difference between Character Embedding and Word Embedding is that Character Embedding can build any word as long as those character are included."
},
{
"code": null,
"e": 8013,
"s": 7768,
"text": "Facebook AI Research (FAIR) did a further step. Team use subword to train the model. Taking “Facebook” as an example, they use “F”, “Fa”, “Fac” etc to train the word. For detail of fasttext, you may visit their website for better understanding."
},
{
"code": null,
"e": 8218,
"s": 8013,
"text": "This is some comment on Character Embedding as it does not include any word meaning but just using characters. We may include both Character Embedding and Word Embedding together to solve our NLP problem."
},
{
"code": null,
"e": 8305,
"s": 8218,
"text": "A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval"
},
{
"code": null,
"e": 8373,
"s": 8305,
"text": "Learning Character-level Representations for Part-of-Speech Tagging"
},
{
"code": null,
"e": 8436,
"s": 8373,
"text": "Character-level Convolutional Networks for Text Classification"
},
{
"code": null,
"e": 8488,
"s": 8436,
"text": "Character Level Deep Learning in Sentiment Analysis"
},
{
"code": null,
"e": 8688,
"s": 8488,
"text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github."
},
{
"code": null,
"e": 8860,
"s": 8688,
"text": "[1] Tomas Mikolov, Greg Corrado, Kai Chen & Jeffrey Dean. Efficient Estimation of Word Representations in Vector Space. September 2013. https://arxiv.org/pdf/1301.3781.pdf"
},
{
"code": null,
"e": 8967,
"s": 8860,
"text": "[2] Xiang Zhang, Yann LeCun. Text Understanding from Scratch. 2016. https://arxiv.org/pdf/1502.01710v5.pdf"
}
] |
Combine similar characters in Python using Dictionary Get() Method - GeeksforGeeks
|
14 Apr, 2022
Let us see how to combine similar characters in a list.
Example :
Input : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]
Output : [‘gg’, ‘eeee’, ‘kk’, ‘ss’, ‘f’, ‘o’, ‘r’]
We will be using the get() method of the dictionary class.
The get() method returns the value of the item with the specified key.
Syntax : dictionary.get(key name, value)
Parameters :
keyname : The key name of the dictionary item.
value : (Optional) If the specified key does not exist, then a value is returned.
Returns : Value of the item with the specified key
Algorithm :
Declare the list.Declare a dictionary.Iterate over the list, using the get() method, if a new key is found, then the value 0 is assigned to it and 1 is added making the final value 1. Else if the key is repeated, then 1 is added to the previously calculated value. So this way, now each key has a value assigned to it, and frequency of all characters is recorded.Separate all the keys and the values and store them in 2 different lists.Use the zip() function store the product of keys and their respective values in the result list.Display the result.
Declare the list.
Declare a dictionary.
Iterate over the list, using the get() method, if a new key is found, then the value 0 is assigned to it and 1 is added making the final value 1. Else if the key is repeated, then 1 is added to the previously calculated value. So this way, now each key has a value assigned to it, and frequency of all characters is recorded.
Separate all the keys and the values and store them in 2 different lists.
Use the zip() function store the product of keys and their respective values in the result list.
Display the result.
Example 1 :
python3
# declaring the list of charactersmylist = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # declaring the dictionarydictionary = {} # counting the frequency of the keysfor key in mylist: dictionary[key] = dictionary.get(key, 0) + 1 # storing the of keys and valuesk = list(dictionary.keys())v = list(dictionary.values()) # declaring the result listresult = [] # storing the product of keys and# their respective values in resultfor i, j in zip(k, v): result.append(i * j) # displaying the resultprint(result)
Output :
['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r']
Example 2 :
python3
# declaring the list of charactersmylist = ['p', 'y', 't', 'h', 'o', 'n', 't', 'u', 't', 'o', 'r', 'i', 'a', 'l'] # declaring the dictionarydictionary = {} # counting the frequency of the keysfor key in mylist: dictionary[key] = dictionary.get(key, 0) + 1 # storing the of keys and valuesk = list(dictionary.keys())v = list(dictionary.values()) # declaring the result listresult = [] # storing the product of keys and# their respective values in resultfor i, j in zip(k, v): result.append(i * j) # displaying the resultprint(result)
Output :
['a', 'h', 'i', 'l', 'n', 'oo', 'p', 'r', 'ttt', 'u', 'y']
clintra
sumitgumber28
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 23781,
"s": 23753,
"text": "\n14 Apr, 2022"
},
{
"code": null,
"e": 23838,
"s": 23781,
"text": "Let us see how to combine similar characters in a list. "
},
{
"code": null,
"e": 23848,
"s": 23838,
"text": "Example :"
},
{
"code": null,
"e": 23923,
"s": 23848,
"text": "Input : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’] "
},
{
"code": null,
"e": 23974,
"s": 23923,
"text": "Output : [‘gg’, ‘eeee’, ‘kk’, ‘ss’, ‘f’, ‘o’, ‘r’]"
},
{
"code": null,
"e": 24033,
"s": 23974,
"text": "We will be using the get() method of the dictionary class."
},
{
"code": null,
"e": 24104,
"s": 24033,
"text": "The get() method returns the value of the item with the specified key."
},
{
"code": null,
"e": 24146,
"s": 24104,
"text": "Syntax : dictionary.get(key name, value) "
},
{
"code": null,
"e": 24159,
"s": 24146,
"text": "Parameters :"
},
{
"code": null,
"e": 24206,
"s": 24159,
"text": "keyname : The key name of the dictionary item."
},
{
"code": null,
"e": 24288,
"s": 24206,
"text": "value : (Optional) If the specified key does not exist, then a value is returned."
},
{
"code": null,
"e": 24339,
"s": 24288,
"text": "Returns : Value of the item with the specified key"
},
{
"code": null,
"e": 24351,
"s": 24339,
"text": "Algorithm :"
},
{
"code": null,
"e": 24903,
"s": 24351,
"text": "Declare the list.Declare a dictionary.Iterate over the list, using the get() method, if a new key is found, then the value 0 is assigned to it and 1 is added making the final value 1. Else if the key is repeated, then 1 is added to the previously calculated value. So this way, now each key has a value assigned to it, and frequency of all characters is recorded.Separate all the keys and the values and store them in 2 different lists.Use the zip() function store the product of keys and their respective values in the result list.Display the result."
},
{
"code": null,
"e": 24921,
"s": 24903,
"text": "Declare the list."
},
{
"code": null,
"e": 24943,
"s": 24921,
"text": "Declare a dictionary."
},
{
"code": null,
"e": 25269,
"s": 24943,
"text": "Iterate over the list, using the get() method, if a new key is found, then the value 0 is assigned to it and 1 is added making the final value 1. Else if the key is repeated, then 1 is added to the previously calculated value. So this way, now each key has a value assigned to it, and frequency of all characters is recorded."
},
{
"code": null,
"e": 25343,
"s": 25269,
"text": "Separate all the keys and the values and store them in 2 different lists."
},
{
"code": null,
"e": 25440,
"s": 25343,
"text": "Use the zip() function store the product of keys and their respective values in the result list."
},
{
"code": null,
"e": 25460,
"s": 25440,
"text": "Display the result."
},
{
"code": null,
"e": 25473,
"s": 25460,
"text": "Example 1 : "
},
{
"code": null,
"e": 25481,
"s": 25473,
"text": "python3"
},
{
"code": "# declaring the list of charactersmylist = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # declaring the dictionarydictionary = {} # counting the frequency of the keysfor key in mylist: dictionary[key] = dictionary.get(key, 0) + 1 # storing the of keys and valuesk = list(dictionary.keys())v = list(dictionary.values()) # declaring the result listresult = [] # storing the product of keys and# their respective values in resultfor i, j in zip(k, v): result.append(i * j) # displaying the resultprint(result)",
"e": 26028,
"s": 25481,
"text": null
},
{
"code": null,
"e": 26037,
"s": 26028,
"text": "Output :"
},
{
"code": null,
"e": 26079,
"s": 26037,
"text": "['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r']"
},
{
"code": null,
"e": 26092,
"s": 26079,
"text": "Example 2 : "
},
{
"code": null,
"e": 26100,
"s": 26092,
"text": "python3"
},
{
"code": "# declaring the list of charactersmylist = ['p', 'y', 't', 'h', 'o', 'n', 't', 'u', 't', 'o', 'r', 'i', 'a', 'l'] # declaring the dictionarydictionary = {} # counting the frequency of the keysfor key in mylist: dictionary[key] = dictionary.get(key, 0) + 1 # storing the of keys and valuesk = list(dictionary.keys())v = list(dictionary.values()) # declaring the result listresult = [] # storing the product of keys and# their respective values in resultfor i, j in zip(k, v): result.append(i * j) # displaying the resultprint(result)",
"e": 26652,
"s": 26100,
"text": null
},
{
"code": null,
"e": 26661,
"s": 26652,
"text": "Output :"
},
{
"code": null,
"e": 26720,
"s": 26661,
"text": "['a', 'h', 'i', 'l', 'n', 'oo', 'p', 'r', 'ttt', 'u', 'y']"
},
{
"code": null,
"e": 26728,
"s": 26720,
"text": "clintra"
},
{
"code": null,
"e": 26742,
"s": 26728,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26754,
"s": 26742,
"text": "python-dict"
},
{
"code": null,
"e": 26776,
"s": 26754,
"text": "Python-dict-functions"
},
{
"code": null,
"e": 26783,
"s": 26776,
"text": "Python"
},
{
"code": null,
"e": 26795,
"s": 26783,
"text": "python-dict"
},
{
"code": null,
"e": 26893,
"s": 26795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26902,
"s": 26893,
"text": "Comments"
},
{
"code": null,
"e": 26915,
"s": 26902,
"text": "Old Comments"
},
{
"code": null,
"e": 26933,
"s": 26915,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26968,
"s": 26933,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26990,
"s": 26968,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27022,
"s": 26990,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27052,
"s": 27022,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27094,
"s": 27052,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27120,
"s": 27094,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27163,
"s": 27120,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27207,
"s": 27163,
"text": "Reading and Writing to text files in Python"
}
] |
Max sum submatrix | Practice | GeeksforGeeks
|
Given a matrix of size NxM and a list of queries containing (a,b) pairs. Find the maximum sum among all (a x b) sub-matrices of the matrix.
Note: The rows and columns of the submatrix must be contiguous. For example:
Example 1:
Input:
N = 3, M = 4
mat[][] = {{1, 2, 3, 9},
{4, 5, 6, 2},
{8, 3, 2, 6}}
Q = 1
Queries[] = {(3,2)}
Output: 28
Explanation:
Here a = 3 and b = 2.
The first 3x2 submatrix is:
1 2
4 5
8 3
The sum of elements in this is 23.
The second 3x2 submatrix is:
2 3
5 6
3 2
The sum of elements in this is 21.
The third 3x2 submatrix is:
3 9
6 2
2 6
The sum of elements in this is 28.
The maximum among these is 28.
Example 2:
Input:
N = 3, M = 4
mat[][] = {{1, 2, 3, 9},
{4, 5, 6, 2},
{8, 3, 2, 6}}
Q = 3
Queries[] = {(1, 1), (2, 2), (3, 3)}
Output: 9 20 38
Example 3:
Input:
N = 2, M = 7
mat[][] = {{49, 44, 46, 22, 24, 11, 2},
{5, 25, 24, 28, 20, 47, 47}}
Q = 1
Queries = {(2, 1)}
Output: 70
Your Task:
You don't need to read input or print anything. Your task is to complete the function maxSubMatrixSumQueries() which takes the 2D array of integers mat, n, m, queries and q as input parameters and returns an array of integers denoting the maximum sum for each query.
Expected Time Complexity: O(Q*N*M)
Expected Auxiliary Space: O(N*M)
Constraints:
1 ≤ N ≤ 103
1 ≤ M ≤ 103
1 ≤ Q ≤ 100
1 ≤ a ≤ N
1 ≤ b ≤ M
1 ≤ mat[i][j] ≤ 103
0
mohittpattel1 week ago
C++ code with explanation.
class Solution{
public:
vector<int> maxSubMatrixSumQueries(vector<int> mat[], int n, int m,
vector<pair<int, int>> &queries, int q) {
// code here
vector<int> ans;
int pre_sum[n + 1][m + 1];
// make the left most row 0
for (int i = 0; i <= n; i++)
pre_sum[i][0] = 0;
// make the right most row 0
for (int i = 0; i <= m; i++)
pre_sum[0][i] = 0;
// calculate the presum of the matrix
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
pre_sum[i][j] = mat[i - 1][j - 1] + pre_sum[i - 1][j] + pre_sum[i][j - 1] - pre_sum[i - 1][j - 1];
}
// Then calculate the maximum and put intothe array
for (pair<int, int> pr : queries)
{
int max = 0, temp, k = pr.first, l = pr.second;
for (int i = k; i <= n; i++)
{
for (int j = l; j <= m; j++)
{
temp = pre_sum[i][j] - pre_sum[i][j - l] - pre_sum[i - k][j] + pre_sum[i - k][j - l];
if (temp > max)
max = temp;
}
}
ans.push_back(max);
}
return ans;
}
};
0
D Sathwik9 months ago
D Sathwik
https://uploads.disquscdn.c...
0
Yash Patil10 months ago
Yash Patil
int[] maxSubMatrixSumQueries(int[][] arr1, int n, int m, int[][] queries, int q) { int[][]dp =new int[n+1][m+1]; int []res =new int[queries.length]; for(int i=1;i<dp.length;i++) {="" for(int="" j="1;j<dp[0].length;j++)" {="" dp[i][j]="arr1[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];" }="" }="" int="" count="0;" for(int="" []x1:queries)="" {="" int="" row="x1[0];" int="" col="x1[1];" int="" val="maxSum(dp,row,col);" res[count++]="val;" }="" return="" res;="" }="" int="" maxsum(int="" [][]dp,int="" row,int="" col)="" {="" int="" max="Integer.MIN_VALUE;" for(int="" i="1;i<dp.length;i++)" {="" for(int="" j="1;j<dp[i].length;j++)" {="" int="" sum="Integer.MIN_VALUE;" if(i-row="">=0&&j-col>=0) { sum=dp[i][j]-dp[i-row][j]-dp[i][j-col]+dp[i-row][j-col]; max=Math.max(sum,max); } } } return max; }
0
SANDEEP MANDAL
This comment was deleted.
0
Shishank Rawat11 months ago
Shishank Rawat
This is my C++ solution:Thank me by Upvoting.
https://uploads.disquscdn.c...
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": 444,
"s": 226,
"text": "Given a matrix of size NxM and a list of queries containing (a,b) pairs. Find the maximum sum among all (a x b) sub-matrices of the matrix. \nNote: The rows and columns of the submatrix must be contiguous. For example:"
},
{
"code": null,
"e": 456,
"s": 444,
"text": "\nExample 1:"
},
{
"code": null,
"e": 888,
"s": 456,
"text": "Input:\nN = 3, M = 4\nmat[][] = {{1, 2, 3, 9}, \n {4, 5, 6, 2}, \n {8, 3, 2, 6}}\nQ = 1\nQueries[] = {(3,2)}\n\nOutput: 28\n\nExplanation:\nHere a = 3 and b = 2.\n\nThe first 3x2 submatrix is:\n1 2\n4 5\n8 3\nThe sum of elements in this is 23.\n\nThe second 3x2 submatrix is:\n2 3\n5 6\n3 2\nThe sum of elements in this is 21.\n\nThe third 3x2 submatrix is:\n3 9\n6 2\n2 6\nThe sum of elements in this is 28.\n\nThe maximum among these is 28."
},
{
"code": null,
"e": 900,
"s": 888,
"text": "\nExample 2:"
},
{
"code": null,
"e": 1057,
"s": 900,
"text": "Input:\nN = 3, M = 4\nmat[][] = {{1, 2, 3, 9}, \n {4, 5, 6, 2}, \n {8, 3, 2, 6}}\nQ = 3\nQueries[] = {(1, 1), (2, 2), (3, 3)}\n\nOutput: 9 20 38"
},
{
"code": null,
"e": 1069,
"s": 1057,
"text": "\nExample 3:"
},
{
"code": null,
"e": 1207,
"s": 1069,
"text": "Input:\nN = 2, M = 7\nmat[][] = {{49, 44, 46, 22, 24, 11, 2}, \n {5, 25, 24, 28, 20, 47, 47}}\nQ = 1\nQueries = {(2, 1)}\n\nOutput: 70"
},
{
"code": null,
"e": 1486,
"s": 1207,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maxSubMatrixSumQueries() which takes the 2D array of integers mat, n, m, queries and q as input parameters and returns an array of integers denoting the maximum sum for each query."
},
{
"code": null,
"e": 1556,
"s": 1488,
"text": "Expected Time Complexity: O(Q*N*M)\nExpected Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 1647,
"s": 1558,
"text": "Constraints:\n1 ≤ N ≤ 103\n1 ≤ M ≤ 103\n1 ≤ Q ≤ 100\n1 ≤ a ≤ N\n1 ≤ b ≤ M\n1 ≤ mat[i][j] ≤ 103"
},
{
"code": null,
"e": 1649,
"s": 1647,
"text": "0"
},
{
"code": null,
"e": 1672,
"s": 1649,
"text": "mohittpattel1 week ago"
},
{
"code": null,
"e": 1699,
"s": 1672,
"text": "C++ code with explanation."
},
{
"code": null,
"e": 3019,
"s": 1699,
"text": "class Solution{\npublic:\n vector<int> maxSubMatrixSumQueries(vector<int> mat[], int n, int m,\n vector<pair<int, int>> &queries, int q) {\n // code here\n vector<int> ans;\n int pre_sum[n + 1][m + 1];\n // make the left most row 0\n for (int i = 0; i <= n; i++)\n pre_sum[i][0] = 0;\n // make the right most row 0\n for (int i = 0; i <= m; i++)\n pre_sum[0][i] = 0;\n \n // calculate the presum of the matrix\n for (int i = 1; i <= n; i++)\n {\n for (int j = 1; j <= m; j++)\n pre_sum[i][j] = mat[i - 1][j - 1] + pre_sum[i - 1][j] + pre_sum[i][j - 1] - pre_sum[i - 1][j - 1];\n }\n \n // Then calculate the maximum and put intothe array\n for (pair<int, int> pr : queries)\n {\n int max = 0, temp, k = pr.first, l = pr.second;\n \n for (int i = k; i <= n; i++)\n {\n for (int j = l; j <= m; j++)\n {\n temp = pre_sum[i][j] - pre_sum[i][j - l] - pre_sum[i - k][j] + pre_sum[i - k][j - l];\n if (temp > max)\n max = temp;\n }\n }\n ans.push_back(max);\n }\n return ans;\n }\n};"
},
{
"code": null,
"e": 3021,
"s": 3019,
"text": "0"
},
{
"code": null,
"e": 3043,
"s": 3021,
"text": "D Sathwik9 months ago"
},
{
"code": null,
"e": 3053,
"s": 3043,
"text": "D Sathwik"
},
{
"code": null,
"e": 3084,
"s": 3053,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 3086,
"s": 3084,
"text": "0"
},
{
"code": null,
"e": 3110,
"s": 3086,
"text": "Yash Patil10 months ago"
},
{
"code": null,
"e": 3121,
"s": 3110,
"text": "Yash Patil"
},
{
"code": null,
"e": 4054,
"s": 3121,
"text": "int[] maxSubMatrixSumQueries(int[][] arr1, int n, int m, int[][] queries, int q) { int[][]dp =new int[n+1][m+1]; int []res =new int[queries.length]; for(int i=1;i<dp.length;i++) {=\"\" for(int=\"\" j=\"1;j<dp[0].length;j++)\" {=\"\" dp[i][j]=\"arr1[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];\" }=\"\" }=\"\" int=\"\" count=\"0;\" for(int=\"\" []x1:queries)=\"\" {=\"\" int=\"\" row=\"x1[0];\" int=\"\" col=\"x1[1];\" int=\"\" val=\"maxSum(dp,row,col);\" res[count++]=\"val;\" }=\"\" return=\"\" res;=\"\" }=\"\" int=\"\" maxsum(int=\"\" [][]dp,int=\"\" row,int=\"\" col)=\"\" {=\"\" int=\"\" max=\"Integer.MIN_VALUE;\" for(int=\"\" i=\"1;i<dp.length;i++)\" {=\"\" for(int=\"\" j=\"1;j<dp[i].length;j++)\" {=\"\" int=\"\" sum=\"Integer.MIN_VALUE;\" if(i-row=\"\">=0&&j-col>=0) { sum=dp[i][j]-dp[i-row][j]-dp[i][j-col]+dp[i-row][j-col]; max=Math.max(sum,max); } } } return max; }"
},
{
"code": null,
"e": 4056,
"s": 4054,
"text": "0"
},
{
"code": null,
"e": 4071,
"s": 4056,
"text": "SANDEEP MANDAL"
},
{
"code": null,
"e": 4097,
"s": 4071,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4099,
"s": 4097,
"text": "0"
},
{
"code": null,
"e": 4127,
"s": 4099,
"text": "Shishank Rawat11 months ago"
},
{
"code": null,
"e": 4142,
"s": 4127,
"text": "Shishank Rawat"
},
{
"code": null,
"e": 4188,
"s": 4142,
"text": "This is my C++ solution:Thank me by Upvoting."
},
{
"code": null,
"e": 4220,
"s": 4188,
"text": " https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 4366,
"s": 4220,
"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": 4402,
"s": 4366,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4412,
"s": 4402,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4422,
"s": 4412,
"text": "\nContest\n"
},
{
"code": null,
"e": 4485,
"s": 4422,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4633,
"s": 4485,
"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": 4841,
"s": 4633,
"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": 4947,
"s": 4841,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JavaScript - Array concat() Method
|
Javascript array concat() method returns a new array comprised of this array joined with two or more arrays.
The syntax of concat() method is as follows −
array.concat(value1, value2, ..., valueN);
valueN − Arrays and/or values to concatenate to the resulting array.
This method returns an array object representing the resultant array, a concatenation of the current and given array(s).
Try the following example.
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type = "text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
document.write("alphaNumeric : " + alphaNumeric );
</script>
</body>
</html>
alphaNumeric : a,b,c,1,2,3
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2575,
"s": 2466,
"text": "Javascript array concat() method returns a new array comprised of this array joined with two or more arrays."
},
{
"code": null,
"e": 2621,
"s": 2575,
"text": "The syntax of concat() method is as follows −"
},
{
"code": null,
"e": 2665,
"s": 2621,
"text": "array.concat(value1, value2, ..., valueN);\n"
},
{
"code": null,
"e": 2734,
"s": 2665,
"text": "valueN − Arrays and/or values to concatenate to the resulting array."
},
{
"code": null,
"e": 2855,
"s": 2734,
"text": "This method returns an array object representing the resultant array, a concatenation of the current and given array(s)."
},
{
"code": null,
"e": 2882,
"s": 2855,
"text": "Try the following example."
},
{
"code": null,
"e": 3244,
"s": 2882,
"text": "<html>\n <head>\n <title>JavaScript Array concat Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var alpha = [\"a\", \"b\", \"c\"];\n var numeric = [1, 2, 3];\n var alphaNumeric = alpha.concat(numeric);\n document.write(\"alphaNumeric : \" + alphaNumeric ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3273,
"s": 3244,
"text": "alphaNumeric : a,b,c,1,2,3 \n"
},
{
"code": null,
"e": 3308,
"s": 3273,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3322,
"s": 3308,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3356,
"s": 3322,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3370,
"s": 3356,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3405,
"s": 3370,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3422,
"s": 3405,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3457,
"s": 3422,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3474,
"s": 3457,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3507,
"s": 3474,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3535,
"s": 3507,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3569,
"s": 3535,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3597,
"s": 3569,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3604,
"s": 3597,
"text": " Print"
},
{
"code": null,
"e": 3615,
"s": 3604,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.