title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
JSP | ScriptletTag - GeeksforGeeks
|
09 Aug, 2018
Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use of servlets. Small programs that are specified in the Web page and run on the Web server to modify the Web page before it is sent to the user who requested it.
There are total three Scripting Element in JSP
Scriptlet tagExpression tagDeclaration tag
Scriptlet tag
Expression tag
Declaration tag
Using these tags we can insert our java code in JSP.
Scriptlet tag
This tag allow user to insert java code in JSP. The statement which is written will be moved to jspservice() using JSP container while generating servlet from JSP. When client make a request, JSP service method is invoked and after that the content which is written inside the scriptlet tag executes.
<html> <body> <% out.print("GeeksforGeeks"); %> <!-- scriptlet tag --></body> </html>
Explanation
The Syntax of JSP Sriptlet tag is begin with ”.
We can write our java code inside this tag.
In java we use System.out.println for printing anything on console. In JSP, we use only out.print to write something on console because the out we’re referring to isn’t System.out, it’s a variable in the effective method that wraps our JSP page.
System.out writes to the servlet container’s console (usually a log file); out is a different class entirely which writes to the output stream for the generated response.
Here we are creating and HTML file to take username from user.save this file as index.html.
<!--index.html --><!-- Example of JSP code which prints the Username --><html> <body> <form action="Geeks.jsp"> <!-- move the control to Geeks.jsp when Submit button is click --> Enter Username:<input type="text" name="username"> <input type="submit" value="Submit"><br/> </form> </body> </html>
Here we are creating A jsp file names as Geeks.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><title>Insert title here</title></head> <body><% String name=request.getParameter("username"); out.print("Hello "+name); %> </body> </html>
output
Java-JSP
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexity and Space Complexity
Mutex vs Semaphore
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Understanding "extern" keyword in C
SQL | Views
How to write a Pseudo Code?
SQL | GROUP BY
Recursive Practice Problems with Solutions
Little and Big Endian Mystery
|
[
{
"code": null,
"e": 24145,
"s": 24117,
"text": "\n09 Aug, 2018"
},
{
"code": null,
"e": 24415,
"s": 24145,
"text": "Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use of servlets. Small programs that are specified in the Web page and run on the Web server to modify the Web page before it is sent to the user who requested it."
},
{
"code": null,
"e": 24462,
"s": 24415,
"text": "There are total three Scripting Element in JSP"
},
{
"code": null,
"e": 24505,
"s": 24462,
"text": "Scriptlet tagExpression tagDeclaration tag"
},
{
"code": null,
"e": 24519,
"s": 24505,
"text": "Scriptlet tag"
},
{
"code": null,
"e": 24534,
"s": 24519,
"text": "Expression tag"
},
{
"code": null,
"e": 24550,
"s": 24534,
"text": "Declaration tag"
},
{
"code": null,
"e": 24603,
"s": 24550,
"text": "Using these tags we can insert our java code in JSP."
},
{
"code": null,
"e": 24617,
"s": 24603,
"text": "Scriptlet tag"
},
{
"code": null,
"e": 24918,
"s": 24617,
"text": "This tag allow user to insert java code in JSP. The statement which is written will be moved to jspservice() using JSP container while generating servlet from JSP. When client make a request, JSP service method is invoked and after that the content which is written inside the scriptlet tag executes."
},
{
"code": "<html> <body> <% out.print(\"GeeksforGeeks\"); %> <!-- scriptlet tag --></body> </html> ",
"e": 25009,
"s": 24918,
"text": null
},
{
"code": null,
"e": 25021,
"s": 25009,
"text": "Explanation"
},
{
"code": null,
"e": 25069,
"s": 25021,
"text": "The Syntax of JSP Sriptlet tag is begin with ”."
},
{
"code": null,
"e": 25113,
"s": 25069,
"text": "We can write our java code inside this tag."
},
{
"code": null,
"e": 25359,
"s": 25113,
"text": "In java we use System.out.println for printing anything on console. In JSP, we use only out.print to write something on console because the out we’re referring to isn’t System.out, it’s a variable in the effective method that wraps our JSP page."
},
{
"code": null,
"e": 25530,
"s": 25359,
"text": "System.out writes to the servlet container’s console (usually a log file); out is a different class entirely which writes to the output stream for the generated response."
},
{
"code": null,
"e": 25622,
"s": 25530,
"text": "Here we are creating and HTML file to take username from user.save this file as index.html."
},
{
"code": "<!--index.html --><!-- Example of JSP code which prints the Username --><html> <body> <form action=\"Geeks.jsp\"> <!-- move the control to Geeks.jsp when Submit button is click --> Enter Username:<input type=\"text\" name=\"username\"> <input type=\"submit\" value=\"Submit\"><br/> </form> </body> </html> ",
"e": 25931,
"s": 25622,
"text": null
},
{
"code": null,
"e": 25982,
"s": 25931,
"text": "Here we are creating A jsp file names as Geeks.jsp"
},
{
"code": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html> <head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"><title>Insert title here</title></head> <body><% String name=request.getParameter(\"username\"); out.print(\"Hello \"+name); %> </body> </html>",
"e": 26399,
"s": 25982,
"text": null
},
{
"code": null,
"e": 26406,
"s": 26399,
"text": "output"
},
{
"code": null,
"e": 26415,
"s": 26406,
"text": "Java-JSP"
},
{
"code": null,
"e": 26424,
"s": 26415,
"text": "Articles"
},
{
"code": null,
"e": 26522,
"s": 26424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26531,
"s": 26522,
"text": "Comments"
},
{
"code": null,
"e": 26544,
"s": 26531,
"text": "Old Comments"
},
{
"code": null,
"e": 26581,
"s": 26544,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 26600,
"s": 26581,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 26663,
"s": 26600,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
},
{
"code": null,
"e": 26699,
"s": 26663,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 26711,
"s": 26699,
"text": "SQL | Views"
},
{
"code": null,
"e": 26739,
"s": 26711,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 26754,
"s": 26739,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 26797,
"s": 26754,
"text": "Recursive Practice Problems with Solutions"
}
] |
Card Flipping Game in C++
|
Suppose on a table are N cards, with a positive integer printed on both side of each card (possibly different). We have to flip any number of cards, and after we choose one card. If the number X on the back side of the chosen card is not on the front of any card, then the number X is known as good. We have to find the smallest number that is good? When no number is good, return 0. Here, fronts[i] and backs[i] represent the number on the front and back side of card i. A flip will swap the front and back numbers, so the value on the front is now on the back and vice versa.
So if the input is like fronts = [1,2,4,4,7] and backs = [1,3,4,1,3], then the output will be 2. So if we flip the second card, the front value will be [1,3,4,4,7], and the backs will be [1,2,4,1,3]. We will choose the second card, which has number 2 on the back, and it is not on the front of any card, so 2 is a good number.
To solve this, we will follow these steps −
define a set s, n := size of fronts, ret := inf
for i in range 0 to n – 1if fronts[i] = back[i], then insert fronts[i] into s
if fronts[i] = back[i], then insert fronts[i] into s
for i in range 0 to n – 1if fronts[i] in set then ret := minimum of ret and fronts[i]
if fronts[i] in set then ret := minimum of ret and fronts[i]
for i in range 0 to n – 1if backs[i] not in set then ret := minimum of ret and backs[i]
if backs[i] not in set then ret := minimum of ret and backs[i]
return 0 when ret = inf, otherwise ret.
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int flipgame(vector<int>& fronts, vector<int>& backs) {
set <int> s;
int n = fronts.size();
int ret = INT_MAX;
for(int i = 0; i < n; i++){
if(fronts[i] == backs[i])s.insert(fronts[i]);
}
for(int i = 0; i <n; i++ ){
if(s.count(fronts[i]) == 0) ret = min(ret, fronts[i]);
}
for(int i = 0; i <n; i++ ){
if(s.count(backs[i]) == 0) ret = min(ret, backs[i]);
}
return ret == INT_MAX? 0 : ret;
}
};
main(){
vector<int> v1 = {1,2,4,4,7};
vector<int> v2 = {1,3,4,1,3};
Solution ob;
cout << (ob.flipgame(v1, v2));
}
[1,2,4,4,7]
[1,3,4,1,3]
2
|
[
{
"code": null,
"e": 1640,
"s": 1062,
"text": "Suppose on a table are N cards, with a positive integer printed on both side of each card (possibly different). We have to flip any number of cards, and after we choose one card. If the number X on the back side of the chosen card is not on the front of any card, then the number X is known as good. We have to find the smallest number that is good? When no number is good, return 0. Here, fronts[i] and backs[i] represent the number on the front and back side of card i. A flip will swap the front and back numbers, so the value on the front is now on the back and vice versa."
},
{
"code": null,
"e": 1967,
"s": 1640,
"text": "So if the input is like fronts = [1,2,4,4,7] and backs = [1,3,4,1,3], then the output will be 2. So if we flip the second card, the front value will be [1,3,4,4,7], and the backs will be [1,2,4,1,3]. We will choose the second card, which has number 2 on the back, and it is not on the front of any card, so 2 is a good number."
},
{
"code": null,
"e": 2011,
"s": 1967,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2059,
"s": 2011,
"text": "define a set s, n := size of fronts, ret := inf"
},
{
"code": null,
"e": 2137,
"s": 2059,
"text": "for i in range 0 to n – 1if fronts[i] = back[i], then insert fronts[i] into s"
},
{
"code": null,
"e": 2190,
"s": 2137,
"text": "if fronts[i] = back[i], then insert fronts[i] into s"
},
{
"code": null,
"e": 2276,
"s": 2190,
"text": "for i in range 0 to n – 1if fronts[i] in set then ret := minimum of ret and fronts[i]"
},
{
"code": null,
"e": 2337,
"s": 2276,
"text": "if fronts[i] in set then ret := minimum of ret and fronts[i]"
},
{
"code": null,
"e": 2425,
"s": 2337,
"text": "for i in range 0 to n – 1if backs[i] not in set then ret := minimum of ret and backs[i]"
},
{
"code": null,
"e": 2488,
"s": 2425,
"text": "if backs[i] not in set then ret := minimum of ret and backs[i]"
},
{
"code": null,
"e": 2528,
"s": 2488,
"text": "return 0 when ret = inf, otherwise ret."
},
{
"code": null,
"e": 2598,
"s": 2528,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2609,
"s": 2598,
"text": " Live Demo"
},
{
"code": null,
"e": 3294,
"s": 2609,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int flipgame(vector<int>& fronts, vector<int>& backs) {\n set <int> s;\n int n = fronts.size();\n int ret = INT_MAX;\n for(int i = 0; i < n; i++){\n if(fronts[i] == backs[i])s.insert(fronts[i]);\n }\n for(int i = 0; i <n; i++ ){\n if(s.count(fronts[i]) == 0) ret = min(ret, fronts[i]);\n }\n for(int i = 0; i <n; i++ ){\n if(s.count(backs[i]) == 0) ret = min(ret, backs[i]);\n }\n return ret == INT_MAX? 0 : ret;\n }\n};\nmain(){\n vector<int> v1 = {1,2,4,4,7};\n vector<int> v2 = {1,3,4,1,3};\n Solution ob;\n cout << (ob.flipgame(v1, v2));\n}"
},
{
"code": null,
"e": 3318,
"s": 3294,
"text": "[1,2,4,4,7]\n[1,3,4,1,3]"
},
{
"code": null,
"e": 3320,
"s": 3318,
"text": "2"
}
] |
Initialization of local variable in a conditional block in Java - GeeksforGeeks
|
11 Sep, 2018
Java comprises 5 conditional blocks namely – if, switch, while, for and try.In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn’t let you leave a local variable uninitialized.
While initializing local variable inside a conditional block, one must bear the following 3 details in mind:1. If the specified condition is true, and ‘values’ are provided in the condition, the program compiles fine.2. If the specified condition is true, but ‘variables’ are provided in the condition, we get a compilation error.3. If the specified condition is false, we get a compilation error.
The above-given points are true for both primitive and reference type local variables.
Example:The code below will give a compilation error.
// Java program to demonstrate error if we// assign value to an uninitialized variable// only in if block.public class InitTesting { public static void main(String args[]) { int i = 100; int j; // Note that the condition is false if (i > 500) j = i + 5; System.out.println("j :" + j); }}
Output:
prog.java:8: error: variable j might not have been initialized
System.out.println("j :" + j);
^
1 error
The condition in the if statement is false. Hence, local variable ‘j’ never gets initialized. Thus, trying to reference uninitialized variable ‘j’ in line8 gives a compilation error.To avoid this, initialize your local variable to a default value outside the conditional block.The code below works fine-
// Java program to demonstrate that the above// error is gone if we initialize the variable.public class InitTesting { public static void main(String args[]) { int i = 100; int j = 0; // Note that the condition is false if (i > 500) { j = i + 5; } System.out.println("j :" + j); }}
Output:
j :0
Also, in Java, ‘values’ are read at compile time. But, ‘variables’ are read at run-time. Hence, when variables are a part of the condition, and another variable is initialized inside the conditional block, it gives an unexpected compile-time error.
Example: Have a look at the code below:
// Java program to demonstrate error even if// condition is true. class Test { public static void main(String args[]) { int a = 90; int b = 80; int i; // The condition is true if (a > b) { i = a + 5; } System.out.println("i :" + i); }}
Output:
prog.java:9: error: variable i might not have been initialized
System.out.println("i :" + i);
^
1 error
It gives a compilation error irrespective of the condition being true or false because Java didn’t read variables at compile time and thus ‘i’ isn’t initialized.
On the other hand, this doesn’t happen if values are specified instead of variables.
// Java program to demonstrate that there is// no error if we constants in if condition.class Test { public static void main(String args[]) { int i; if (90 > 80) { i = a + 5; } System.out.println("i :" + i); }}
Output:
i :95
java-basics
Java-Data Types
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24052,
"s": 24024,
"text": "\n11 Sep, 2018"
},
{
"code": null,
"e": 24313,
"s": 24052,
"text": "Java comprises 5 conditional blocks namely – if, switch, while, for and try.In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn’t let you leave a local variable uninitialized."
},
{
"code": null,
"e": 24711,
"s": 24313,
"text": "While initializing local variable inside a conditional block, one must bear the following 3 details in mind:1. If the specified condition is true, and ‘values’ are provided in the condition, the program compiles fine.2. If the specified condition is true, but ‘variables’ are provided in the condition, we get a compilation error.3. If the specified condition is false, we get a compilation error."
},
{
"code": null,
"e": 24798,
"s": 24711,
"text": "The above-given points are true for both primitive and reference type local variables."
},
{
"code": null,
"e": 24852,
"s": 24798,
"text": "Example:The code below will give a compilation error."
},
{
"code": "// Java program to demonstrate error if we// assign value to an uninitialized variable// only in if block.public class InitTesting { public static void main(String args[]) { int i = 100; int j; // Note that the condition is false if (i > 500) j = i + 5; System.out.println(\"j :\" + j); }}",
"e": 25208,
"s": 24852,
"text": null
},
{
"code": null,
"e": 25366,
"s": 25208,
"text": " Output: \nprog.java:8: error: variable j might not have been initialized\n System.out.println(\"j :\" + j);\n ^\n1 error\n"
},
{
"code": null,
"e": 25670,
"s": 25366,
"text": "The condition in the if statement is false. Hence, local variable ‘j’ never gets initialized. Thus, trying to reference uninitialized variable ‘j’ in line8 gives a compilation error.To avoid this, initialize your local variable to a default value outside the conditional block.The code below works fine-"
},
{
"code": "// Java program to demonstrate that the above// error is gone if we initialize the variable.public class InitTesting { public static void main(String args[]) { int i = 100; int j = 0; // Note that the condition is false if (i > 500) { j = i + 5; } System.out.println(\"j :\" + j); }}",
"e": 26016,
"s": 25670,
"text": null
},
{
"code": null,
"e": 26031,
"s": 26016,
"text": " Output:\nj :0\n"
},
{
"code": null,
"e": 26280,
"s": 26031,
"text": "Also, in Java, ‘values’ are read at compile time. But, ‘variables’ are read at run-time. Hence, when variables are a part of the condition, and another variable is initialized inside the conditional block, it gives an unexpected compile-time error."
},
{
"code": null,
"e": 26320,
"s": 26280,
"text": "Example: Have a look at the code below:"
},
{
"code": "// Java program to demonstrate error even if// condition is true. class Test { public static void main(String args[]) { int a = 90; int b = 80; int i; // The condition is true if (a > b) { i = a + 5; } System.out.println(\"i :\" + i); }}",
"e": 26628,
"s": 26320,
"text": null
},
{
"code": null,
"e": 26785,
"s": 26628,
"text": " Output:\nprog.java:9: error: variable i might not have been initialized\n System.out.println(\"i :\" + i);\n ^\n1 error\n"
},
{
"code": null,
"e": 26947,
"s": 26785,
"text": "It gives a compilation error irrespective of the condition being true or false because Java didn’t read variables at compile time and thus ‘i’ isn’t initialized."
},
{
"code": null,
"e": 27032,
"s": 26947,
"text": "On the other hand, this doesn’t happen if values are specified instead of variables."
},
{
"code": "// Java program to demonstrate that there is// no error if we constants in if condition.class Test { public static void main(String args[]) { int i; if (90 > 80) { i = a + 5; } System.out.println(\"i :\" + i); }}",
"e": 27291,
"s": 27032,
"text": null
},
{
"code": null,
"e": 27307,
"s": 27291,
"text": " Output:\ni :95\n"
},
{
"code": null,
"e": 27319,
"s": 27307,
"text": "java-basics"
},
{
"code": null,
"e": 27335,
"s": 27319,
"text": "Java-Data Types"
},
{
"code": null,
"e": 27340,
"s": 27335,
"text": "Java"
},
{
"code": null,
"e": 27345,
"s": 27340,
"text": "Java"
},
{
"code": null,
"e": 27443,
"s": 27345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27452,
"s": 27443,
"text": "Comments"
},
{
"code": null,
"e": 27465,
"s": 27452,
"text": "Old Comments"
},
{
"code": null,
"e": 27497,
"s": 27465,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27527,
"s": 27497,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27546,
"s": 27527,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27597,
"s": 27546,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27628,
"s": 27597,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27646,
"s": 27628,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27678,
"s": 27646,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27698,
"s": 27678,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27710,
"s": 27698,
"text": "Set in Java"
}
] |
What is aggregation in Java?
|
When an object A contains a reference to another object B or we can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation.
Aggregation helps in reusing the code. Object B can have utility methods and which can be utilized by multiple objects. Whichever class has object B then it can utilize its methods.
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle {
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.
In the Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
This concept of containing an object to do action is termed as Aggregation.
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "When an object A contains a reference to another object B or we can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation."
},
{
"code": null,
"e": 1399,
"s": 1217,
"text": "Aggregation helps in reusing the code. Object B can have utility methods and which can be utilized by multiple objects. Whichever class has object B then it can utilize its methods."
},
{
"code": null,
"e": 1502,
"s": 1399,
"text": "public class Vehicle{}\npublic class Speed{}\n\npublic class Van extends Vehicle {\n private Speed sp;\n}"
},
{
"code": null,
"e": 1736,
"s": 1502,
"text": "This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications."
},
{
"code": null,
"e": 2199,
"s": 1736,
"text": "In the Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.\nThis concept of containing an object to do action is termed as Aggregation."
}
] |
Check Data Type of each DataFrame Column in R - GeeksforGeeks
|
21 Apr, 2021
In this article, we will discuss how to identify the data type of variables in a column of a given dataframe using R Programming language. We will be using str() and sapply() function in this article to check the data type of each column in a dataframe.
Method 1: Using str() function
str() function in R Language is used for compactly displaying the internal structure of an R object. It can display even the internal structure of large lists which are nested. It provides one-liner output for the basic R objects letting the user know about the object and its constituents.
Example 1: In the code below, we are passing a dataframe as an argument in the str() function as we want to check its datatype. Notice the “name” column is identified as Factor, roll column is identified as num or numeric, date column is identified as Date(as we have used as.Date() function to convert it to the Date data type), pwd column is identified as logi or Logic data type.
Syntax: str(object, ...)
Parameter: object: Any R object about which information is required.
Code:
R
# sample dataframedf <- data.frame(name = c("Welcome", "to", "Geeks", "for", "Geeks"), roll = c(10, 40.1, 50.5, 80, 70), date = as.Date(c("2001-10-30","2000-01-21", "1999-02-16","1950-12-03" ,"1995-11-09")), pwd = c(FALSE, TRUE, TRUE, TRUE, FALSE) )# checks the data type of each columnstr(df)
Output:
'data.frame': 5 obs. of 4 variables:
$ name: Factor w/ 4 levels "for","Geeks",..: 4 3 2 1 2
$ roll: num 10 40.1 50.5 80 70
$ date: Date, format: "2001-10-30" "2000-01-21" ...
$ pwd : logi FALSE TRUE TRUE TRUE FALSE
Example 2:
Notice in the previous example “name” column is identified as Factor data type. We can pass “stringAsFactors=FALSE” as an argument while defining a dataframe if you want the “name” column to be identified as chr or character datatype.
Syntax:
stringAsFactors= FALSE
R
# sample dataframedf <- data.frame(name = c("Welcome", "to", "Geeks", "for", "Geeks"), roll = c(10, 40.1, 50.5, 80, 70), date = as.Date(c("2001-10-30","2000-01-21","1999-02-16", "1950-12-03","1995-11-09")), pwd = c(FALSE, TRUE, TRUE, TRUE, FALSE), stringsAsFactors = FALSE ) # checks the data type of each columnstr(df)
Output:
'data.frame': 5 obs. of 4 variables:
$ name: chr "Welcome" "to" "Geeks" "for" ...
$ roll: num 10 40.1 50.5 80 70
$ date: Date, format: "2001-10-30" "2000-01-21" ...
$ pwd : logi FALSE TRUE TRUE TRUE FALSE
Method 2: Using sapply() and class() function
sapply() function in R Language takes a list, vector, or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of the same length as the original set.
Syntax: sapply(X, FUN)
Parameters:
X: A vector or an object
FUN: Function applied to each element of x
The sapply() function takes an object(dataframe “df” in this case) and a function(class() in this case) as arguments, and it applies the function to each element of the object(dataframe in this case). In the code below, we have used sapply() function to apply class() function to each column of the dataframe, and the class() function returns the data type of the column.
Code:
R
# sample dataframedf <- data.frame(name = c("Welcome", "to", "Geeks", "for", "Geeks"), roll = c(10, 40.1, 50.5, 80, 70), date = as.Date(c("2001-10-30","2000-01-21","1999-02-16", "1950-12-03","1995-11-09")), pwd = c(FALSE, TRUE, TRUE, TRUE, FALSE), stringsAsFactors = FALSE ) # checks the data type of each columnsapply(df,class)
Output:
name roll date pwd
"character" "numeric" "Date" "logical"
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25497,
"s": 25242,
"text": "In this article, we will discuss how to identify the data type of variables in a column of a given dataframe using R Programming language. We will be using str() and sapply() function in this article to check the data type of each column in a dataframe. "
},
{
"code": null,
"e": 25528,
"s": 25497,
"text": "Method 1: Using str() function"
},
{
"code": null,
"e": 25820,
"s": 25528,
"text": "str() function in R Language is used for compactly displaying the internal structure of an R object. It can display even the internal structure of large lists which are nested. It provides one-liner output for the basic R objects letting the user know about the object and its constituents. "
},
{
"code": null,
"e": 26203,
"s": 25820,
"text": "Example 1: In the code below, we are passing a dataframe as an argument in the str() function as we want to check its datatype. Notice the “name” column is identified as Factor, roll column is identified as num or numeric, date column is identified as Date(as we have used as.Date() function to convert it to the Date data type), pwd column is identified as logi or Logic data type."
},
{
"code": null,
"e": 26228,
"s": 26203,
"text": "Syntax: str(object, ...)"
},
{
"code": null,
"e": 26297,
"s": 26228,
"text": "Parameter: object: Any R object about which information is required."
},
{
"code": null,
"e": 26303,
"s": 26297,
"text": "Code:"
},
{
"code": null,
"e": 26305,
"s": 26303,
"text": "R"
},
{
"code": "# sample dataframedf <- data.frame(name = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), roll = c(10, 40.1, 50.5, 80, 70), date = as.Date(c(\"2001-10-30\",\"2000-01-21\", \"1999-02-16\",\"1950-12-03\" ,\"1995-11-09\")), pwd = c(FALSE, TRUE, TRUE, TRUE, FALSE) )# checks the data type of each columnstr(df)",
"e": 26748,
"s": 26305,
"text": null
},
{
"code": null,
"e": 26756,
"s": 26748,
"text": "Output:"
},
{
"code": null,
"e": 26981,
"s": 26756,
"text": "'data.frame': 5 obs. of 4 variables:\n $ name: Factor w/ 4 levels \"for\",\"Geeks\",..: 4 3 2 1 2\n $ roll: num 10 40.1 50.5 80 70\n $ date: Date, format: \"2001-10-30\" \"2000-01-21\" ...\n $ pwd : logi FALSE TRUE TRUE TRUE FALSE"
},
{
"code": null,
"e": 26992,
"s": 26981,
"text": "Example 2:"
},
{
"code": null,
"e": 27227,
"s": 26992,
"text": "Notice in the previous example “name” column is identified as Factor data type. We can pass “stringAsFactors=FALSE” as an argument while defining a dataframe if you want the “name” column to be identified as chr or character datatype."
},
{
"code": null,
"e": 27235,
"s": 27227,
"text": "Syntax:"
},
{
"code": null,
"e": 27258,
"s": 27235,
"text": "stringAsFactors= FALSE"
},
{
"code": null,
"e": 27260,
"s": 27258,
"text": "R"
},
{
"code": "# sample dataframedf <- data.frame(name = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), roll = c(10, 40.1, 50.5, 80, 70), date = as.Date(c(\"2001-10-30\",\"2000-01-21\",\"1999-02-16\", \"1950-12-03\",\"1995-11-09\")), pwd = c(FALSE, TRUE, TRUE, TRUE, FALSE), stringsAsFactors = FALSE ) # checks the data type of each columnstr(df)",
"e": 27695,
"s": 27260,
"text": null
},
{
"code": null,
"e": 27703,
"s": 27695,
"text": "Output:"
},
{
"code": null,
"e": 27919,
"s": 27703,
"text": "'data.frame': 5 obs. of 4 variables:\n $ name: chr \"Welcome\" \"to\" \"Geeks\" \"for\" ...\n $ roll: num 10 40.1 50.5 80 70\n $ date: Date, format: \"2001-10-30\" \"2000-01-21\" ...\n $ pwd : logi FALSE TRUE TRUE TRUE FALSE"
},
{
"code": null,
"e": 27965,
"s": 27919,
"text": "Method 2: Using sapply() and class() function"
},
{
"code": null,
"e": 28190,
"s": 27965,
"text": "sapply() function in R Language takes a list, vector, or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of the same length as the original set."
},
{
"code": null,
"e": 28213,
"s": 28190,
"text": "Syntax: sapply(X, FUN)"
},
{
"code": null,
"e": 28225,
"s": 28213,
"text": "Parameters:"
},
{
"code": null,
"e": 28250,
"s": 28225,
"text": "X: A vector or an object"
},
{
"code": null,
"e": 28293,
"s": 28250,
"text": "FUN: Function applied to each element of x"
},
{
"code": null,
"e": 28665,
"s": 28293,
"text": "The sapply() function takes an object(dataframe “df” in this case) and a function(class() in this case) as arguments, and it applies the function to each element of the object(dataframe in this case). In the code below, we have used sapply() function to apply class() function to each column of the dataframe, and the class() function returns the data type of the column."
},
{
"code": null,
"e": 28671,
"s": 28665,
"text": "Code:"
},
{
"code": null,
"e": 28673,
"s": 28671,
"text": "R"
},
{
"code": "# sample dataframedf <- data.frame(name = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), roll = c(10, 40.1, 50.5, 80, 70), date = as.Date(c(\"2001-10-30\",\"2000-01-21\",\"1999-02-16\", \"1950-12-03\",\"1995-11-09\")), pwd = c(FALSE, TRUE, TRUE, TRUE, FALSE), stringsAsFactors = FALSE ) # checks the data type of each columnsapply(df,class)",
"e": 29117,
"s": 28673,
"text": null
},
{
"code": null,
"e": 29125,
"s": 29117,
"text": "Output:"
},
{
"code": null,
"e": 29217,
"s": 29125,
"text": " name roll date pwd \n\"character\" \"numeric\" \"Date\" \"logical\" "
},
{
"code": null,
"e": 29224,
"s": 29217,
"text": "Picked"
},
{
"code": null,
"e": 29245,
"s": 29224,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 29257,
"s": 29245,
"text": "R-DataFrame"
},
{
"code": null,
"e": 29268,
"s": 29257,
"text": "R Language"
},
{
"code": null,
"e": 29279,
"s": 29268,
"text": "R Programs"
},
{
"code": null,
"e": 29377,
"s": 29279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29429,
"s": 29377,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29467,
"s": 29429,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29502,
"s": 29467,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29560,
"s": 29502,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29609,
"s": 29560,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29667,
"s": 29609,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29716,
"s": 29667,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29766,
"s": 29716,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29809,
"s": 29766,
"text": "Replace Specific Characters in String in R"
}
] |
Degree of Vertex of a Graph
|
It is the number of vertices adjacent to a vertex V.
Notation − deg(V).
In a simple graph with n number of vertices, the degree of any vertices is −
deg(v) = n – 1 ∀ v ∈ G
A vertex can form an edge with all other vertices except by itself. So the degree of a vertex will be up to the number of vertices in the graph minus 1. This 1 is for the self-vertex as it cannot form a loop by itself. If there is a loop at any of the vertices, then it is not a Simple Graph.
Degree of vertex can be considered under two cases of graphs −
Undirected Graph
Directed Graph
An undirected graph has no directed edges. Consider the following examples.
Take a look at the following graph −
In the above Undirected Graph,
deg(a) = 2, as there are 2 edges meeting at vertex 'a'.
deg(a) = 2, as there are 2 edges meeting at vertex 'a'.
deg(b) = 3, as there are 3 edges meeting at vertex 'b'.
deg(b) = 3, as there are 3 edges meeting at vertex 'b'.
deg(c) = 1, as there is 1 edge formed at vertex 'c'So 'c' is a pendent vertex.
deg(c) = 1, as there is 1 edge formed at vertex 'c'
So 'c' is a pendent vertex.
deg(d) = 2, as there are 2 edges meeting at vertex 'd'.
deg(d) = 2, as there are 2 edges meeting at vertex 'd'.
deg(e) = 0, as there are 0 edges formed at vertex 'e'.So 'e' is an isolated vertex.
deg(e) = 0, as there are 0 edges formed at vertex 'e'.
So 'e' is an isolated vertex.
Take a look at the following graph −
In the above graph,
deg(a) = 2, deg(b) = 2, deg(c) = 2, deg(d) = 2, and deg(e) = 0.
The vertex 'e' is an isolated vertex. The graph does not have any pendent vertex.
In a directed graph, each vertex has an indegree and an outdegree.
Indegree of vertex V is the number of edges which are coming into the vertex V.
Indegree of vertex V is the number of edges which are coming into the vertex V.
Notation − deg−(V).
Notation − deg−(V).
Outdegree of vertex V is the number of edges which are going out from the vertex V.
Outdegree of vertex V is the number of edges which are going out from the vertex V.
Notation − deg+(V).
Notation − deg+(V).
Consider the following examples.
Take a look at the following directed graph. Vertex 'a' has two edges, 'ad' and 'ab', which are going outwards. Hence its outdegree is 2. Similarly, there is an edge 'ga', coming towards vertex 'a'. Hence the indegree of 'a' is 1.
The indegree and outdegree of other vertices are shown in the following table −
Take a look at the following directed graph. Vertex 'a' has an edge 'ae' going outwards from vertex 'a'. Hence its outdegree is 1. Similarly, the graph has an edge 'ba' coming towards vertex 'a'. Hence the indegree of 'a' is 1.
The indegree and outdegree of other vertices are shown in the following table −
|
[
{
"code": null,
"e": 1115,
"s": 1062,
"text": "It is the number of vertices adjacent to a vertex V."
},
{
"code": null,
"e": 1134,
"s": 1115,
"text": "Notation − deg(V)."
},
{
"code": null,
"e": 1211,
"s": 1134,
"text": "In a simple graph with n number of vertices, the degree of any vertices is −"
},
{
"code": null,
"e": 1234,
"s": 1211,
"text": "deg(v) = n – 1 ∀ v ∈ G"
},
{
"code": null,
"e": 1527,
"s": 1234,
"text": "A vertex can form an edge with all other vertices except by itself. So the degree of a vertex will be up to the number of vertices in the graph minus 1. This 1 is for the self-vertex as it cannot form a loop by itself. If there is a loop at any of the vertices, then it is not a Simple Graph."
},
{
"code": null,
"e": 1590,
"s": 1527,
"text": "Degree of vertex can be considered under two cases of graphs −"
},
{
"code": null,
"e": 1607,
"s": 1590,
"text": "Undirected Graph"
},
{
"code": null,
"e": 1622,
"s": 1607,
"text": "Directed Graph"
},
{
"code": null,
"e": 1698,
"s": 1622,
"text": "An undirected graph has no directed edges. Consider the following examples."
},
{
"code": null,
"e": 1735,
"s": 1698,
"text": "Take a look at the following graph −"
},
{
"code": null,
"e": 1766,
"s": 1735,
"text": "In the above Undirected Graph,"
},
{
"code": null,
"e": 1822,
"s": 1766,
"text": "deg(a) = 2, as there are 2 edges meeting at vertex 'a'."
},
{
"code": null,
"e": 1878,
"s": 1822,
"text": "deg(a) = 2, as there are 2 edges meeting at vertex 'a'."
},
{
"code": null,
"e": 1934,
"s": 1878,
"text": "deg(b) = 3, as there are 3 edges meeting at vertex 'b'."
},
{
"code": null,
"e": 1990,
"s": 1934,
"text": "deg(b) = 3, as there are 3 edges meeting at vertex 'b'."
},
{
"code": null,
"e": 2069,
"s": 1990,
"text": "deg(c) = 1, as there is 1 edge formed at vertex 'c'So 'c' is a pendent vertex."
},
{
"code": null,
"e": 2121,
"s": 2069,
"text": "deg(c) = 1, as there is 1 edge formed at vertex 'c'"
},
{
"code": null,
"e": 2149,
"s": 2121,
"text": "So 'c' is a pendent vertex."
},
{
"code": null,
"e": 2205,
"s": 2149,
"text": "deg(d) = 2, as there are 2 edges meeting at vertex 'd'."
},
{
"code": null,
"e": 2261,
"s": 2205,
"text": "deg(d) = 2, as there are 2 edges meeting at vertex 'd'."
},
{
"code": null,
"e": 2345,
"s": 2261,
"text": "deg(e) = 0, as there are 0 edges formed at vertex 'e'.So 'e' is an isolated vertex."
},
{
"code": null,
"e": 2400,
"s": 2345,
"text": "deg(e) = 0, as there are 0 edges formed at vertex 'e'."
},
{
"code": null,
"e": 2430,
"s": 2400,
"text": "So 'e' is an isolated vertex."
},
{
"code": null,
"e": 2467,
"s": 2430,
"text": "Take a look at the following graph −"
},
{
"code": null,
"e": 2487,
"s": 2467,
"text": "In the above graph,"
},
{
"code": null,
"e": 2551,
"s": 2487,
"text": "deg(a) = 2, deg(b) = 2, deg(c) = 2, deg(d) = 2, and deg(e) = 0."
},
{
"code": null,
"e": 2633,
"s": 2551,
"text": "The vertex 'e' is an isolated vertex. The graph does not have any pendent vertex."
},
{
"code": null,
"e": 2700,
"s": 2633,
"text": "In a directed graph, each vertex has an indegree and an outdegree."
},
{
"code": null,
"e": 2780,
"s": 2700,
"text": "Indegree of vertex V is the number of edges which are coming into the vertex V."
},
{
"code": null,
"e": 2860,
"s": 2780,
"text": "Indegree of vertex V is the number of edges which are coming into the vertex V."
},
{
"code": null,
"e": 2880,
"s": 2860,
"text": "Notation − deg−(V)."
},
{
"code": null,
"e": 2900,
"s": 2880,
"text": "Notation − deg−(V)."
},
{
"code": null,
"e": 2984,
"s": 2900,
"text": "Outdegree of vertex V is the number of edges which are going out from the vertex V."
},
{
"code": null,
"e": 3068,
"s": 2984,
"text": "Outdegree of vertex V is the number of edges which are going out from the vertex V."
},
{
"code": null,
"e": 3088,
"s": 3068,
"text": "Notation − deg+(V)."
},
{
"code": null,
"e": 3108,
"s": 3088,
"text": "Notation − deg+(V)."
},
{
"code": null,
"e": 3141,
"s": 3108,
"text": "Consider the following examples."
},
{
"code": null,
"e": 3372,
"s": 3141,
"text": "Take a look at the following directed graph. Vertex 'a' has two edges, 'ad' and 'ab', which are going outwards. Hence its outdegree is 2. Similarly, there is an edge 'ga', coming towards vertex 'a'. Hence the indegree of 'a' is 1."
},
{
"code": null,
"e": 3452,
"s": 3372,
"text": "The indegree and outdegree of other vertices are shown in the following table −"
},
{
"code": null,
"e": 3680,
"s": 3452,
"text": "Take a look at the following directed graph. Vertex 'a' has an edge 'ae' going outwards from vertex 'a'. Hence its outdegree is 1. Similarly, the graph has an edge 'ba' coming towards vertex 'a'. Hence the indegree of 'a' is 1."
},
{
"code": null,
"e": 3760,
"s": 3680,
"text": "The indegree and outdegree of other vertices are shown in the following table −"
}
] |
GitHub User insights using GitHub API — Data Collection and Analysis | by Karan Bhanot | Towards Data Science
|
As I was working with GitHub pages, I decided that I’d like to have some statistics about my GitHub projects on it. Thus, I decided to use GitHub’s own API to draw insights. As this might be useful to others as well, I decided to create it as a project and publish on GitHub itself. Check out the repository below:
https://github.com/kb22/GitHub-User-Insights-using-API
There are two parts to this project:
Data Collection — I used GitHub’s API using my credentials to fetch my repositories and some key information regarding them.Data Analysis — Using the data collected above, I drew some insights from the data.
Data Collection — I used GitHub’s API using my credentials to fetch my repositories and some key information regarding them.
Data Analysis — Using the data collected above, I drew some insights from the data.
Add your credentials to the file credentials.json. If your username is userABC and password is passXYZ, the json file should look like:
{ "username": "userABC", "password": "passXYZ"}
Once the changes to the json file are made, save the file. Then, simply run the file get_github_data.py to get data from your profile and save it to the files repos_info.csv and commits_info.csv. Use the following command to run the Python file:
python get_github_data.py
I first saved my credentials inside the credentials.json file.
After reading the credentials file, I used the username and password to create the authentication variable which I’ll use for GitHub API authentication. Authenticating while accessing our own account allows us to make 5000 calls per hour.
I’ll use the https://api.github.com/users/<USERNAME> API to get data for my account.
There are several keys in the response. From the json, I’ll extract user information such as name, location, email, bio, public_repos, and public gists. I’ll also keep some of the urls handy including repos_url, gists_url and blog.
At the time of this article, I have 36 public repositories and 208 public gists.
I’ll now use the repos_url to fetch all repositories. The url however limits the maximum number of repositories at 30 in each batch. Hence, I had to handle it.
I make a call to the endpoint, and if the number of repositories returned is 30, it means that there might be more repositories and I should check the next page. I append a parameter in the API called page with value set as 2, 3, 4.... based on the page I am referring to. If the repositories returned is less than 30, this means there are no more repositories and I end the loop.
As I have 36 repositories, I was able to fetch them all in two API calls and save the result in repos_data.
To get any further insights, I had to take a look at the response. So, I checked out the first repository information.
As we can see, there is a lot of information about each repository.
I decided to select the following for each repository:1. id: Unique id for the repository.2. name: The name of the repository.3. description: The description of the repository.4. created_at: The time and date when the repository was first created.5. updated_at: The time and date when the repository was last updated.6. login: Username of the owner of the repository.7. license: The license type (if any).8. has_wiki: A boolean that signifies if the repository has a wiki document.9. forks_count: Total forks of the repository.10. open_issues_count: Total issues opened in the repository.11. stargazers_count: The total stars on the repository.12. watchers_count: Total users watching the repository.13. url: The url of the repository.14. commits_url: The url for all commits in the repository.15. languages_url: The url for all languages in the repository.
For the commit url, I removed the end value inside the braces (including the braces). I created the languages_url myself from the repository url.
The dataframe repos_df now has all the repository information I needed. However, I wanted to take a step further and decided to extract all languages here itself and append it to the dataframe.
Languages for each repository can have multiple values, so I decided to combine all languages in the form of a comma separated list.
Once this was complete, I saved the dataframe to a file repos_info.csv.
I also had access to the commits url for each repository. I decided that I could collect the commits for each repository and save them to their own file too.
Just like the repositories API, the commits API is also limited to 30 commits in one call. So, using the same technique of using page parameter, I retrieved all commits. I took a look at the response json.
For each commit, I saved the repository Id the git commit belongs to, the sha value of the commit, the date of commit and the message of the commit.
I saved the dataframe data to the file commits_info.csv.
Now that the complete data is available, I decided to draw some insights out of the data.
I noticed that I had 36 repositories and 408 commits. I then decided to use the describe() method to take a look at the forks, watchers, issues and stars. I noticed the following:
I’ve had maximum forks as 67 while the minimum are 0.The number of watchers and stars go hand in hand.I’ve had no issues reported in any repository.
I’ve had maximum forks as 67 while the minimum are 0.
The number of watchers and stars go hand in hand.
I’ve had no issues reported in any repository.
I also observed that the two most common commit messages I’ve used are Update README.md and Initial commit. It appears that sometimes I do tend to update readme files on GitHub itself and use its default message as the commit message.
Next, I wanted to see how the commits were distributed amongst my various repositories. I combined the two datasets (repos and commits) based on the repository id and created a plot.
From the figure above, we can clearly see that I’ve had the maximum commits in IEEE MyEvent App, which is an Android application for event management. The second most committed repository is the one associated with IBM’s Applied Data Science Capstone course called Coursera_Capstone.
It’s been a long time since I started working on projects and pushing them to GitHub. I’ve worked the most during the year 2018 and 2019 and expect to see the same in the yearly analysis.
I have made maximum commits in this year itself even though it’s just June. The second place goes to the year 2016. I was pursuing my Bachelors in Computer Science back then and I had started working on my own projects and thus this high number of commits. I expected more commits in the year 2018 but I started late so probably there were less commits in total.
Let’s now break down the year 2019 and see how I progressed there.
I broke down the year into months and visualized the data on a bar plot.
It appears that I made the maximum commits in the month of March. There are still 6 days left in June but it has already taken the second place. The least commits were in January.
Let’s break down March, 2019 further.
Let’s also see the commit history in the month of March.
I made the maximum number of commits on March 2, 2019.
As my interest grew in Data Science, I worked on many projects using Python. Thus, Python would be the most dominant language.
I’ve worked on a variety of languages including HTML, CSS, C++, Java, and others. However, the most common is Jupyter Notebook. My code in Jupyter notebooks is written in Python 3 and thus Python is the most common language in all my projects.
In this article, I discussed the steps I used to collect GitHub data for my profile and then used the data to draw insights.
Hope you liked this. Do share your thoughts, ideas and suggestions. I’d love to hear from you.
|
[
{
"code": null,
"e": 487,
"s": 172,
"text": "As I was working with GitHub pages, I decided that I’d like to have some statistics about my GitHub projects on it. Thus, I decided to use GitHub’s own API to draw insights. As this might be useful to others as well, I decided to create it as a project and publish on GitHub itself. Check out the repository below:"
},
{
"code": null,
"e": 542,
"s": 487,
"text": "https://github.com/kb22/GitHub-User-Insights-using-API"
},
{
"code": null,
"e": 579,
"s": 542,
"text": "There are two parts to this project:"
},
{
"code": null,
"e": 787,
"s": 579,
"text": "Data Collection — I used GitHub’s API using my credentials to fetch my repositories and some key information regarding them.Data Analysis — Using the data collected above, I drew some insights from the data."
},
{
"code": null,
"e": 912,
"s": 787,
"text": "Data Collection — I used GitHub’s API using my credentials to fetch my repositories and some key information regarding them."
},
{
"code": null,
"e": 996,
"s": 912,
"text": "Data Analysis — Using the data collected above, I drew some insights from the data."
},
{
"code": null,
"e": 1132,
"s": 996,
"text": "Add your credentials to the file credentials.json. If your username is userABC and password is passXYZ, the json file should look like:"
},
{
"code": null,
"e": 1183,
"s": 1132,
"text": "{ \"username\": \"userABC\", \"password\": \"passXYZ\"}"
},
{
"code": null,
"e": 1429,
"s": 1183,
"text": "Once the changes to the json file are made, save the file. Then, simply run the file get_github_data.py to get data from your profile and save it to the files repos_info.csv and commits_info.csv. Use the following command to run the Python file:"
},
{
"code": null,
"e": 1455,
"s": 1429,
"text": "python get_github_data.py"
},
{
"code": null,
"e": 1518,
"s": 1455,
"text": "I first saved my credentials inside the credentials.json file."
},
{
"code": null,
"e": 1757,
"s": 1518,
"text": "After reading the credentials file, I used the username and password to create the authentication variable which I’ll use for GitHub API authentication. Authenticating while accessing our own account allows us to make 5000 calls per hour."
},
{
"code": null,
"e": 1842,
"s": 1757,
"text": "I’ll use the https://api.github.com/users/<USERNAME> API to get data for my account."
},
{
"code": null,
"e": 2074,
"s": 1842,
"text": "There are several keys in the response. From the json, I’ll extract user information such as name, location, email, bio, public_repos, and public gists. I’ll also keep some of the urls handy including repos_url, gists_url and blog."
},
{
"code": null,
"e": 2155,
"s": 2074,
"text": "At the time of this article, I have 36 public repositories and 208 public gists."
},
{
"code": null,
"e": 2315,
"s": 2155,
"text": "I’ll now use the repos_url to fetch all repositories. The url however limits the maximum number of repositories at 30 in each batch. Hence, I had to handle it."
},
{
"code": null,
"e": 2696,
"s": 2315,
"text": "I make a call to the endpoint, and if the number of repositories returned is 30, it means that there might be more repositories and I should check the next page. I append a parameter in the API called page with value set as 2, 3, 4.... based on the page I am referring to. If the repositories returned is less than 30, this means there are no more repositories and I end the loop."
},
{
"code": null,
"e": 2804,
"s": 2696,
"text": "As I have 36 repositories, I was able to fetch them all in two API calls and save the result in repos_data."
},
{
"code": null,
"e": 2923,
"s": 2804,
"text": "To get any further insights, I had to take a look at the response. So, I checked out the first repository information."
},
{
"code": null,
"e": 2991,
"s": 2923,
"text": "As we can see, there is a lot of information about each repository."
},
{
"code": null,
"e": 3849,
"s": 2991,
"text": "I decided to select the following for each repository:1. id: Unique id for the repository.2. name: The name of the repository.3. description: The description of the repository.4. created_at: The time and date when the repository was first created.5. updated_at: The time and date when the repository was last updated.6. login: Username of the owner of the repository.7. license: The license type (if any).8. has_wiki: A boolean that signifies if the repository has a wiki document.9. forks_count: Total forks of the repository.10. open_issues_count: Total issues opened in the repository.11. stargazers_count: The total stars on the repository.12. watchers_count: Total users watching the repository.13. url: The url of the repository.14. commits_url: The url for all commits in the repository.15. languages_url: The url for all languages in the repository."
},
{
"code": null,
"e": 3995,
"s": 3849,
"text": "For the commit url, I removed the end value inside the braces (including the braces). I created the languages_url myself from the repository url."
},
{
"code": null,
"e": 4189,
"s": 3995,
"text": "The dataframe repos_df now has all the repository information I needed. However, I wanted to take a step further and decided to extract all languages here itself and append it to the dataframe."
},
{
"code": null,
"e": 4322,
"s": 4189,
"text": "Languages for each repository can have multiple values, so I decided to combine all languages in the form of a comma separated list."
},
{
"code": null,
"e": 4394,
"s": 4322,
"text": "Once this was complete, I saved the dataframe to a file repos_info.csv."
},
{
"code": null,
"e": 4552,
"s": 4394,
"text": "I also had access to the commits url for each repository. I decided that I could collect the commits for each repository and save them to their own file too."
},
{
"code": null,
"e": 4758,
"s": 4552,
"text": "Just like the repositories API, the commits API is also limited to 30 commits in one call. So, using the same technique of using page parameter, I retrieved all commits. I took a look at the response json."
},
{
"code": null,
"e": 4907,
"s": 4758,
"text": "For each commit, I saved the repository Id the git commit belongs to, the sha value of the commit, the date of commit and the message of the commit."
},
{
"code": null,
"e": 4964,
"s": 4907,
"text": "I saved the dataframe data to the file commits_info.csv."
},
{
"code": null,
"e": 5054,
"s": 4964,
"text": "Now that the complete data is available, I decided to draw some insights out of the data."
},
{
"code": null,
"e": 5234,
"s": 5054,
"text": "I noticed that I had 36 repositories and 408 commits. I then decided to use the describe() method to take a look at the forks, watchers, issues and stars. I noticed the following:"
},
{
"code": null,
"e": 5383,
"s": 5234,
"text": "I’ve had maximum forks as 67 while the minimum are 0.The number of watchers and stars go hand in hand.I’ve had no issues reported in any repository."
},
{
"code": null,
"e": 5437,
"s": 5383,
"text": "I’ve had maximum forks as 67 while the minimum are 0."
},
{
"code": null,
"e": 5487,
"s": 5437,
"text": "The number of watchers and stars go hand in hand."
},
{
"code": null,
"e": 5534,
"s": 5487,
"text": "I’ve had no issues reported in any repository."
},
{
"code": null,
"e": 5769,
"s": 5534,
"text": "I also observed that the two most common commit messages I’ve used are Update README.md and Initial commit. It appears that sometimes I do tend to update readme files on GitHub itself and use its default message as the commit message."
},
{
"code": null,
"e": 5952,
"s": 5769,
"text": "Next, I wanted to see how the commits were distributed amongst my various repositories. I combined the two datasets (repos and commits) based on the repository id and created a plot."
},
{
"code": null,
"e": 6236,
"s": 5952,
"text": "From the figure above, we can clearly see that I’ve had the maximum commits in IEEE MyEvent App, which is an Android application for event management. The second most committed repository is the one associated with IBM’s Applied Data Science Capstone course called Coursera_Capstone."
},
{
"code": null,
"e": 6424,
"s": 6236,
"text": "It’s been a long time since I started working on projects and pushing them to GitHub. I’ve worked the most during the year 2018 and 2019 and expect to see the same in the yearly analysis."
},
{
"code": null,
"e": 6787,
"s": 6424,
"text": "I have made maximum commits in this year itself even though it’s just June. The second place goes to the year 2016. I was pursuing my Bachelors in Computer Science back then and I had started working on my own projects and thus this high number of commits. I expected more commits in the year 2018 but I started late so probably there were less commits in total."
},
{
"code": null,
"e": 6854,
"s": 6787,
"text": "Let’s now break down the year 2019 and see how I progressed there."
},
{
"code": null,
"e": 6927,
"s": 6854,
"text": "I broke down the year into months and visualized the data on a bar plot."
},
{
"code": null,
"e": 7107,
"s": 6927,
"text": "It appears that I made the maximum commits in the month of March. There are still 6 days left in June but it has already taken the second place. The least commits were in January."
},
{
"code": null,
"e": 7145,
"s": 7107,
"text": "Let’s break down March, 2019 further."
},
{
"code": null,
"e": 7202,
"s": 7145,
"text": "Let’s also see the commit history in the month of March."
},
{
"code": null,
"e": 7257,
"s": 7202,
"text": "I made the maximum number of commits on March 2, 2019."
},
{
"code": null,
"e": 7384,
"s": 7257,
"text": "As my interest grew in Data Science, I worked on many projects using Python. Thus, Python would be the most dominant language."
},
{
"code": null,
"e": 7628,
"s": 7384,
"text": "I’ve worked on a variety of languages including HTML, CSS, C++, Java, and others. However, the most common is Jupyter Notebook. My code in Jupyter notebooks is written in Python 3 and thus Python is the most common language in all my projects."
},
{
"code": null,
"e": 7753,
"s": 7628,
"text": "In this article, I discussed the steps I used to collect GitHub data for my profile and then used the data to draw insights."
}
] |
Count of points such that sum of Manhattan distances is minimized - GeeksforGeeks
|
12 Jan, 2022
Given N points in K dimensional space in a 2D array Points[][], where 1≤ N ≤ 105 and 1 ≤ K ≤ 5. The task is to determine the number of points (with integer coordinates) such that the sum of Manhattan distances from these points to the N points is minimized.
Manhattan distance is the sum of distances between two points measured along axes at right angles. In a plane with p1 at (x1, y1) and p2 at (x2, y2), it is |x1 – x2| + |y1 – y2|.
Examples:
Input: N = 3, K = 3, Points = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3} } Output: 1Explanation: From {2,2,2}, the sum of Manhattan distances to other 2 points is minimum
Input: N = 4, K = 4, Points = { {1, 6, 9, 6}, {5, 2, 5, 7}, {2, 0, 1, 5}, {4, 6, 3, 9} } Output: 90
Approach: The approach is based on sorting. To minimize the Manhattan distance, just sort the points in all K dimensions and proceed according to the number of points given. Follow the below steps to solve the problem:
Case -1 When N is odd: It can be solved on the basis of following observationThe number of such optimal points will always be 1 because after sorting them in all K dimensions, there will be just one median point where the sum of Manhattan distances will attain minimum value.
The number of such optimal points will always be 1 because after sorting them in all K dimensions, there will be just one median point where the sum of Manhattan distances will attain minimum value.
For example: Consider the expression |x-3| + |x-5| + |x-8|. This attains its minimum value only at a single point x = 5.
Case-2 When N is even: The following observation helps in solving the problem.Sort the points on the basis of one dimension.For each dimension, there will be 2 median indices namely (N/2)-1 and (N/2).All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value.So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1.Similarly, find the number of median coordinates in all dimensions after sorting the numbers on the basis of that dimension, and their product will form the total number of such optimal points in the K-dimensional space.
Sort the points on the basis of one dimension.
For each dimension, there will be 2 median indices namely (N/2)-1 and (N/2).All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value.So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1.
All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value.
So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1.
Similarly, find the number of median coordinates in all dimensions after sorting the numbers on the basis of that dimension, and their product will form the total number of such optimal points in the K-dimensional space.
For example: Consider the expression |x-3| + |x-5| + |x-8| + |x-10|. This attains its minimum value for all x in the range [5,8]. So there will be (8-5)+1 = 4 number of such x. Similarly, find for all the K dimensions.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the required number// of points which minimizes the sum// of Manhattan distancesint NumberOfPointsWithMinDistance( int n, int k, vector<vector<int> >& point){ // Sorting points in all k dimension for (int i = 0; i < k; ++i) sort(point[i].begin(), point[i].end()); // When n is odd if (n % 2 == 1) { return 1; } // When n is even int ans = 1; for (int i = 0; i < k; ++i) { int possible_points = point[i][n / 2] - point[i][(n / 2) - 1] + 1; ans = ans * possible_points; } return ans;} int main(){ int N = 4, K = 4; vector<vector<int> > Points = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; cout << NumberOfPointsWithMinDistance(N, K, Points); return 0;}
// Java implementation of above approachimport java.util.*;class GFG{ // Function to find the required number // of points which minimizes the sum // of Manhattan distances static int NumberOfPointsWithMinDistance( int n, int k, int[][] point) { // Sorting points in all k dimension for (int i = 0; i < k; ++i) Arrays.sort(point[i]); // When n is odd if (n % 2 == 1) { return 1; } // When n is even int ans = 1; for (int i = 0; i < k; ++i) { int possible_points = point[i][n / 2] - point[i][(n / 2) - 1] + 1; ans = ans * possible_points; } return ans; } public static void main(String[] args) { int N = 4, K = 4; int[][] Points = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; System.out.print(NumberOfPointsWithMinDistance(N, K, Points)); }} // This code is contributed by gauravrajput1
# Python code for the above approach # Function to find the required number# of points which minimizes the sum# of Manhattan distancesdef NumberOfPointsWithMinDistance(n, k, points): # Sorting points in all k dimension for i in range(k): points[i].sort() # When n is odd if (n % 2 == 1): return 1 # When n is even ans = 1 for i in range(k): possible_points = points[i][(n // 2)] - points[i][(n // 2) - 1] + 1 ans = ans * possible_points return ans # Drive codeN = 4K = 4Points = [[1, 5, 2, 4], [6, 2, 0, 6], [9, 5, 1, 3], [6, 7, 5, 9]]print(NumberOfPointsWithMinDistance(N, K, Points)) # This code is contributed by gfgking
// C# implementation of above approachusing System;using System.Linq;public class GFG{ // Function to find the required number // of points which minimizes the sum // of Manhattan distances static int NumberOfPointsWithMinDistance( int n, int k, int[,] point) { int []x = null; // Sorting points in all k dimension for (int i = 0; i < k; ++i) { x = GetRow(point, i); Array.Sort(x); for(int j = 0; j < x.GetLength(0); j++) point[i,j] = x[j]; } // When n is odd if (n % 2 == 1) { return 1; } // When n is even int ans = 1; for (int i = 0; i < k; ++i) { int possible_points = point[i,n / 2] - point[i,(n / 2) - 1] + 1; ans = ans * possible_points; } return ans; } public static int[] GetRow(int[,] matrix, int row) { var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector; } public static void Main(String[] args) { int N = 4, K = 4; int[,] Points = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; Console.Write(NumberOfPointsWithMinDistance(N, K, Points)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript code for the above approach // Function to find the required number // of points which minimizes the sum // of Manhattan distances function NumberOfPointsWithMinDistance( n, k, points) { // Sorting points in all k dimension for (let i = 0; i < k; ++i) points[i].sort(function (a, b) { return a - b }) // When n is odd if (n % 2 == 1) { return 1; } // When n is even let ans = 1; for (let i = 0; i < k; ++i) { let possible_points = points[i][Math.floor(n / 2)] - points[i][Math.floor(n / 2) - 1] + 1; ans = ans * possible_points; } return ans; } let N = 4, K = 4; let Points = [[1, 5, 2, 4], [6, 2, 0, 6], [9, 5, 1, 3], [6, 7, 5, 9]]; document.write(NumberOfPointsWithMinDistance(N, K, Points)); // This code is contributed by Potta Lokesh </script>
90
Time Complexity: O(K * N * log(N))Auxiliary Space: O(1)
lokeshpotta20
gfgking
GauravRajput1
29AjayKumar
Algo-Geek 2021
Coordinate Geometry
Algo Geek
Arrays
Geometric
Mathematical
Sorting
Arrays
Mathematical
Sorting
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of operation required to water all the plants
Check if the given string is valid English word or not
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Encode given String by inserting in Matrix column-wise and printing it row-wise
Minimum count of words among all the given sentences
Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Arrays in C/C++
Program for array rotation
|
[
{
"code": null,
"e": 26376,
"s": 26348,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 26636,
"s": 26376,
"text": "Given N points in K dimensional space in a 2D array Points[][], where 1≤ N ≤ 105 and 1 ≤ K ≤ 5. The task is to determine the number of points (with integer coordinates) such that the sum of Manhattan distances from these points to the N points is minimized. "
},
{
"code": null,
"e": 26815,
"s": 26636,
"text": "Manhattan distance is the sum of distances between two points measured along axes at right angles. In a plane with p1 at (x1, y1) and p2 at (x2, y2), it is |x1 – x2| + |y1 – y2|."
},
{
"code": null,
"e": 26827,
"s": 26815,
"text": "Examples: "
},
{
"code": null,
"e": 27022,
"s": 26827,
"text": "Input: N = 3, K = 3, Points = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3} } Output: 1Explanation: From {2,2,2}, the sum of Manhattan distances to other 2 points is minimum"
},
{
"code": null,
"e": 27171,
"s": 27022,
"text": "Input: N = 4, K = 4, Points = { {1, 6, 9, 6}, {5, 2, 5, 7}, {2, 0, 1, 5}, {4, 6, 3, 9} } Output: 90"
},
{
"code": null,
"e": 27390,
"s": 27171,
"text": "Approach: The approach is based on sorting. To minimize the Manhattan distance, just sort the points in all K dimensions and proceed according to the number of points given. Follow the below steps to solve the problem:"
},
{
"code": null,
"e": 27666,
"s": 27390,
"text": "Case -1 When N is odd: It can be solved on the basis of following observationThe number of such optimal points will always be 1 because after sorting them in all K dimensions, there will be just one median point where the sum of Manhattan distances will attain minimum value."
},
{
"code": null,
"e": 27865,
"s": 27666,
"text": "The number of such optimal points will always be 1 because after sorting them in all K dimensions, there will be just one median point where the sum of Manhattan distances will attain minimum value."
},
{
"code": null,
"e": 27986,
"s": 27865,
"text": "For example: Consider the expression |x-3| + |x-5| + |x-8|. This attains its minimum value only at a single point x = 5."
},
{
"code": null,
"e": 28652,
"s": 27986,
"text": "Case-2 When N is even: The following observation helps in solving the problem.Sort the points on the basis of one dimension.For each dimension, there will be 2 median indices namely (N/2)-1 and (N/2).All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value.So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1.Similarly, find the number of median coordinates in all dimensions after sorting the numbers on the basis of that dimension, and their product will form the total number of such optimal points in the K-dimensional space."
},
{
"code": null,
"e": 28699,
"s": 28652,
"text": "Sort the points on the basis of one dimension."
},
{
"code": null,
"e": 29021,
"s": 28699,
"text": "For each dimension, there will be 2 median indices namely (N/2)-1 and (N/2).All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value.So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1."
},
{
"code": null,
"e": 29168,
"s": 29021,
"text": "All the numbers in the range [ Points[(N/2) -1], Points[N/2] ] will act as medians where the sum of Manhattan distances will attain minimum value."
},
{
"code": null,
"e": 29268,
"s": 29168,
"text": "So total number of median coordinates for that dimension will be Points[(N/2)] – Points[(N/2)-1]+1."
},
{
"code": null,
"e": 29489,
"s": 29268,
"text": "Similarly, find the number of median coordinates in all dimensions after sorting the numbers on the basis of that dimension, and their product will form the total number of such optimal points in the K-dimensional space."
},
{
"code": null,
"e": 29708,
"s": 29489,
"text": "For example: Consider the expression |x-3| + |x-5| + |x-8| + |x-10|. This attains its minimum value for all x in the range [5,8]. So there will be (8-5)+1 = 4 number of such x. Similarly, find for all the K dimensions."
},
{
"code": null,
"e": 29759,
"s": 29708,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 29763,
"s": 29759,
"text": "C++"
},
{
"code": null,
"e": 29768,
"s": 29763,
"text": "Java"
},
{
"code": null,
"e": 29776,
"s": 29768,
"text": "Python3"
},
{
"code": null,
"e": 29779,
"s": 29776,
"text": "C#"
},
{
"code": null,
"e": 29790,
"s": 29779,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the required number// of points which minimizes the sum// of Manhattan distancesint NumberOfPointsWithMinDistance( int n, int k, vector<vector<int> >& point){ // Sorting points in all k dimension for (int i = 0; i < k; ++i) sort(point[i].begin(), point[i].end()); // When n is odd if (n % 2 == 1) { return 1; } // When n is even int ans = 1; for (int i = 0; i < k; ++i) { int possible_points = point[i][n / 2] - point[i][(n / 2) - 1] + 1; ans = ans * possible_points; } return ans;} int main(){ int N = 4, K = 4; vector<vector<int> > Points = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; cout << NumberOfPointsWithMinDistance(N, K, Points); return 0;}",
"e": 30729,
"s": 29790,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*;class GFG{ // Function to find the required number // of points which minimizes the sum // of Manhattan distances static int NumberOfPointsWithMinDistance( int n, int k, int[][] point) { // Sorting points in all k dimension for (int i = 0; i < k; ++i) Arrays.sort(point[i]); // When n is odd if (n % 2 == 1) { return 1; } // When n is even int ans = 1; for (int i = 0; i < k; ++i) { int possible_points = point[i][n / 2] - point[i][(n / 2) - 1] + 1; ans = ans * possible_points; } return ans; } public static void main(String[] args) { int N = 4, K = 4; int[][] Points = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; System.out.print(NumberOfPointsWithMinDistance(N, K, Points)); }} // This code is contributed by gauravrajput1",
"e": 31680,
"s": 30729,
"text": null
},
{
"code": "# Python code for the above approach # Function to find the required number# of points which minimizes the sum# of Manhattan distancesdef NumberOfPointsWithMinDistance(n, k, points): # Sorting points in all k dimension for i in range(k): points[i].sort() # When n is odd if (n % 2 == 1): return 1 # When n is even ans = 1 for i in range(k): possible_points = points[i][(n // 2)] - points[i][(n // 2) - 1] + 1 ans = ans * possible_points return ans # Drive codeN = 4K = 4Points = [[1, 5, 2, 4], [6, 2, 0, 6], [9, 5, 1, 3], [6, 7, 5, 9]]print(NumberOfPointsWithMinDistance(N, K, Points)) # This code is contributed by gfgking",
"e": 32363,
"s": 31680,
"text": null
},
{
"code": "// C# implementation of above approachusing System;using System.Linq;public class GFG{ // Function to find the required number // of points which minimizes the sum // of Manhattan distances static int NumberOfPointsWithMinDistance( int n, int k, int[,] point) { int []x = null; // Sorting points in all k dimension for (int i = 0; i < k; ++i) { x = GetRow(point, i); Array.Sort(x); for(int j = 0; j < x.GetLength(0); j++) point[i,j] = x[j]; } // When n is odd if (n % 2 == 1) { return 1; } // When n is even int ans = 1; for (int i = 0; i < k; ++i) { int possible_points = point[i,n / 2] - point[i,(n / 2) - 1] + 1; ans = ans * possible_points; } return ans; } public static int[] GetRow(int[,] matrix, int row) { var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector; } public static void Main(String[] args) { int N = 4, K = 4; int[,] Points = { { 1, 5, 2, 4 }, { 6, 2, 0, 6 }, { 9, 5, 1, 3 }, { 6, 7, 5, 9 } }; Console.Write(NumberOfPointsWithMinDistance(N, K, Points)); }} // This code is contributed by 29AjayKumar",
"e": 33676,
"s": 32363,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to find the required number // of points which minimizes the sum // of Manhattan distances function NumberOfPointsWithMinDistance( n, k, points) { // Sorting points in all k dimension for (let i = 0; i < k; ++i) points[i].sort(function (a, b) { return a - b }) // When n is odd if (n % 2 == 1) { return 1; } // When n is even let ans = 1; for (let i = 0; i < k; ++i) { let possible_points = points[i][Math.floor(n / 2)] - points[i][Math.floor(n / 2) - 1] + 1; ans = ans * possible_points; } return ans; } let N = 4, K = 4; let Points = [[1, 5, 2, 4], [6, 2, 0, 6], [9, 5, 1, 3], [6, 7, 5, 9]]; document.write(NumberOfPointsWithMinDistance(N, K, Points)); // This code is contributed by Potta Lokesh </script>",
"e": 34754,
"s": 33676,
"text": null
},
{
"code": null,
"e": 34760,
"s": 34757,
"text": "90"
},
{
"code": null,
"e": 34818,
"s": 34762,
"text": "Time Complexity: O(K * N * log(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34834,
"s": 34820,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 34842,
"s": 34834,
"text": "gfgking"
},
{
"code": null,
"e": 34856,
"s": 34842,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34868,
"s": 34856,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34883,
"s": 34868,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 34903,
"s": 34883,
"text": "Coordinate Geometry"
},
{
"code": null,
"e": 34913,
"s": 34903,
"text": "Algo Geek"
},
{
"code": null,
"e": 34920,
"s": 34913,
"text": "Arrays"
},
{
"code": null,
"e": 34930,
"s": 34920,
"text": "Geometric"
},
{
"code": null,
"e": 34943,
"s": 34930,
"text": "Mathematical"
},
{
"code": null,
"e": 34951,
"s": 34943,
"text": "Sorting"
},
{
"code": null,
"e": 34958,
"s": 34951,
"text": "Arrays"
},
{
"code": null,
"e": 34971,
"s": 34958,
"text": "Mathematical"
},
{
"code": null,
"e": 34979,
"s": 34971,
"text": "Sorting"
},
{
"code": null,
"e": 34989,
"s": 34979,
"text": "Geometric"
},
{
"code": null,
"e": 35087,
"s": 34989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35139,
"s": 35087,
"text": "Count of operation required to water all the plants"
},
{
"code": null,
"e": 35194,
"s": 35139,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 35285,
"s": 35194,
"text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form"
},
{
"code": null,
"e": 35365,
"s": 35285,
"text": "Encode given String by inserting in Matrix column-wise and printing it row-wise"
},
{
"code": null,
"e": 35418,
"s": 35365,
"text": "Minimum count of words among all the given sentences"
},
{
"code": null,
"e": 35433,
"s": 35418,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35501,
"s": 35433,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35547,
"s": 35501,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35563,
"s": 35547,
"text": "Arrays in C/C++"
}
] |
Open-CV Based Sudoku Solver Powered By Rust | by PRAKHAR KAUSHIK | Towards Data Science
|
Okay so one day browsing through Reddit, I came across a project, It was a sudoku solver using video cam stream. The project was cool, but there was the only thing I didn’t like: it used to crop the sudoku image and give a solved sudoku image solution.
So I thought why not project back the solution to the original image to make it look like it's solved in the original image?
Pretty cool right?!
The project is simple, take the sudoku image, solve it and project back the solution to the original image, thats all!!
Well, that was my initial plan, but the execution is another thing.
Brief project technology description :
Get the sudoku block in the image — Python OPEN CV
Crop the sudoku image and change perspective — Python OPEN CV
Extract the digits in some ordered manner — Python KNN Model
Solve the sudoku — Using Rust Sudoku Solver
Project back the solution into the original image — Python OPEN CV
Well we can solve the sudoku using Python but for some reason, I wanted to try adding Rust to python, also its faster than python in solving the sudoku.
If you find it interesting, let's start!!
After this section, we will be converting the full image to cropped sudoku image.
Okay so basic logic is
Get the biggest box in the image as it will be most probably the sudoku box.Next is to draw lines along the sudoku box edges.Find the intersection points of these lines.Use the intersection points to change the perspective of the image and get the cropped sudoku.
Get the biggest box in the image as it will be most probably the sudoku box.
Next is to draw lines along the sudoku box edges.
Find the intersection points of these lines.
Use the intersection points to change the perspective of the image and get the cropped sudoku.
Okay, so let's see each step one by one!
Let's understand the code!
First of all, contour is basically any closed shape
we will be using opencv library, the steps are:
Converting image to GRAY
Using adaptiveThreshold to convert each pixel of the image to either black or pure white.
Opencv has a function findContours it returns the contours(closed shape)
Going through Each contour and getting the max area contour.
After this, we will be having the biggest contour which most probably is the sudoku box.
As this just gives the outline of the shape, we can’t use it to get the sudoku box, we need the four corner points to change perspective.
Hence we will be first drawing this contour on a blank image and then draw straight lines on this shape, it will give us four lines which will be later used to get the four corner points.
After this, we will have lines along the sudoku sides but the thing is, there are multiple lines along a single side because the Houghlines uses roughly inline points to draw a line and as our image is not very clear nor is the correct perspective hence what we get is multiple lines along a single side.
So what we will be doing is we will eliminate all lines which are close to each other, but leave one hence we will be left with 4 lines for 4 sides.
So now we have 4 lines, what’s left is to get the intersection points of these lines.
Well as our lines are not parallel hence we will be getting 6 points of intersection. To solve this we will be using the slope of lines, we will divide the lines into 2 categories, horizontal and vertical. And this way we will get only 4 points.
Note: The lines are not horizontal and vertical, but are just 2 categories.
for (rho,theta) in createhor: for (rho1,theta1) in createver: if (rho,theta)!=(rho1,theta1): a=[[np.cos(theta),np.sin(theta)],[np.cos(theta1),np.sin(theta1)]] b=[rho,rho1] cor=np.linalg.solve(a,b) if list(cor) not in points: points.append(list(cor))
Now we have 4 corner points, it’s time to do the magic and get the sudoku image.
Nothing fancy, we will be using the warpPerspective to change the perspective and get the image.
Final output:
This section will be focused on extracting the digits from sudoku image.
So first is some eroding and dilating to remove the noise.
Next is to get the contour of digits, and drawing the on a new blank image. After that, it's just drawing the divider lines.
After this, we will get
A clean sudoku image with no noise.
Next is simple, just iterating through each box and predicting the numbers. The first approach which failed very very miserably was to use a CNN model and training it to predict the numbers. But for some reason, it was only predicting 6 no matter what the input was.
After some experimenting, I went ahead with the KNN Model.
The first problem was to create the dataset, Tried kaggle but apparently there are no datasets for simple plain numbers. So I created a script which first writes the digits on an image, adds some Noise and blur to make it realistic and then crop it.
Then I used another good library Augmentor. It uses the present images and adds random tilts, rotations etc. Hence what I got was 10k images for each number. Pretty cool!! At least for me, I was not able to sleep after doing that masterpiece stuff. Okay after we are done of thinking about it, let's move to train the model.
Next was easy, just use this model to predict the numbers and creating a new image of a sudoku.
After everything, what we have is:
We will be solving sudoku using Rust in this section.
After our last section, we have numbers in sudoku image, what's left is to code a sudoku solver, in rust and thankfully we can export it into a library which can be imported in python.
There is a library sudoku which provides a good sudoku solver, so I used it to create a function and wrote Python bindings to import in python, another masterpiece moment lol.
After this solving the sudoku and creating a solution mask was left.
And the final solution looked like.
Great!! Let's move to the next part.
The final section, it will be focusing on projecting the solution to the original image.
Once we have solution mapped on a black image, just doing a bitwise not and was enough to remove the black part of the image, and as we had the initial points, changing back the perspective, is also easy
M = cv2.getPerspectiveTransform(pts2,pts1) img = cv2.warpPerspective(sudoku_image,M,(original.shape[1],original.shape[0])) img = cv2.bitwise_not(img) img = cv2.bitwise_and(img,original)
That's all!! The final image is
You can find whole source code at!!
github.com
Thanks for reading!!
|
[
{
"code": null,
"e": 425,
"s": 172,
"text": "Okay so one day browsing through Reddit, I came across a project, It was a sudoku solver using video cam stream. The project was cool, but there was the only thing I didn’t like: it used to crop the sudoku image and give a solved sudoku image solution."
},
{
"code": null,
"e": 550,
"s": 425,
"text": "So I thought why not project back the solution to the original image to make it look like it's solved in the original image?"
},
{
"code": null,
"e": 570,
"s": 550,
"text": "Pretty cool right?!"
},
{
"code": null,
"e": 690,
"s": 570,
"text": "The project is simple, take the sudoku image, solve it and project back the solution to the original image, thats all!!"
},
{
"code": null,
"e": 758,
"s": 690,
"text": "Well, that was my initial plan, but the execution is another thing."
},
{
"code": null,
"e": 797,
"s": 758,
"text": "Brief project technology description :"
},
{
"code": null,
"e": 848,
"s": 797,
"text": "Get the sudoku block in the image — Python OPEN CV"
},
{
"code": null,
"e": 910,
"s": 848,
"text": "Crop the sudoku image and change perspective — Python OPEN CV"
},
{
"code": null,
"e": 971,
"s": 910,
"text": "Extract the digits in some ordered manner — Python KNN Model"
},
{
"code": null,
"e": 1015,
"s": 971,
"text": "Solve the sudoku — Using Rust Sudoku Solver"
},
{
"code": null,
"e": 1082,
"s": 1015,
"text": "Project back the solution into the original image — Python OPEN CV"
},
{
"code": null,
"e": 1235,
"s": 1082,
"text": "Well we can solve the sudoku using Python but for some reason, I wanted to try adding Rust to python, also its faster than python in solving the sudoku."
},
{
"code": null,
"e": 1277,
"s": 1235,
"text": "If you find it interesting, let's start!!"
},
{
"code": null,
"e": 1359,
"s": 1277,
"text": "After this section, we will be converting the full image to cropped sudoku image."
},
{
"code": null,
"e": 1382,
"s": 1359,
"text": "Okay so basic logic is"
},
{
"code": null,
"e": 1646,
"s": 1382,
"text": "Get the biggest box in the image as it will be most probably the sudoku box.Next is to draw lines along the sudoku box edges.Find the intersection points of these lines.Use the intersection points to change the perspective of the image and get the cropped sudoku."
},
{
"code": null,
"e": 1723,
"s": 1646,
"text": "Get the biggest box in the image as it will be most probably the sudoku box."
},
{
"code": null,
"e": 1773,
"s": 1723,
"text": "Next is to draw lines along the sudoku box edges."
},
{
"code": null,
"e": 1818,
"s": 1773,
"text": "Find the intersection points of these lines."
},
{
"code": null,
"e": 1913,
"s": 1818,
"text": "Use the intersection points to change the perspective of the image and get the cropped sudoku."
},
{
"code": null,
"e": 1954,
"s": 1913,
"text": "Okay, so let's see each step one by one!"
},
{
"code": null,
"e": 1981,
"s": 1954,
"text": "Let's understand the code!"
},
{
"code": null,
"e": 2033,
"s": 1981,
"text": "First of all, contour is basically any closed shape"
},
{
"code": null,
"e": 2081,
"s": 2033,
"text": "we will be using opencv library, the steps are:"
},
{
"code": null,
"e": 2106,
"s": 2081,
"text": "Converting image to GRAY"
},
{
"code": null,
"e": 2196,
"s": 2106,
"text": "Using adaptiveThreshold to convert each pixel of the image to either black or pure white."
},
{
"code": null,
"e": 2269,
"s": 2196,
"text": "Opencv has a function findContours it returns the contours(closed shape)"
},
{
"code": null,
"e": 2330,
"s": 2269,
"text": "Going through Each contour and getting the max area contour."
},
{
"code": null,
"e": 2419,
"s": 2330,
"text": "After this, we will be having the biggest contour which most probably is the sudoku box."
},
{
"code": null,
"e": 2557,
"s": 2419,
"text": "As this just gives the outline of the shape, we can’t use it to get the sudoku box, we need the four corner points to change perspective."
},
{
"code": null,
"e": 2745,
"s": 2557,
"text": "Hence we will be first drawing this contour on a blank image and then draw straight lines on this shape, it will give us four lines which will be later used to get the four corner points."
},
{
"code": null,
"e": 3050,
"s": 2745,
"text": "After this, we will have lines along the sudoku sides but the thing is, there are multiple lines along a single side because the Houghlines uses roughly inline points to draw a line and as our image is not very clear nor is the correct perspective hence what we get is multiple lines along a single side."
},
{
"code": null,
"e": 3199,
"s": 3050,
"text": "So what we will be doing is we will eliminate all lines which are close to each other, but leave one hence we will be left with 4 lines for 4 sides."
},
{
"code": null,
"e": 3285,
"s": 3199,
"text": "So now we have 4 lines, what’s left is to get the intersection points of these lines."
},
{
"code": null,
"e": 3531,
"s": 3285,
"text": "Well as our lines are not parallel hence we will be getting 6 points of intersection. To solve this we will be using the slope of lines, we will divide the lines into 2 categories, horizontal and vertical. And this way we will get only 4 points."
},
{
"code": null,
"e": 3607,
"s": 3531,
"text": "Note: The lines are not horizontal and vertical, but are just 2 categories."
},
{
"code": null,
"e": 3954,
"s": 3607,
"text": "for (rho,theta) in createhor: for (rho1,theta1) in createver: if (rho,theta)!=(rho1,theta1): a=[[np.cos(theta),np.sin(theta)],[np.cos(theta1),np.sin(theta1)]] b=[rho,rho1] cor=np.linalg.solve(a,b) if list(cor) not in points: points.append(list(cor))"
},
{
"code": null,
"e": 4035,
"s": 3954,
"text": "Now we have 4 corner points, it’s time to do the magic and get the sudoku image."
},
{
"code": null,
"e": 4132,
"s": 4035,
"text": "Nothing fancy, we will be using the warpPerspective to change the perspective and get the image."
},
{
"code": null,
"e": 4146,
"s": 4132,
"text": "Final output:"
},
{
"code": null,
"e": 4219,
"s": 4146,
"text": "This section will be focused on extracting the digits from sudoku image."
},
{
"code": null,
"e": 4278,
"s": 4219,
"text": "So first is some eroding and dilating to remove the noise."
},
{
"code": null,
"e": 4403,
"s": 4278,
"text": "Next is to get the contour of digits, and drawing the on a new blank image. After that, it's just drawing the divider lines."
},
{
"code": null,
"e": 4427,
"s": 4403,
"text": "After this, we will get"
},
{
"code": null,
"e": 4463,
"s": 4427,
"text": "A clean sudoku image with no noise."
},
{
"code": null,
"e": 4730,
"s": 4463,
"text": "Next is simple, just iterating through each box and predicting the numbers. The first approach which failed very very miserably was to use a CNN model and training it to predict the numbers. But for some reason, it was only predicting 6 no matter what the input was."
},
{
"code": null,
"e": 4789,
"s": 4730,
"text": "After some experimenting, I went ahead with the KNN Model."
},
{
"code": null,
"e": 5039,
"s": 4789,
"text": "The first problem was to create the dataset, Tried kaggle but apparently there are no datasets for simple plain numbers. So I created a script which first writes the digits on an image, adds some Noise and blur to make it realistic and then crop it."
},
{
"code": null,
"e": 5364,
"s": 5039,
"text": "Then I used another good library Augmentor. It uses the present images and adds random tilts, rotations etc. Hence what I got was 10k images for each number. Pretty cool!! At least for me, I was not able to sleep after doing that masterpiece stuff. Okay after we are done of thinking about it, let's move to train the model."
},
{
"code": null,
"e": 5460,
"s": 5364,
"text": "Next was easy, just use this model to predict the numbers and creating a new image of a sudoku."
},
{
"code": null,
"e": 5495,
"s": 5460,
"text": "After everything, what we have is:"
},
{
"code": null,
"e": 5549,
"s": 5495,
"text": "We will be solving sudoku using Rust in this section."
},
{
"code": null,
"e": 5734,
"s": 5549,
"text": "After our last section, we have numbers in sudoku image, what's left is to code a sudoku solver, in rust and thankfully we can export it into a library which can be imported in python."
},
{
"code": null,
"e": 5910,
"s": 5734,
"text": "There is a library sudoku which provides a good sudoku solver, so I used it to create a function and wrote Python bindings to import in python, another masterpiece moment lol."
},
{
"code": null,
"e": 5979,
"s": 5910,
"text": "After this solving the sudoku and creating a solution mask was left."
},
{
"code": null,
"e": 6015,
"s": 5979,
"text": "And the final solution looked like."
},
{
"code": null,
"e": 6052,
"s": 6015,
"text": "Great!! Let's move to the next part."
},
{
"code": null,
"e": 6141,
"s": 6052,
"text": "The final section, it will be focusing on projecting the solution to the original image."
},
{
"code": null,
"e": 6345,
"s": 6141,
"text": "Once we have solution mapped on a black image, just doing a bitwise not and was enough to remove the black part of the image, and as we had the initial points, changing back the perspective, is also easy"
},
{
"code": null,
"e": 6544,
"s": 6345,
"text": "M = cv2.getPerspectiveTransform(pts2,pts1) img = cv2.warpPerspective(sudoku_image,M,(original.shape[1],original.shape[0])) img = cv2.bitwise_not(img) img = cv2.bitwise_and(img,original)"
},
{
"code": null,
"e": 6576,
"s": 6544,
"text": "That's all!! The final image is"
},
{
"code": null,
"e": 6612,
"s": 6576,
"text": "You can find whole source code at!!"
},
{
"code": null,
"e": 6623,
"s": 6612,
"text": "github.com"
}
] |
Angular 4 - Directives
|
Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −
These form the main class having details of how the component should be processed, instantiated and used at runtime.
A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor.
Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below.
In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard.
Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is −
ng g directive nameofthedirective
e.g
ng g directive changeText
This is how it appears in the command line
C:\projectA4\Angular 4-app>ng g directive changeText
installing directive
create src\app\change-text.directive.spec.ts
create src\app\change-text.directive.ts
update src\app\app.module.ts
The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
@NgModule({
declarations: [
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below.
import { Directive } from '@angular/core';
@Directive({
selector: '[changeText]'
})
export class ChangeTextDirective {
constructor() { }
}
The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive.
In the app.component.html view, let us add the directive as follows −
<div style="text-align:center">
<span changeText >Welcome to {{title}}.</span>
</div>
We will write the changes in change-text.directive.ts file as follows −
import { Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[changeText]'
})
export class ChangeTextDirective {
constructor(Element: ElementRef) {
console.log(Element);
Element.nativeElement.innerText="Text is changed by changeText Directive. ";
}
}
In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied.
We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above.
Now, the browser will show the following.
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": 2129,
"s": 1992,
"text": "Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −"
},
{
"code": null,
"e": 2246,
"s": 2129,
"text": "These form the main class having details of how the component should be processed, instantiated and used at runtime."
},
{
"code": null,
"e": 2409,
"s": 2246,
"text": "A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor."
},
{
"code": null,
"e": 2542,
"s": 2409,
"text": "Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below."
},
{
"code": null,
"e": 2683,
"s": 2542,
"text": "In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard."
},
{
"code": null,
"e": 2847,
"s": 2683,
"text": "Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is −"
},
{
"code": null,
"e": 2914,
"s": 2847,
"text": "ng g directive nameofthedirective\n\ne.g\n\nng g directive changeText\n"
},
{
"code": null,
"e": 2957,
"s": 2914,
"text": "This is how it appears in the command line"
},
{
"code": null,
"e": 3155,
"s": 2957,
"text": "C:\\projectA4\\Angular 4-app>ng g directive changeText\ninstalling directive\n create src\\app\\change-text.directive.spec.ts\n create src\\app\\change-text.directive.ts\n update src\\app\\app.module.ts\n"
},
{
"code": null,
"e": 3288,
"s": 3155,
"text": "The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated."
},
{
"code": null,
"e": 3791,
"s": 3288,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\n\n@NgModule({\n declarations: [\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n\n imports: [\n BrowserModule\n ],\n\n providers: [],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule { }"
},
{
"code": null,
"e": 3926,
"s": 3791,
"text": "The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below."
},
{
"code": null,
"e": 4073,
"s": 3926,
"text": "import { Directive } from '@angular/core';\n@Directive({\n selector: '[changeText]'\n})\n\nexport class ChangeTextDirective {\n constructor() { }\n}\n"
},
{
"code": null,
"e": 4250,
"s": 4073,
"text": "The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive."
},
{
"code": null,
"e": 4320,
"s": 4250,
"text": "In the app.component.html view, let us add the directive as follows −"
},
{
"code": null,
"e": 4410,
"s": 4320,
"text": "<div style=\"text-align:center\">\n <span changeText >Welcome to {{title}}.</span>\n</div>\n"
},
{
"code": null,
"e": 4482,
"s": 4410,
"text": "We will write the changes in change-text.directive.ts file as follows −"
},
{
"code": null,
"e": 4773,
"s": 4482,
"text": "import { Directive, ElementRef} from '@angular/core';\n@Directive({\n selector: '[changeText]'\n})\n\nexport class ChangeTextDirective {\n constructor(Element: ElementRef) {\n console.log(Element);\n Element.nativeElement.innerText=\"Text is changed by changeText Directive. \";\n }\n}\n"
},
{
"code": null,
"e": 4998,
"s": 4773,
"text": "In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied."
},
{
"code": null,
"e": 5152,
"s": 4998,
"text": "We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above."
},
{
"code": null,
"e": 5194,
"s": 5152,
"text": "Now, the browser will show the following."
},
{
"code": null,
"e": 5229,
"s": 5194,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5243,
"s": 5229,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5278,
"s": 5243,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5292,
"s": 5278,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5327,
"s": 5292,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5347,
"s": 5327,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5382,
"s": 5347,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5399,
"s": 5382,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5432,
"s": 5399,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5444,
"s": 5432,
"text": " Senol Atac"
},
{
"code": null,
"e": 5479,
"s": 5444,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5491,
"s": 5479,
"text": " Senol Atac"
},
{
"code": null,
"e": 5498,
"s": 5491,
"text": " Print"
},
{
"code": null,
"e": 5509,
"s": 5498,
"text": " Add Notes"
}
] |
Introduction to Image Processing with Python — Image Filtering | by Tonichi Edeza | Towards Data Science
|
In this article, we will tackle basic image filtering. We will see how to apply kernels to an image to change its overall look. Though this can be utilized for purely aesthetic purposes, we will also go through the practical applications of image filtering.
Let’s get started!
As always we begin by importing the required Python Libraries
import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imread, imshowfrom skimage.color import rgb2grayfrom skimage import img_as_uintfrom scipy.signal import convolve2d
Great, now the next step is to define our filters (going forward referred to as Kernels as is the nomenclature). To start off let us first define a simple edge detection kernel.
kernel_edgedetection = np.array([[-1, -1, -1], [-1, 8.5, -1], [-1, -1, -1]])
As you may recall in my previous article, images are represented as matrices. In this case, our kernel is defined as a 3x3 matrix.
imshow(kernel_edgedetection, cmap = 'gray');
Now let us apply this to our image. Below is the image we shall be using as an example.
morph = imread('Morph_Image_1.png')
To apply the edge detection kernel to our image we simply have to use the convolve2d function in SciPy. But before that, we must first convert our image into greyscale (remember that we are applying a 2 Dimensional kernel).
plt.figure(num=None, figsize=(8, 6), dpi=80)morph_gray = rgb2gray(morph)imshow(morph_gray);
To apply the kernel, we can simply use the convolve2d function in SciPy.
conv_im1 = convolve2d(morph_gray, kernel_edgedetection)imshow(abs(conv_im1) , cmap='gray');
As we can see, the application of the kernel highlights all the edges detected by the machine. Note that there is no hard rule on the exact figures to use for edge detection. The main idea is that you have to define a kernel that will search for contrasts in the image. To explore this idea, let us create a function that uses different figures for edge detection.
def edge_detector(image): f_size = 15 morph_gray = rgb2gray(image) kernels = [np.array([[-1, -1, -1], [-1, i, -1], [-1, -1, -1]]) for i in range(2,10,1)] titles = [f'Edge Detection Center {kernels[k][1][1]}' for k in range(len(kernels))] fig, ax = plt.subplots(2, 4, figsize=(17,12)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'{titles[n]}', fontsize = f_size) ax.imshow(abs(convolve2d(morph_gray, kernels[n])) , cmap='gray') ax.set_axis_off() fig.tight_layout()
Apologies for the rather dense code as it may be difficult to understand for beginners, but I found it pertinent to create due to the number of subplots. In further lessons, I will give tips on how to create flat codes as well.
Going back to the image, we can see that the sweet spot for the edge value seems to be between 7 and 9. One could theoretically go deeper into the most visually appealing value but let us just say that 8 is the best value to use.
Note that so far we have only used the edge detection kernel, let us also take a look at two other popular kernels known as the Vertical Sobel and Horizontal Sobel.
# Horizontal Sobel Filterh_sobel = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])# Vertical Sobel Filterv_sobel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])fig, ax = plt.subplots(1, 2, figsize=(17,12))ax[0].set_title(f'Horizontal Sobel', fontsize = 15)ax[0].imshow(h_sobel, cmap='gray')ax[0].set_axis_off()ax[1].set_title(f'Vertical Sobel', fontsize = 15)ax[1].imshow(v_sobel , cmap='gray')ax[1].set_axis_off()
The kernels look specifically for horizontal and vertical edges specifically.
fig, ax = plt.subplots(1, 2, figsize=(17,12))ax[0].set_title(f'Horizontal Sobel', fontsize = 15)ax[0].imshow(abs(convolve2d(morph_gray, h_sobel)), cmap='gray')ax[0].set_axis_off()ax[1].set_title(f'Vertical Sobel', fontsize = 15)ax[1].imshow(abs(convolve2d(morph_gray, v_sobel)) , cmap='gray')ax[1].set_axis_off()
As we can see, there are many fascinating filters we can work with. I just chose edge detection as it the most understandable for beginners and other people who are just getting into image processing. To close this article out, let us apply these filters to a much more complex image.
Applying an edge filter to the image does not yield very good results.
kernel_edgedetection = np.array([[-1, -1, -1], [-1, 8.5, -1], [-1, -1, -1]])edge_dog = abs(convolve2d(graydog, kernel_edgedetection, mode = 'valid'))imshow(edge_dog, cmap='gray');
Though we can see that the dog is detectable, we also see that the machine picks up “edges” in the sand. Indeed it is rendering them as a grid pattern. To remedy this we can first blur the image.
blur = (1 / 16.0) * np.array([[1., 2., 1.], [2., 4., 2.], [1., 2., 1.]])blurred_dog = abs(convolve2d(graydog, blur, mode = 'valid' ))imshow(blurred_dog , cmap='gray');
From here we can convolve the image with the edge detector. Yielding the below result.
kernel_edgedetection = np.array([[-1, -1, -1], [-1, 8.05, -1], [-1, -1, -1]])blurry_edge_dog = abs(convolve2d(blurred_dog, kernel_edgedetection, mode = 'valid'))imshow( blurry_edge_dog , cmap='gray');
We see that the sand no longer exhibits edges as before, a good improvement that will help the machine not fall prey to false (or irrelevant) patterns.
Lastly, we would like to see the shape of the dog. Notice how the dog is actually much darker than the surrounding sand, we can use this to our advantage. We simply need to transform the matrix into integers and then filter out all the pixels that are less than the mean.
binary_dog = img_as_uint(blurry_edge_dog < np.mean(blurry_edge_dog))imshow(binary_dog , cmap='gray');
Though still grainy, the shape of the dog becomes easy to spot. The grains of sand also retain their noise like quality.
In Conclusion
Though we used kernels to do some pretty mundane things (detecting vertical and horizontal edges, finding the shapes of dogs), knowing how to use them correctly can be vital in your journey as a data scientist. As we have learned, some images may be easier to filter than others (particularly images with very well defined patterns).
Remember that despite their parallels, our human minds interpret images very differently from our machines. Patterns that we usually ignore (such as lines in the sand) may be treated as important by the machine. In our case we had to first blur the image before enacting the proper filters, this is not too different from the way our own brains “junk” visual information. Just be aware that programming filters in the machine will help it see the world the way we want it to see.
Equally as important though, be aware that we as humans also see the world based on our own filters. And that we too were programmed to see the world the way someone else wanted to us to see it.
|
[
{
"code": null,
"e": 305,
"s": 47,
"text": "In this article, we will tackle basic image filtering. We will see how to apply kernels to an image to change its overall look. Though this can be utilized for purely aesthetic purposes, we will also go through the practical applications of image filtering."
},
{
"code": null,
"e": 324,
"s": 305,
"text": "Let’s get started!"
},
{
"code": null,
"e": 386,
"s": 324,
"text": "As always we begin by importing the required Python Libraries"
},
{
"code": null,
"e": 573,
"s": 386,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imread, imshowfrom skimage.color import rgb2grayfrom skimage import img_as_uintfrom scipy.signal import convolve2d"
},
{
"code": null,
"e": 751,
"s": 573,
"text": "Great, now the next step is to define our filters (going forward referred to as Kernels as is the nomenclature). To start off let us first define a simple edge detection kernel."
},
{
"code": null,
"e": 892,
"s": 751,
"text": "kernel_edgedetection = np.array([[-1, -1, -1], [-1, 8.5, -1], [-1, -1, -1]])"
},
{
"code": null,
"e": 1023,
"s": 892,
"text": "As you may recall in my previous article, images are represented as matrices. In this case, our kernel is defined as a 3x3 matrix."
},
{
"code": null,
"e": 1068,
"s": 1023,
"text": "imshow(kernel_edgedetection, cmap = 'gray');"
},
{
"code": null,
"e": 1156,
"s": 1068,
"text": "Now let us apply this to our image. Below is the image we shall be using as an example."
},
{
"code": null,
"e": 1192,
"s": 1156,
"text": "morph = imread('Morph_Image_1.png')"
},
{
"code": null,
"e": 1416,
"s": 1192,
"text": "To apply the edge detection kernel to our image we simply have to use the convolve2d function in SciPy. But before that, we must first convert our image into greyscale (remember that we are applying a 2 Dimensional kernel)."
},
{
"code": null,
"e": 1508,
"s": 1416,
"text": "plt.figure(num=None, figsize=(8, 6), dpi=80)morph_gray = rgb2gray(morph)imshow(morph_gray);"
},
{
"code": null,
"e": 1581,
"s": 1508,
"text": "To apply the kernel, we can simply use the convolve2d function in SciPy."
},
{
"code": null,
"e": 1673,
"s": 1581,
"text": "conv_im1 = convolve2d(morph_gray, kernel_edgedetection)imshow(abs(conv_im1) , cmap='gray');"
},
{
"code": null,
"e": 2038,
"s": 1673,
"text": "As we can see, the application of the kernel highlights all the edges detected by the machine. Note that there is no hard rule on the exact figures to use for edge detection. The main idea is that you have to define a kernel that will search for contrasts in the image. To explore this idea, let us create a function that uses different figures for edge detection."
},
{
"code": null,
"e": 2654,
"s": 2038,
"text": "def edge_detector(image): f_size = 15 morph_gray = rgb2gray(image) kernels = [np.array([[-1, -1, -1], [-1, i, -1], [-1, -1, -1]]) for i in range(2,10,1)] titles = [f'Edge Detection Center {kernels[k][1][1]}' for k in range(len(kernels))] fig, ax = plt.subplots(2, 4, figsize=(17,12)) for n, ax in enumerate(ax.flatten()): ax.set_title(f'{titles[n]}', fontsize = f_size) ax.imshow(abs(convolve2d(morph_gray, kernels[n])) , cmap='gray') ax.set_axis_off() fig.tight_layout()"
},
{
"code": null,
"e": 2882,
"s": 2654,
"text": "Apologies for the rather dense code as it may be difficult to understand for beginners, but I found it pertinent to create due to the number of subplots. In further lessons, I will give tips on how to create flat codes as well."
},
{
"code": null,
"e": 3112,
"s": 2882,
"text": "Going back to the image, we can see that the sweet spot for the edge value seems to be between 7 and 9. One could theoretically go deeper into the most visually appealing value but let us just say that 8 is the best value to use."
},
{
"code": null,
"e": 3277,
"s": 3112,
"text": "Note that so far we have only used the edge detection kernel, let us also take a look at two other popular kernels known as the Vertical Sobel and Horizontal Sobel."
},
{
"code": null,
"e": 3768,
"s": 3277,
"text": "# Horizontal Sobel Filterh_sobel = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])# Vertical Sobel Filterv_sobel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])fig, ax = plt.subplots(1, 2, figsize=(17,12))ax[0].set_title(f'Horizontal Sobel', fontsize = 15)ax[0].imshow(h_sobel, cmap='gray')ax[0].set_axis_off()ax[1].set_title(f'Vertical Sobel', fontsize = 15)ax[1].imshow(v_sobel , cmap='gray')ax[1].set_axis_off()"
},
{
"code": null,
"e": 3846,
"s": 3768,
"text": "The kernels look specifically for horizontal and vertical edges specifically."
},
{
"code": null,
"e": 4159,
"s": 3846,
"text": "fig, ax = plt.subplots(1, 2, figsize=(17,12))ax[0].set_title(f'Horizontal Sobel', fontsize = 15)ax[0].imshow(abs(convolve2d(morph_gray, h_sobel)), cmap='gray')ax[0].set_axis_off()ax[1].set_title(f'Vertical Sobel', fontsize = 15)ax[1].imshow(abs(convolve2d(morph_gray, v_sobel)) , cmap='gray')ax[1].set_axis_off()"
},
{
"code": null,
"e": 4444,
"s": 4159,
"text": "As we can see, there are many fascinating filters we can work with. I just chose edge detection as it the most understandable for beginners and other people who are just getting into image processing. To close this article out, let us apply these filters to a much more complex image."
},
{
"code": null,
"e": 4515,
"s": 4444,
"text": "Applying an edge filter to the image does not yield very good results."
},
{
"code": null,
"e": 4774,
"s": 4515,
"text": "kernel_edgedetection = np.array([[-1, -1, -1], [-1, 8.5, -1], [-1, -1, -1]])edge_dog = abs(convolve2d(graydog, kernel_edgedetection, mode = 'valid'))imshow(edge_dog, cmap='gray');"
},
{
"code": null,
"e": 4970,
"s": 4774,
"text": "Though we can see that the dog is detectable, we also see that the machine picks up “edges” in the sand. Indeed it is rendering them as a grid pattern. To remedy this we can first blur the image."
},
{
"code": null,
"e": 5202,
"s": 4970,
"text": "blur = (1 / 16.0) * np.array([[1., 2., 1.], [2., 4., 2.], [1., 2., 1.]])blurred_dog = abs(convolve2d(graydog, blur, mode = 'valid' ))imshow(blurred_dog , cmap='gray');"
},
{
"code": null,
"e": 5289,
"s": 5202,
"text": "From here we can convolve the image with the edge detector. Yielding the below result."
},
{
"code": null,
"e": 5576,
"s": 5289,
"text": "kernel_edgedetection = np.array([[-1, -1, -1], [-1, 8.05, -1], [-1, -1, -1]])blurry_edge_dog = abs(convolve2d(blurred_dog, kernel_edgedetection, mode = 'valid'))imshow( blurry_edge_dog , cmap='gray');"
},
{
"code": null,
"e": 5728,
"s": 5576,
"text": "We see that the sand no longer exhibits edges as before, a good improvement that will help the machine not fall prey to false (or irrelevant) patterns."
},
{
"code": null,
"e": 6000,
"s": 5728,
"text": "Lastly, we would like to see the shape of the dog. Notice how the dog is actually much darker than the surrounding sand, we can use this to our advantage. We simply need to transform the matrix into integers and then filter out all the pixels that are less than the mean."
},
{
"code": null,
"e": 6102,
"s": 6000,
"text": "binary_dog = img_as_uint(blurry_edge_dog < np.mean(blurry_edge_dog))imshow(binary_dog , cmap='gray');"
},
{
"code": null,
"e": 6223,
"s": 6102,
"text": "Though still grainy, the shape of the dog becomes easy to spot. The grains of sand also retain their noise like quality."
},
{
"code": null,
"e": 6237,
"s": 6223,
"text": "In Conclusion"
},
{
"code": null,
"e": 6571,
"s": 6237,
"text": "Though we used kernels to do some pretty mundane things (detecting vertical and horizontal edges, finding the shapes of dogs), knowing how to use them correctly can be vital in your journey as a data scientist. As we have learned, some images may be easier to filter than others (particularly images with very well defined patterns)."
},
{
"code": null,
"e": 7051,
"s": 6571,
"text": "Remember that despite their parallels, our human minds interpret images very differently from our machines. Patterns that we usually ignore (such as lines in the sand) may be treated as important by the machine. In our case we had to first blur the image before enacting the proper filters, this is not too different from the way our own brains “junk” visual information. Just be aware that programming filters in the machine will help it see the world the way we want it to see."
}
] |
JavaScript Array unshift() Method - GeeksforGeeks
|
04 Oct, 2021
Below is the example of Array unshift() method.
Example:<script>function func() { // Original array var array = ["GFG", "Geeks", "for", "Geeks"]; // Checking for condition in array var value = array.unshift("GeeksforGeeks"); document.write(value); document.write("<br />"); document.write(array); } func();</script>
<script>function func() { // Original array var array = ["GFG", "Geeks", "for", "Geeks"]; // Checking for condition in array var value = array.unshift("GeeksforGeeks"); document.write(value); document.write("<br />"); document.write(array); } func();</script>
Output:5
GeeksforGeeks,GFG,Geeks,for,Geeks
5
GeeksforGeeks,GFG,Geeks,for,Geeks
The arr.unshift() method is used to add one or more elements to the beginning of the given array. This function increases the length of the existing array by the number of elements added to the array.
Syntax:
array.unshift(element1, element2, ..., elementX)
Parameters: This method accept a single parameters.
element: This parameter elements to be added at the beginning of the array.
Return value: This function returns the new length of the array after inserting the arguments at the beginning of the array.
Below examples illustrate the JavaScript Array unshift() method:
Example 1: In this example the function unshift() adds 28 and 65 to the front of the array.var arr = [23,76,19,94];
document.write(arr.unshift(28,65));
document.write(arr);
Output:6
28,65,23,76,19,94
var arr = [23,76,19,94];
document.write(arr.unshift(28,65));
document.write(arr);
Output:
6
28,65,23,76,19,94
Example 2: In this example the shift() method tries to remove the first element of the array, but the array is empty, therefore it returns undefined.var arr = [23,76,19,94];
document.write(arr.unshift());
document.write(arr);
Output:4
23,76,19,94
var arr = [23,76,19,94];
document.write(arr.unshift());
document.write(arr);
Output:
4
23,76,19,94
Code for the above method is provided below:Program 1:
// JavaScript to illustrate unshift() function<script>function sayHello() { var arr = [23,76,19,94]; // Adding elements to the front of the array document.write(arr.unshift(28,65)); document.write("<br>"); document.write(arr);}sayHello();</script>
Output:
6
28,65,23,76,19,94
Program 2:
// JavaScript to illustrate unshift() function<script>function sayHello() { var arr = [23,76,19,94]; // Adding elements to the front of the array document.write(arr.unshift(28,65)); document.write("<br>"); document.write(arr);}sayHello();</script>
Output:
4
23,76,19,94
Supported Browsers: The browsers supported by JavaScript Array unshift() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Opera 4 and above
Safari 1 and above
sakthipreetha2001
ysachin2314
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26692,
"s": 26664,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 26740,
"s": 26692,
"text": "Below is the example of Array unshift() method."
},
{
"code": null,
"e": 27047,
"s": 26740,
"text": "Example:<script>function func() { // Original array var array = [\"GFG\", \"Geeks\", \"for\", \"Geeks\"]; // Checking for condition in array var value = array.unshift(\"GeeksforGeeks\"); document.write(value); document.write(\"<br />\"); document.write(array); } func();</script>"
},
{
"code": "<script>function func() { // Original array var array = [\"GFG\", \"Geeks\", \"for\", \"Geeks\"]; // Checking for condition in array var value = array.unshift(\"GeeksforGeeks\"); document.write(value); document.write(\"<br />\"); document.write(array); } func();</script>",
"e": 27346,
"s": 27047,
"text": null
},
{
"code": null,
"e": 27389,
"s": 27346,
"text": "Output:5\nGeeksforGeeks,GFG,Geeks,for,Geeks"
},
{
"code": null,
"e": 27425,
"s": 27389,
"text": "5\nGeeksforGeeks,GFG,Geeks,for,Geeks"
},
{
"code": null,
"e": 27626,
"s": 27425,
"text": "The arr.unshift() method is used to add one or more elements to the beginning of the given array. This function increases the length of the existing array by the number of elements added to the array."
},
{
"code": null,
"e": 27634,
"s": 27626,
"text": "Syntax:"
},
{
"code": null,
"e": 27684,
"s": 27634,
"text": "array.unshift(element1, element2, ..., elementX)\n"
},
{
"code": null,
"e": 27736,
"s": 27684,
"text": "Parameters: This method accept a single parameters."
},
{
"code": null,
"e": 27812,
"s": 27736,
"text": "element: This parameter elements to be added at the beginning of the array."
},
{
"code": null,
"e": 27937,
"s": 27812,
"text": "Return value: This function returns the new length of the array after inserting the arguments at the beginning of the array."
},
{
"code": null,
"e": 28002,
"s": 27937,
"text": "Below examples illustrate the JavaScript Array unshift() method:"
},
{
"code": null,
"e": 28203,
"s": 28002,
"text": "Example 1: In this example the function unshift() adds 28 and 65 to the front of the array.var arr = [23,76,19,94];\ndocument.write(arr.unshift(28,65));\ndocument.write(arr);\nOutput:6\n28,65,23,76,19,94\n"
},
{
"code": null,
"e": 28286,
"s": 28203,
"text": "var arr = [23,76,19,94];\ndocument.write(arr.unshift(28,65));\ndocument.write(arr);\n"
},
{
"code": null,
"e": 28294,
"s": 28286,
"text": "Output:"
},
{
"code": null,
"e": 28315,
"s": 28294,
"text": "6\n28,65,23,76,19,94\n"
},
{
"code": null,
"e": 28562,
"s": 28315,
"text": "Example 2: In this example the shift() method tries to remove the first element of the array, but the array is empty, therefore it returns undefined.var arr = [23,76,19,94];\ndocument.write(arr.unshift());\ndocument.write(arr);\nOutput:4\n23,76,19,94"
},
{
"code": null,
"e": 28640,
"s": 28562,
"text": "var arr = [23,76,19,94];\ndocument.write(arr.unshift());\ndocument.write(arr);\n"
},
{
"code": null,
"e": 28648,
"s": 28640,
"text": "Output:"
},
{
"code": null,
"e": 28662,
"s": 28648,
"text": "4\n23,76,19,94"
},
{
"code": null,
"e": 28717,
"s": 28662,
"text": "Code for the above method is provided below:Program 1:"
},
{
"code": "// JavaScript to illustrate unshift() function<script>function sayHello() { var arr = [23,76,19,94]; // Adding elements to the front of the array document.write(arr.unshift(28,65)); document.write(\"<br>\"); document.write(arr);}sayHello();</script>",
"e": 28987,
"s": 28717,
"text": null
},
{
"code": null,
"e": 28995,
"s": 28987,
"text": "Output:"
},
{
"code": null,
"e": 29016,
"s": 28995,
"text": "6\n28,65,23,76,19,94\n"
},
{
"code": null,
"e": 29027,
"s": 29016,
"text": "Program 2:"
},
{
"code": "// JavaScript to illustrate unshift() function<script>function sayHello() { var arr = [23,76,19,94]; // Adding elements to the front of the array document.write(arr.unshift(28,65)); document.write(\"<br>\"); document.write(arr);}sayHello();</script>",
"e": 29297,
"s": 29027,
"text": null
},
{
"code": null,
"e": 29305,
"s": 29297,
"text": "Output:"
},
{
"code": null,
"e": 29319,
"s": 29305,
"text": "4\n23,76,19,94"
},
{
"code": null,
"e": 29417,
"s": 29319,
"text": "Supported Browsers: The browsers supported by JavaScript Array unshift() method are listed below:"
},
{
"code": null,
"e": 29443,
"s": 29417,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 29461,
"s": 29443,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 29481,
"s": 29461,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 29513,
"s": 29481,
"text": "Internet Explorer 5.5 and above"
},
{
"code": null,
"e": 29531,
"s": 29513,
"text": "Opera 4 and above"
},
{
"code": null,
"e": 29550,
"s": 29531,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 29568,
"s": 29550,
"text": "sakthipreetha2001"
},
{
"code": null,
"e": 29580,
"s": 29568,
"text": "ysachin2314"
},
{
"code": null,
"e": 29597,
"s": 29580,
"text": "javascript-array"
},
{
"code": null,
"e": 29616,
"s": 29597,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 29627,
"s": 29616,
"text": "JavaScript"
},
{
"code": null,
"e": 29644,
"s": 29627,
"text": "Web Technologies"
},
{
"code": null,
"e": 29742,
"s": 29644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29782,
"s": 29742,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29827,
"s": 29782,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29888,
"s": 29827,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29960,
"s": 29888,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30012,
"s": 29960,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30052,
"s": 30012,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30085,
"s": 30052,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30130,
"s": 30085,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30173,
"s": 30130,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
\blacktriangledown - Tex Command
|
\blacktriangledown - Used to draw black triangle down symbol.
{ \blacktriangledown }
\blacktriangledown command draws black triangle down symbol.
\blacktriangledown
▾
\blacktriangledown
▾
\blacktriangledown
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8048,
"s": 7986,
"text": "\\blacktriangledown - Used to draw black triangle down symbol."
},
{
"code": null,
"e": 8071,
"s": 8048,
"text": "{ \\blacktriangledown }"
},
{
"code": null,
"e": 8132,
"s": 8071,
"text": "\\blacktriangledown command draws black triangle down symbol."
},
{
"code": null,
"e": 8159,
"s": 8132,
"text": "\n\\blacktriangledown \n\n▾\n\n\n"
},
{
"code": null,
"e": 8184,
"s": 8159,
"text": "\\blacktriangledown \n\n▾\n\n"
},
{
"code": null,
"e": 8204,
"s": 8184,
"text": "\\blacktriangledown "
},
{
"code": null,
"e": 8236,
"s": 8204,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8249,
"s": 8236,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8282,
"s": 8249,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8295,
"s": 8282,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8327,
"s": 8295,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8363,
"s": 8327,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8398,
"s": 8363,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8415,
"s": 8398,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8448,
"s": 8415,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8462,
"s": 8448,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8494,
"s": 8462,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8509,
"s": 8494,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8516,
"s": 8509,
"text": " Print"
},
{
"code": null,
"e": 8527,
"s": 8516,
"text": " Add Notes"
}
] |
Find the Closest Element in BST | Practice | GeeksforGeeks
|
Given a BST and an integer. Find the least absolute difference between any node value of the BST and the given integer.
Example 1:
Input:
10
/ \
2 11
/ \
1 5
/ \
3 6
\
4
K = 13
Output: 2
Explanation: K=13. The node that has
value nearest to K is 11. so the answer
is 2
Example 2:
Input:
8
/ \
1 9
\ \
4 10
/
3
K = 9
Output: 0
Explanation: K=9. The node that has
value nearest to K is 9. so the answer
is 0.
Your Task:
You don't need to read input or print anything. Your task is to complete the function minDiff() that takes the root of the BST and an integer K as its input and returns the minimum absolute difference between any node value of the BST and the integer K.
Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 <= Number of nodes <= 100000
0
adarshsharadpandey231 day ago
vector<int> v;
void inOrder(Node* root)
{
if(root==NULL)
{
return;
}
inOrder(root->left);
v.push_back(root->data);
inOrder(root->right);
}
int minDiff(Node *root, int K)
{
//Your code here
int dif=K+1;
inOrder(root);
for(int i=0;i<v.size();i++)
{
if(v[i]-K>=0 && v[i]-K<dif)
{
dif=v[i]-K;
}
else if(K-v[i]>=0 && K-v[i]<dif)
{
dif=K-v[i];
}
}
return dif;
}
0
rengarajan6 days ago
def minDiff(self,root, K):
# code here
if root is None:
return float("inf")
else:
return min(abs(root.data-K),self.minDiff(root.left,K),self.minDiff(root.right,K))
Python
+1
swastikp17112 weeks ago
Optimized Java Solution ( Iterative approach )
class Solution
{
static int minDiff(Node root, int k)
{
int minAbsDiff=Integer.MAX_VALUE;
int absDiff=0;
while(root!=null){
if(root.data==k) return 0;
absDiff=Math.abs(root.data-k);
minAbsDiff=Math.min(minAbsDiff,absDiff);
if(k<root.data){
root=root.left;
}else{
root=root.right;
}
}
return minAbsDiff;
}
}
+1
geniusambi882 weeks ago
Different approach using Ceil and floor function
int floor(Node *root ,int x){ int res=0; while(root!=NULL) { if(root->data==x) { return root->data; } if(root->data>x) { root=root->left; } else{ res=root->data; root=root->right; } } return res;}int ceil(Node *root ,int x){ int res=0; while(root!=NULL) { if(root->data==x) { return root->data; } if(root->data>x) { res=root->data; root=root->left; } else{ root=root->right; } } return res;} int minDiff(Node *root, int K) { //Your code here int f=floor(root,K); int c= ceil(root,K); int fd =abs(f-K); int cd=abs(c-K); int res =min(fd,cd); return res; }
0
pritamtech19984 weeks ago
nt minDiff(Node *root, int K) { if(root){ int d = abs(root->data - K); if(K > root->data) return min(d, minDiff(root->right, K)); else if(K < root->data) return min(d, minDiff(root->left, K)); else return 0; }else return INT_MAX; }
+1
badgujarsachin831 month ago
void cheak(Node* root, int k,int &dif){
if(root==NULL){
return ;
}
int curdif=abs(k-root->data);
if(curdif<dif){
dif=curdif;
}
if(k<root->data){
cheak(root->left,k,dif);
}
else{
cheak(root->right,k,dif);
}
}
int minDiff(Node *root, int K)
{
int dif=INT_MAX;
cheak(root,K,dif);
return dif;
}
0
jayanth2642 months ago
void finddiff(Node *root, int K,int &diff){ if(root==NULL) { return; } int currentdiff=abs(K-root->data); if(currentdiff<diff) { diff=currentdiff; } if(K<root->data) { finddiff(root->left,K,diff); } else { finddiff(root->right,K,diff); } } int minDiff(Node *root, int K) { int diff=INT_MAX; finddiff(root,K,diff); return diff; }
-2
vermabhishek6572 months ago
cpp solution
int minDiff(Node *root, int K) { //Your code here if(root==NULL) return K; queue<Node*> q; q.push(root); int res=INT_MAX; while(q.empty()==false) { Node*curr=q.front(); if(curr->data==K) return 0; res= min(res,abs(K-curr->data)); q.pop(); if(curr->left!=NULL) q.push(curr->left); if(curr->right!=NULL) q.push(curr->right); } return res; }
0
jai20222 months ago
Easy C++ using inorder traversal
void inorder(Node* root,int &diff,int K){ if(root==NULL) return; inorder(root->left,diff,K); diff = min(diff,abs(K-root->data)); inorder(root->right,diff,K);} int minDiff(Node *root, int K) { //Your code here int diff = INT_MAX; inorder(root,diff,K); return diff; }
0
emmanueluluabuike2 months ago
Java Solution
static int minDiff(Node root, int k) {
// Write your code here
int ans = 0;
if(root == null) // base case
return k;
if(root.data == k) // base case
return ans;
int firstNodeDiff = Math.abs(root.data - k); // sub the first node.data from k to find the min difference
if(k < root.data)
ans = minDiff(root.left, k);
else
ans = minDiff(root.right, k);
return Math.min(ans, firstNodeDiff);
}
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": 358,
"s": 238,
"text": "Given a BST and an integer. Find the least absolute difference between any node value of the BST and the given integer."
},
{
"code": null,
"e": 369,
"s": 358,
"text": "Example 1:"
},
{
"code": null,
"e": 570,
"s": 369,
"text": "Input:\n 10\n / \\\n 2 11\n / \\ \n 1 5\n / \\\n 3 6\n \\\n 4\nK = 13\nOutput: 2\nExplanation: K=13. The node that has\nvalue nearest to K is 11. so the answer\nis 2\n"
},
{
"code": null,
"e": 581,
"s": 570,
"text": "Example 2:"
},
{
"code": null,
"e": 750,
"s": 581,
"text": "Input:\n 8\n / \\\n 1 9\n \\ \\\n 4 10\n /\n 3\nK = 9\nOutput: 0\nExplanation: K=9. The node that has\nvalue nearest to K is 9. so the answer\nis 0."
},
{
"code": null,
"e": 1015,
"s": 750,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function minDiff() that takes the root of the BST and an integer K as its input and returns the minimum absolute difference between any node value of the BST and the integer K."
},
{
"code": null,
"e": 1111,
"s": 1015,
"text": "Expected Time Complexity: O(Height of the BST).\nExpected Auxiliary Space: O(Height of the BST)."
},
{
"code": null,
"e": 1155,
"s": 1111,
"text": "Constraints:\n1 <= Number of nodes <= 100000"
},
{
"code": null,
"e": 1157,
"s": 1155,
"text": "0"
},
{
"code": null,
"e": 1187,
"s": 1157,
"text": "adarshsharadpandey231 day ago"
},
{
"code": null,
"e": 1762,
"s": 1187,
"text": "vector<int> v;\n\tvoid inOrder(Node* root)\n\t{\n\t if(root==NULL)\n\t {\n\t return;\n\t }\n\t inOrder(root->left);\n\t v.push_back(root->data);\n\t inOrder(root->right);\n\t}\n int minDiff(Node *root, int K)\n {\n //Your code here\n int dif=K+1;\n inOrder(root);\n for(int i=0;i<v.size();i++)\n {\n if(v[i]-K>=0 && v[i]-K<dif)\n {\n dif=v[i]-K;\n }\n else if(K-v[i]>=0 && K-v[i]<dif)\n {\n dif=K-v[i];\n }\n }\n return dif;\n \n }"
},
{
"code": null,
"e": 1764,
"s": 1762,
"text": "0"
},
{
"code": null,
"e": 1785,
"s": 1764,
"text": "rengarajan6 days ago"
},
{
"code": null,
"e": 1998,
"s": 1785,
"text": " def minDiff(self,root, K):\n # code here\n if root is None:\n return float(\"inf\")\n else:\n return min(abs(root.data-K),self.minDiff(root.left,K),self.minDiff(root.right,K))"
},
{
"code": null,
"e": 2005,
"s": 1998,
"text": "Python"
},
{
"code": null,
"e": 2008,
"s": 2005,
"text": "+1"
},
{
"code": null,
"e": 2032,
"s": 2008,
"text": "swastikp17112 weeks ago"
},
{
"code": null,
"e": 2079,
"s": 2032,
"text": "Optimized Java Solution ( Iterative approach )"
},
{
"code": null,
"e": 2607,
"s": 2079,
"text": "class Solution\n{\n static int minDiff(Node root, int k) \n { \n int minAbsDiff=Integer.MAX_VALUE; \n int absDiff=0;\n \n while(root!=null){\n\n if(root.data==k) return 0;\n \n absDiff=Math.abs(root.data-k);\n minAbsDiff=Math.min(minAbsDiff,absDiff);\n \n if(k<root.data){\n root=root.left;\n }else{\n root=root.right;\n }\n \n }\n return minAbsDiff;\n } \n}"
},
{
"code": null,
"e": 2610,
"s": 2607,
"text": "+1"
},
{
"code": null,
"e": 2634,
"s": 2610,
"text": "geniusambi882 weeks ago"
},
{
"code": null,
"e": 2683,
"s": 2634,
"text": "Different approach using Ceil and floor function"
},
{
"code": null,
"e": 3503,
"s": 2687,
"text": " int floor(Node *root ,int x){ int res=0; while(root!=NULL) { if(root->data==x) { return root->data; } if(root->data>x) { root=root->left; } else{ res=root->data; root=root->right; } } return res;}int ceil(Node *root ,int x){ int res=0; while(root!=NULL) { if(root->data==x) { return root->data; } if(root->data>x) { res=root->data; root=root->left; } else{ root=root->right; } } return res;} int minDiff(Node *root, int K) { //Your code here int f=floor(root,K); int c= ceil(root,K); int fd =abs(f-K); int cd=abs(c-K); int res =min(fd,cd); return res; } "
},
{
"code": null,
"e": 3505,
"s": 3503,
"text": "0"
},
{
"code": null,
"e": 3531,
"s": 3505,
"text": "pritamtech19984 weeks ago"
},
{
"code": null,
"e": 3871,
"s": 3531,
"text": "nt minDiff(Node *root, int K) { if(root){ int d = abs(root->data - K); if(K > root->data) return min(d, minDiff(root->right, K)); else if(K < root->data) return min(d, minDiff(root->left, K)); else return 0; }else return INT_MAX; }"
},
{
"code": null,
"e": 3874,
"s": 3871,
"text": "+1"
},
{
"code": null,
"e": 3902,
"s": 3874,
"text": "badgujarsachin831 month ago"
},
{
"code": null,
"e": 4309,
"s": 3902,
"text": "\tvoid cheak(Node* root, int k,int &dif){\n\t if(root==NULL){\n\t return ;\n\t }\n\t int curdif=abs(k-root->data);\n\t if(curdif<dif){\n\t dif=curdif;\n\t }\n\t if(k<root->data){\n\t cheak(root->left,k,dif);\n\t }\n\t else{\n\t cheak(root->right,k,dif);\n\t }\n\t \n\t}\n int minDiff(Node *root, int K)\n {\n int dif=INT_MAX;\n cheak(root,K,dif);\n return dif;\n }"
},
{
"code": null,
"e": 4311,
"s": 4309,
"text": "0"
},
{
"code": null,
"e": 4334,
"s": 4311,
"text": "jayanth2642 months ago"
},
{
"code": null,
"e": 4765,
"s": 4334,
"text": " void finddiff(Node *root, int K,int &diff){ if(root==NULL) { return; } int currentdiff=abs(K-root->data); if(currentdiff<diff) { diff=currentdiff; } if(K<root->data) { finddiff(root->left,K,diff); } else { finddiff(root->right,K,diff); } } int minDiff(Node *root, int K) { int diff=INT_MAX; finddiff(root,K,diff); return diff; }"
},
{
"code": null,
"e": 4768,
"s": 4765,
"text": "-2"
},
{
"code": null,
"e": 4796,
"s": 4768,
"text": "vermabhishek6572 months ago"
},
{
"code": null,
"e": 4810,
"s": 4796,
"text": "cpp solution "
},
{
"code": null,
"e": 5538,
"s": 4812,
"text": " int minDiff(Node *root, int K) { //Your code here if(root==NULL) return K; queue<Node*> q; q.push(root); int res=INT_MAX; while(q.empty()==false) { Node*curr=q.front(); if(curr->data==K) return 0; res= min(res,abs(K-curr->data)); q.pop(); if(curr->left!=NULL) q.push(curr->left); if(curr->right!=NULL) q.push(curr->right); } return res; }"
},
{
"code": null,
"e": 5540,
"s": 5538,
"text": "0"
},
{
"code": null,
"e": 5560,
"s": 5540,
"text": "jai20222 months ago"
},
{
"code": null,
"e": 5593,
"s": 5560,
"text": "Easy C++ using inorder traversal"
},
{
"code": null,
"e": 5903,
"s": 5595,
"text": "void inorder(Node* root,int &diff,int K){ if(root==NULL) return; inorder(root->left,diff,K); diff = min(diff,abs(K-root->data)); inorder(root->right,diff,K);} int minDiff(Node *root, int K) { //Your code here int diff = INT_MAX; inorder(root,diff,K); return diff; }"
},
{
"code": null,
"e": 5905,
"s": 5903,
"text": "0"
},
{
"code": null,
"e": 5935,
"s": 5905,
"text": "emmanueluluabuike2 months ago"
},
{
"code": null,
"e": 5949,
"s": 5935,
"text": "Java Solution"
},
{
"code": null,
"e": 6472,
"s": 5949,
"text": "static int minDiff(Node root, int k) { \n // Write your code here\n int ans = 0;\n if(root == null) // base case\n return k;\n if(root.data == k) // base case\n return ans;\n\n int firstNodeDiff = Math.abs(root.data - k); // sub the first node.data from k to find the min difference\n \n if(k < root.data)\n ans = minDiff(root.left, k);\n else\n ans = minDiff(root.right, k);\n \n return Math.min(ans, firstNodeDiff);\n } "
},
{
"code": null,
"e": 6618,
"s": 6472,
"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": 6654,
"s": 6618,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6664,
"s": 6654,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6674,
"s": 6664,
"text": "\nContest\n"
},
{
"code": null,
"e": 6737,
"s": 6674,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6885,
"s": 6737,
"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": 7093,
"s": 6885,
"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": 7199,
"s": 7093,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Program to Illustrate Escaping Characters in Regex - GeeksforGeeks
|
30 Sep, 2021
Special Characters like dot(.), hash(#), etc., which have a special meaning to the regular expression need to be escaped to match in the regular expression. For example, if dot(.) is not escaped in a regular expression, it matches any single character, thus giving ambiguous results.
Methods:
Characters can be escaped in Java Regex in two ways which are listed as follows which we will be discussing upto depth:
Using \Q and \E for escapingUsing backslash(\\) for escaping
Using \Q and \E for escaping
Using backslash(\\) for escaping
Method 1: Using \Q and \E for escaping
We can use the \Q and \E escape sequences to escape characters.
\Q marks the start of the escape sequence whereas \E marks the end of the escape sequence.
Any characters between the \Q and \E are escaped.
Generally used for escaping multiple characters.
In the below source code the Regex pattern p is escaped for the dot(.) operator, whereas the pattern p1 is not escaped for dot(.). Thus, the pattern p matches only with the string s whereas the pattern p1 matches with both the strings s and s1.
Example
Java
// Java Program to Illustrate Escaping Characters in Java// Regex Using \Q and \E for escaping // Importing required classesimport java.io.*;import java.util.regex.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Sample strings as inputs String s = "Geeks.forGeeks"; String s1 = "GeeksforGeeks"; // Creating object of Pattern class // 1. Patterns with dot escaped Pattern p = Pattern.compile("\\Q.\\E"); // 2, Pattern without dot escaped Pattern p1 = Pattern.compile("."); // Matchers for each pattern string combination Matcher m = p.matcher(s); Matcher m1 = p.matcher(s1); Matcher m2 = p1.matcher(s); Matcher m3 = p1.matcher(s1); // Print and display whether p,p1 matches // or not via boolean true false System.out.println("p matches s: " + m.find()); System.out.println("p matches s1: " + m1.find()); System.out.println("p1 matches s: " + m2.find()); System.out.println("p1 matches s1: " + m3.find()); }}
p matches s: true
p matches s1: false
p1 matches s: true
p1 matches s1: true
Method 2: Using backslash(\\) for escaping
We can use a backslash to escape characters.
We require two backslashes as backslash is itself a character and needs to be escaped.
Characters after \\ are escaped.
It is generally used to escape characters at the end of the string.
Implementation:
In the below source code the Regex pattern p is escaped for the dot(.) operator, whereas the pattern p1 is not escaped for dot(.). Thus the pattern p matches only with the string s whereas the pattern p1 matches with both the strings s and s1.
Example:
Java
/*package whatever //do not write package name here */ import java.io.*;import java.util.regex.*; class GFG { public static void main (String[] args) { String s="Geeks.forGeeks";//sample strings String s1="GeeksforGeeks"; //patterns with dot escaped Pattern p=Pattern.compile("\\."); // pattern without dot escaped Pattern p1=Pattern.compile("."); //matchers for each pattern string combination Matcher m=p.matcher(s); Matcher m1=p.matcher(s1); Matcher m2=p1.matcher(s); Matcher m3=p1.matcher(s1); //outputs System.out.println("p matches s: "+m.find()); System.out.println("p matches s1: "+m1.find()); System.out.println("p1 matches s: "+m2.find()); System.out.println("p1 matches s1: "+m3.find()); }}
Output:
p matches s: true
p matches s1: false
p1 matches s: true
p1 matches s1: true
gabaa406
anikaseth98
java-regular-expression
Picked
Java
Java Programs
Java
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
Stream In Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Convert a String to Character array in Java
Java Programming Examples
How to Iterate HashMap in Java?
Implementing a Linked List in Java using Class
Min Heap in Java
|
[
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 23865,
"s": 23581,
"text": "Special Characters like dot(.), hash(#), etc., which have a special meaning to the regular expression need to be escaped to match in the regular expression. For example, if dot(.) is not escaped in a regular expression, it matches any single character, thus giving ambiguous results."
},
{
"code": null,
"e": 23875,
"s": 23865,
"text": "Methods: "
},
{
"code": null,
"e": 23995,
"s": 23875,
"text": "Characters can be escaped in Java Regex in two ways which are listed as follows which we will be discussing upto depth:"
},
{
"code": null,
"e": 24056,
"s": 23995,
"text": "Using \\Q and \\E for escapingUsing backslash(\\\\) for escaping"
},
{
"code": null,
"e": 24085,
"s": 24056,
"text": "Using \\Q and \\E for escaping"
},
{
"code": null,
"e": 24118,
"s": 24085,
"text": "Using backslash(\\\\) for escaping"
},
{
"code": null,
"e": 24157,
"s": 24118,
"text": "Method 1: Using \\Q and \\E for escaping"
},
{
"code": null,
"e": 24221,
"s": 24157,
"text": "We can use the \\Q and \\E escape sequences to escape characters."
},
{
"code": null,
"e": 24312,
"s": 24221,
"text": "\\Q marks the start of the escape sequence whereas \\E marks the end of the escape sequence."
},
{
"code": null,
"e": 24362,
"s": 24312,
"text": "Any characters between the \\Q and \\E are escaped."
},
{
"code": null,
"e": 24411,
"s": 24362,
"text": "Generally used for escaping multiple characters."
},
{
"code": null,
"e": 24656,
"s": 24411,
"text": "In the below source code the Regex pattern p is escaped for the dot(.) operator, whereas the pattern p1 is not escaped for dot(.). Thus, the pattern p matches only with the string s whereas the pattern p1 matches with both the strings s and s1."
},
{
"code": null,
"e": 24664,
"s": 24656,
"text": "Example"
},
{
"code": null,
"e": 24669,
"s": 24664,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Escaping Characters in Java// Regex Using \\Q and \\E for escaping // Importing required classesimport java.io.*;import java.util.regex.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Sample strings as inputs String s = \"Geeks.forGeeks\"; String s1 = \"GeeksforGeeks\"; // Creating object of Pattern class // 1. Patterns with dot escaped Pattern p = Pattern.compile(\"\\\\Q.\\\\E\"); // 2, Pattern without dot escaped Pattern p1 = Pattern.compile(\".\"); // Matchers for each pattern string combination Matcher m = p.matcher(s); Matcher m1 = p.matcher(s1); Matcher m2 = p1.matcher(s); Matcher m3 = p1.matcher(s1); // Print and display whether p,p1 matches // or not via boolean true false System.out.println(\"p matches s: \" + m.find()); System.out.println(\"p matches s1: \" + m1.find()); System.out.println(\"p1 matches s: \" + m2.find()); System.out.println(\"p1 matches s1: \" + m3.find()); }}",
"e": 25775,
"s": 24669,
"text": null
},
{
"code": null,
"e": 25852,
"s": 25775,
"text": "p matches s: true\np matches s1: false\np1 matches s: true\np1 matches s1: true"
},
{
"code": null,
"e": 25895,
"s": 25852,
"text": "Method 2: Using backslash(\\\\) for escaping"
},
{
"code": null,
"e": 25940,
"s": 25895,
"text": "We can use a backslash to escape characters."
},
{
"code": null,
"e": 26027,
"s": 25940,
"text": "We require two backslashes as backslash is itself a character and needs to be escaped."
},
{
"code": null,
"e": 26060,
"s": 26027,
"text": "Characters after \\\\ are escaped."
},
{
"code": null,
"e": 26128,
"s": 26060,
"text": "It is generally used to escape characters at the end of the string."
},
{
"code": null,
"e": 26144,
"s": 26128,
"text": "Implementation:"
},
{
"code": null,
"e": 26388,
"s": 26144,
"text": "In the below source code the Regex pattern p is escaped for the dot(.) operator, whereas the pattern p1 is not escaped for dot(.). Thus the pattern p matches only with the string s whereas the pattern p1 matches with both the strings s and s1."
},
{
"code": null,
"e": 26397,
"s": 26388,
"text": "Example:"
},
{
"code": null,
"e": 26402,
"s": 26397,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.regex.*; class GFG { public static void main (String[] args) { String s=\"Geeks.forGeeks\";//sample strings String s1=\"GeeksforGeeks\"; //patterns with dot escaped Pattern p=Pattern.compile(\"\\\\.\"); // pattern without dot escaped Pattern p1=Pattern.compile(\".\"); //matchers for each pattern string combination Matcher m=p.matcher(s); Matcher m1=p.matcher(s1); Matcher m2=p1.matcher(s); Matcher m3=p1.matcher(s1); //outputs System.out.println(\"p matches s: \"+m.find()); System.out.println(\"p matches s1: \"+m1.find()); System.out.println(\"p1 matches s: \"+m2.find()); System.out.println(\"p1 matches s1: \"+m3.find()); }}",
"e": 27262,
"s": 26402,
"text": null
},
{
"code": null,
"e": 27270,
"s": 27262,
"text": "Output:"
},
{
"code": null,
"e": 27347,
"s": 27270,
"text": "p matches s: true\np matches s1: false\np1 matches s: true\np1 matches s1: true"
},
{
"code": null,
"e": 27356,
"s": 27347,
"text": "gabaa406"
},
{
"code": null,
"e": 27368,
"s": 27356,
"text": "anikaseth98"
},
{
"code": null,
"e": 27392,
"s": 27368,
"text": "java-regular-expression"
},
{
"code": null,
"e": 27399,
"s": 27392,
"text": "Picked"
},
{
"code": null,
"e": 27404,
"s": 27399,
"text": "Java"
},
{
"code": null,
"e": 27418,
"s": 27404,
"text": "Java Programs"
},
{
"code": null,
"e": 27423,
"s": 27418,
"text": "Java"
},
{
"code": null,
"e": 27521,
"s": 27423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27530,
"s": 27521,
"text": "Comments"
},
{
"code": null,
"e": 27543,
"s": 27530,
"text": "Old Comments"
},
{
"code": null,
"e": 27564,
"s": 27543,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27583,
"s": 27564,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27598,
"s": 27583,
"text": "Stream In Java"
},
{
"code": null,
"e": 27628,
"s": 27598,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27674,
"s": 27628,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27718,
"s": 27674,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27744,
"s": 27718,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27776,
"s": 27744,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 27823,
"s": 27776,
"text": "Implementing a Linked List in Java using Class"
}
] |
How to create a swipe refresh layout in Android using Kotlin?
|
This example demonstrates how to create a swipe refresh layout in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Swipe to Reload"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
class MainActivity : AppCompatActivity() {
lateinit var swipeRefreshLayout: SwipeRefreshLayout
lateinit var textView: TextView
var number: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
swipeRefreshLayout = findViewById(R.id.swipe)
textView = findViewById(R.id.textView)
swipeRefreshLayout.setOnRefreshListener {
number++
textView.text = " Total number = $number"
Handler().postDelayed(Runnable {
swipeRefreshLayout.isRefreshing = false
}, 4000)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Click here to download the project code.
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how to create a swipe refresh layout in Android using Kotlin."
},
{
"code": null,
"e": 1279,
"s": 1150,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1344,
"s": 1279,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2193,
"s": 1344,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <androidx.swiperefreshlayout.widget.SwipeRefreshLayout\n android:id=\"@+id/swipe\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:gravity=\"center\"\n android:text=\"Swipe to Reload\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>\n</RelativeLayout>"
},
{
"code": null,
"e": 2248,
"s": 2193,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3104,
"s": 2248,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.os.Handler\nimport android.widget.TextView\nimport androidx.swiperefreshlayout.widget.SwipeRefreshLayout\nclass MainActivity : AppCompatActivity() {\n lateinit var swipeRefreshLayout: SwipeRefreshLayout\n lateinit var textView: TextView\n var number: Int = 0\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n swipeRefreshLayout = findViewById(R.id.swipe)\n textView = findViewById(R.id.textView)\n swipeRefreshLayout.setOnRefreshListener {\n number++\n textView.text = \" Total number = $number\"\n Handler().postDelayed(Runnable {\n swipeRefreshLayout.isRefreshing = false\n }, 4000)\n }\n }\n}"
},
{
"code": null,
"e": 3159,
"s": 3104,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3833,
"s": 3159,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4183,
"s": 3833,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 4224,
"s": 4183,
"text": "Click here to download the project code."
}
] |
Angular CLI - ng e2e Command
|
This chapter explains the syntax, argument and options of ng e2e command along with an example. Here, e2e refers to end to end.
The syntax for ng e2e command is as follows −
ng e2e <project> [options]
ng e <project> [options]
ng e2e builds, serves an application and then runs the end to end test cases using protractor. Options are optional parameters.
The argument for ng e2e command is as follows −
Options are optional parameters.
A named build target, as specified in the "configurations" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the "--prod" flag
Aliases: -c
Shows a help message for this command in the console.
Default: false
Invert the selection specified by the 'grep' option.
Default: false
Try to update webdriver.
Default: true
First move to an angular project updated using ng build command.which is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm.
Now run the e2e command.
An example for ng e2e command is given below −
\>Node\>TutorialsPoint> ng e2e
...
chunk {main} main.js, main.js.map (main) 14.3 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3 MB [initial] [rendered]
Date: 2020-06-06T04:20:15.029Z - Hash: 16f321e3d4599af26622 - Time: 20899ms
** Angular Live Development Server is listening on localhost:4200, open your bro
wser on http://localhost:4200/ **
: Compiled successfully.
...
workspace-project App
x should display welcome message
- Failed: No element found using locator: By(css selector, app-root .content span)
...
From: Task: Run it("should display welcome message") in control flow
...
**************************************************
* Failures *
**************************************************
1) workspace-project App should display welcome message
- Failed: No element found using locator: By(css selector, app-root .content span)
Executed 1 of 1 spec (1 FAILED) in 2 secs.
Now to fix failures update the app.component.html
app.component.html
<div class="content" role="main">
<span>{{ title }} app is running!</span>
</div>
<app-goals></app-goals>
<router-outlet></router-outlet>
Now run the e2e command.
An example for ng e2e command is given below −
\>Node\>TutorialsPoint> ng e2e
...
chunk {main} main.js, main.js.map (main) 14.9 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3 MB [initial] [rendered]
Date: 2020-06-06T04:28:33.514Z - Hash: 5d8bf2fc7ff59fa390b0 - Time: 10529ms
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
: Compiled successfully.
...
workspace-project App
√ should display welcome message
Executed 1 of 1 spec SUCCESS in 2 secs.
ng e2e also opens the browser and use it to run acceptance test cases using UI.
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": 2203,
"s": 2075,
"text": "This chapter explains the syntax, argument and options of ng e2e command along with an example. Here, e2e refers to end to end."
},
{
"code": null,
"e": 2249,
"s": 2203,
"text": "The syntax for ng e2e command is as follows −"
},
{
"code": null,
"e": 2302,
"s": 2249,
"text": "ng e2e <project> [options]\nng e <project> [options]\n"
},
{
"code": null,
"e": 2430,
"s": 2302,
"text": "ng e2e builds, serves an application and then runs the end to end test cases using protractor. Options are optional parameters."
},
{
"code": null,
"e": 2478,
"s": 2430,
"text": "The argument for ng e2e command is as follows −"
},
{
"code": null,
"e": 2511,
"s": 2478,
"text": "Options are optional parameters."
},
{
"code": null,
"e": 2735,
"s": 2511,
"text": "A named build target, as specified in the \"configurations\" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the \"--prod\" flag"
},
{
"code": null,
"e": 2747,
"s": 2735,
"text": "Aliases: -c"
},
{
"code": null,
"e": 2801,
"s": 2747,
"text": "Shows a help message for this command in the console."
},
{
"code": null,
"e": 2816,
"s": 2801,
"text": "Default: false"
},
{
"code": null,
"e": 2869,
"s": 2816,
"text": "Invert the selection specified by the 'grep' option."
},
{
"code": null,
"e": 2884,
"s": 2869,
"text": "Default: false"
},
{
"code": null,
"e": 2909,
"s": 2884,
"text": "Try to update webdriver."
},
{
"code": null,
"e": 2923,
"s": 2909,
"text": "Default: true"
},
{
"code": null,
"e": 3078,
"s": 2923,
"text": "First move to an angular project updated using ng build command.which is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm."
},
{
"code": null,
"e": 3103,
"s": 3078,
"text": "Now run the e2e command."
},
{
"code": null,
"e": 3150,
"s": 3103,
"text": "An example for ng e2e command is given below −"
},
{
"code": null,
"e": 4377,
"s": 3150,
"text": "\\>Node\\>TutorialsPoint> ng e2e\n...\nchunk {main} main.js, main.js.map (main) 14.3 kB [initial] [rendered]\nchunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]\nchunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]\nchunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]\nchunk {vendor} vendor.js, vendor.js.map (vendor) 3 MB [initial] [rendered]\nDate: 2020-06-06T04:20:15.029Z - Hash: 16f321e3d4599af26622 - Time: 20899ms\n** Angular Live Development Server is listening on localhost:4200, open your bro\nwser on http://localhost:4200/ **\n: Compiled successfully.\n...\n workspace-project App\n x should display welcome message\n - Failed: No element found using locator: By(css selector, app-root .content span)\n ...\n From: Task: Run it(\"should display welcome message\") in control flow\n ...\n**************************************************\n* Failures *\n**************************************************\n\n1) workspace-project App should display welcome message\n - Failed: No element found using locator: By(css selector, app-root .content span)\n\nExecuted 1 of 1 spec (1 FAILED) in 2 secs.\n"
},
{
"code": null,
"e": 4427,
"s": 4377,
"text": "Now to fix failures update the app.component.html"
},
{
"code": null,
"e": 4446,
"s": 4427,
"text": "app.component.html"
},
{
"code": null,
"e": 4588,
"s": 4446,
"text": "<div class=\"content\" role=\"main\">\n <span>{{ title }} app is running!</span>\n</div>\n<app-goals></app-goals>\n<router-outlet></router-outlet>\n"
},
{
"code": null,
"e": 4613,
"s": 4588,
"text": "Now run the e2e command."
},
{
"code": null,
"e": 4660,
"s": 4613,
"text": "An example for ng e2e command is given below −"
},
{
"code": null,
"e": 5412,
"s": 4660,
"text": "\\>Node\\>TutorialsPoint> ng e2e\n...\nchunk {main} main.js, main.js.map (main) 14.9 kB [initial] [rendered]\nchunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]\nchunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]\nchunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]\nchunk {vendor} vendor.js, vendor.js.map (vendor) 3 MB [initial] [rendered]\nDate: 2020-06-06T04:28:33.514Z - Hash: 5d8bf2fc7ff59fa390b0 - Time: 10529ms\n** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **\n: Compiled successfully.\n...\n workspace-project App\n √ should display welcome message\n\nExecuted 1 of 1 spec SUCCESS in 2 secs.\n"
},
{
"code": null,
"e": 5492,
"s": 5412,
"text": "ng e2e also opens the browser and use it to run acceptance test cases using UI."
},
{
"code": null,
"e": 5527,
"s": 5492,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5541,
"s": 5527,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5576,
"s": 5541,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5590,
"s": 5576,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5625,
"s": 5590,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5645,
"s": 5625,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5680,
"s": 5645,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5697,
"s": 5680,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5730,
"s": 5697,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5742,
"s": 5730,
"text": " Senol Atac"
},
{
"code": null,
"e": 5777,
"s": 5742,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5789,
"s": 5777,
"text": " Senol Atac"
},
{
"code": null,
"e": 5796,
"s": 5789,
"text": " Print"
},
{
"code": null,
"e": 5807,
"s": 5796,
"text": " Add Notes"
}
] |
What is the groups() method in regular expressions in Python?
|
This method returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.
>>> m = re.match(r"(\d+)\.(\d+)", "27.1835")
>>> m.groups()
('27', '1835')
If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to None unless the default argument is given −
>>> m = re.match(r"(\d+)\.?(\d+)?", "27")
>>> m.groups() # Second group defaults to None.
('27', None)
>>> m.groups('0') # Now, the second group defaults to '0'.
('27', '0')
|
[
{
"code": null,
"e": 1367,
"s": 1062,
"text": "This method returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases."
},
{
"code": null,
"e": 1442,
"s": 1367,
"text": ">>> m = re.match(r\"(\\d+)\\.(\\d+)\", \"27.1835\")\n>>> m.groups()\n('27', '1835')"
},
{
"code": null,
"e": 1625,
"s": 1442,
"text": "If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to None unless the default argument is given −"
},
{
"code": null,
"e": 1806,
"s": 1625,
"text": ">>> m = re.match(r\"(\\d+)\\.?(\\d+)?\", \"27\")\n>>> m.groups() # Second group defaults to None.\n('27', None)\n>>> m.groups('0') # Now, the second group defaults to '0'.\n('27', '0')"
}
] |
TypeORM - Entity
|
An entity is a collection of fields and associated database operations. It is used to map database table and its fields with the entities and its attributes. This chapter explains about the TypeORM entities in detail.
Let us create a simple Entity class in our code. Move to your project root location and go inside src folder and move to entity folder. Now, create a TypeScript file, Student.ts and enter below code −
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class Student {
@PrimaryGeneratedColumn()
id: number;
@Column()
Name: string;
@Column()
age: number;
}
Here,
Entity() decorator class is used to represent that the Student class is an entity.
PrimaryGeneratedColumn() decorator class is used to represent that the id column is the primary key column of the Student entity.
Column() decorator class is used to represent other columns such as Name and Age of the Student entity.
Now, Entity class Student is created. TypeORM will auto generate a table corresponding to the Student entity in our database and it will be named as student. Now, move to src/index.ts file and add the following code −
import "reflect-metadata";
import {createConnection} from "typeorm";
import {Student} from "./entity/Student"; //import Student entity
createConnection().then(async connection => {
console.log("Inserting a new record into the student database...");
//create student object const stud = new Student();
//Assign student name and age here stud.Name = "student1";
stud.age = 12;
//save student object in connection await connection.manager.save(stud); console.log("Saved a new user with id: " + stud.id);
console.log("Loading users from the database...");
//Display student saved records const students = await connection.manager.find(Student); console.log("Loaded users: ", students);
console.log("Here you can setup and run express/koa/any other framework.");
}).catch(error => console.log(error));
Here,
Line 1 - 3 imports the relevant classes, createConnection and Student
Line 5 creates a new connection to the database using createConnection and if connection is established, it executes the code inside the then block.
Line 10 create new Student object, stud.
Line 13-14 set the attributes of our newly created stud object.
Line 17 saves the entity to the database using save method available in connection.manager object.
Line 23 fetches the student details from the database using find method available in connection.manager object.
We have created Student entity and create connection in index.ts. Let us start both MySql server and your application.
npm start
This will return the following output on your screen −
Open mysql server following student table is added inside your database.
As learned earlier, Entity is actually a collection of attributes. As entity object refers the database table. Its attributes / member variables refer the corresponding database table’s fields / columns. TypeORM supports all type of database fields through Column class. Let us learn the different type of column supported by TypeORM in this chapter.
@Column() decorator class is used to represent the column and its type in the entity.
For example, age attribute of the student entity and the type of the age attribute can be defined as below −
@Column("int") age: integer; // OR @Column({ type: "int" }) age: integer;
Here,
age is the attribute of the entity. In other word, age is a field / column in the student table in the database.
int represent the type of the age column in the database.
TypeORM supports nearly all the types available in the popular database engine. Actually, TypeORM enables different set of types for each database engine. We can use any database type supported by our database engine without any issue.
For example, the type supported by TypeORM for postgresql database engine is as follows −
int, int2, int4, int8, smallint, integer, bigint, decimal, numeric, real, float, float4, float8, double precision, money, character varying,
varchar, character, char, text, citext, hstore, bytea, bit, varbit, bit
varying, timetz, timestamptz, timestamp, timestamp without time zone, timestamp with time zone, date, time, time without time zone, time with time zone, interval, bool, boolean, enum, point, line, lseg, box, path, polygon, circle, cidr, inet, macaddr, tsvector, tsquery, uuid, xml, json, jsonb, int4range, int8range, numrange, tsrange, tstzrange, daterange, geometry, geography, cube
Similarly, TypeORM supports a different set of datatype for MySQL.
TypeORM provides an extensive set of options other than type to describe the column. For example, length option refers the length of the database field and it can be specified as below −
@Column("varchar", { length: 100 })
Some of the most common column options are as follows −
name − Name of the database field / column.
length − Length of the database field / column.
nullable − Specify whether the database field / column allows null or not.
default − Default value of the database field / column.
primary − Specify whether the database field / column is primary key of the table.
unique − Specify whether the database field / column is unique
*precision** − Precision of the database field / column
scale − Scale of the database field / column
comment − Comment or description of the database field / column
TypeORM provides additional decorator, @Generated to auto generate the column values. For example, Universally Unique Identifier (UUID) is quite common to use in database to store unique value in a column. The sample code to generate UUID is as follows −
@Entity()
export class Student {
@PrimaryColumn()
id: number;
@Column()
@Generated("uuid")
uuid: string;
}
Here,
uuid is generated automatically and stored inside the database.
At least one primary column field is mandatory for any entity in database. It is classified into different types of decorators. We will discuss it one by one.
@PrimaryColumn()
@PrimaryColumn() decorator is used to create primary column for any type of data. Simple example is shown below,
import {Entity, PrimaryColumn} from "typeorm";
@Entity()
export class Student {
@PrimaryColumn()
id: number;
}
Here,
id is an integer, which doesn’t accept duplicate values, but we need to assign values.
We can assign primary column for one or more fields as well, if the situation demands.
import {Entity, PrimaryColumn} from "typeorm";
@Entity()
export class Student {
@PrimaryColumn()
id: number;
@PrimaryColumn()
email: string;
@PrimaryColumn()
phone: number;
}
@PrimaryGeneratedColumn() field is used to specify the primary column as well as to auto generate the column value in the database. It is shown below −
import {Entity, PrimaryGeneratedColumn} from "typeorm";
@Entity()
export class Student {
@PrimaryGeneratedColumn()
id: number;
}
Here,
You don’t have to assign id value; it will be generated automatically by the TypeORM in the database table.
@PrimaryGeneratedColumn also accepts an argument to specify the type of generator. One of the main use is to generate unique id based on UUID.
import {Entity, PrimaryGeneratedColumn} from "typeorm";
@Entity()
export class Student {
@PrimaryGeneratedColumn("uuid") id: string;
}
Advanced relational database supports array datatype. To support the array datatype, TypeORM provides a special column type, *simple-array" to store primitive array values. A sample code to use it is as follows −
@Entity()
export class Student {
@PrimaryGeneratedColumn()
id: number;
@Column("simple-array")
names: string[];
}
Lot of modern database engine supports JSON database. To use JSON datatype, TypeORM provides a special type, single-json. The sample code to use it is as follows −
@Entity()
export class Student {
@PrimaryGeneratedColumn()
id: number;
@Column("simple-json")
info: { firstName: string, middleName: string, lastName: string };
}
This value can be defined in index.ts as,
const stud = new Student();
stud.info = { firstName: "John", middleName: "peter", lastName: "Michael" };
TypeORM supports the following special columns
@CreateDateColumn − It is a special column to set entity’s insertion date automatically.
@UpdateDateColumn − It is used to set the entity’s update time automatically.
@VersionColumn − Set version number for entity automatically.
Entity inheritance is use to reduce duplication of entities. Consider the below entities −
@Entity()
export class Result {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
description: string;
@Column()
eligible: string
}
The code for grade.ts is as follows −
@Entity()
export class Grade {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
title: string;
@Column()
description: string;
@Column()
grading : string;
}
Here,
The above two entities have columns id, title and description. Using entity inheritance, we create one base class Details and combine the above two entities as specified below.
export abstract class Details {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
description: string;
}
@Entity()
export class Result extends Details{
@Column()
eligible: string
}
@Entity()
export class Grade extends Details{
@Column()
name : string;
@Column()
grading : string;
}
Now start your server, you could see the below response,
Now open your mysql server and move to your database, you could see the following tables,
19 Lectures
50 mins
James Coonce
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2269,
"s": 2051,
"text": "An entity is a collection of fields and associated database operations. It is used to map database table and its fields with the entities and its attributes. This chapter explains about the TypeORM entities in detail."
},
{
"code": null,
"e": 2470,
"s": 2269,
"text": "Let us create a simple Entity class in our code. Move to your project root location and go inside src folder and move to entity folder. Now, create a TypeScript file, Student.ts and enter below code −"
},
{
"code": null,
"e": 2693,
"s": 2470,
"text": "import {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\"; \n\n@Entity() \nexport class Student { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n Name: string; \n \n @Column() \n age: number; \n}"
},
{
"code": null,
"e": 2699,
"s": 2693,
"text": "Here,"
},
{
"code": null,
"e": 2782,
"s": 2699,
"text": "Entity() decorator class is used to represent that the Student class is an entity."
},
{
"code": null,
"e": 2912,
"s": 2782,
"text": "PrimaryGeneratedColumn() decorator class is used to represent that the id column is the primary key column of the Student entity."
},
{
"code": null,
"e": 3016,
"s": 2912,
"text": "Column() decorator class is used to represent other columns such as Name and Age of the Student entity."
},
{
"code": null,
"e": 3234,
"s": 3016,
"text": "Now, Entity class Student is created. TypeORM will auto generate a table corresponding to the Student entity in our database and it will be named as student. Now, move to src/index.ts file and add the following code −"
},
{
"code": null,
"e": 4086,
"s": 3234,
"text": "import \"reflect-metadata\"; \nimport {createConnection} from \"typeorm\";\nimport {Student} from \"./entity/Student\"; //import Student entity\n\ncreateConnection().then(async connection => { \n\n console.log(\"Inserting a new record into the student database...\"); \n \n //create student object const stud = new Student(); \n \n //Assign student name and age here stud.Name = \"student1\"; \n stud.age = 12; \n \n //save student object in connection await connection.manager.save(stud); console.log(\"Saved a new user with id: \" + stud.id);\n \n console.log(\"Loading users from the database...\");\n\n //Display student saved records const students = await connection.manager.find(Student); console.log(\"Loaded users: \", students);\n\n console.log(\"Here you can setup and run express/koa/any other framework.\");\n}).catch(error => console.log(error));"
},
{
"code": null,
"e": 4092,
"s": 4086,
"text": "Here,"
},
{
"code": null,
"e": 4162,
"s": 4092,
"text": "Line 1 - 3 imports the relevant classes, createConnection and Student"
},
{
"code": null,
"e": 4311,
"s": 4162,
"text": "Line 5 creates a new connection to the database using createConnection and if connection is established, it executes the code inside the then block."
},
{
"code": null,
"e": 4352,
"s": 4311,
"text": "Line 10 create new Student object, stud."
},
{
"code": null,
"e": 4416,
"s": 4352,
"text": "Line 13-14 set the attributes of our newly created stud object."
},
{
"code": null,
"e": 4515,
"s": 4416,
"text": "Line 17 saves the entity to the database using save method available in connection.manager object."
},
{
"code": null,
"e": 4627,
"s": 4515,
"text": "Line 23 fetches the student details from the database using find method available in connection.manager object."
},
{
"code": null,
"e": 4746,
"s": 4627,
"text": "We have created Student entity and create connection in index.ts. Let us start both MySql server and your application."
},
{
"code": null,
"e": 4757,
"s": 4746,
"text": "npm start\n"
},
{
"code": null,
"e": 4812,
"s": 4757,
"text": "This will return the following output on your screen −"
},
{
"code": null,
"e": 4885,
"s": 4812,
"text": "Open mysql server following student table is added inside your database."
},
{
"code": null,
"e": 5236,
"s": 4885,
"text": "As learned earlier, Entity is actually a collection of attributes. As entity object refers the database table. Its attributes / member variables refer the corresponding database table’s fields / columns. TypeORM supports all type of database fields through Column class. Let us learn the different type of column supported by TypeORM in this chapter."
},
{
"code": null,
"e": 5322,
"s": 5236,
"text": "@Column() decorator class is used to represent the column and its type in the entity."
},
{
"code": null,
"e": 5431,
"s": 5322,
"text": "For example, age attribute of the student entity and the type of the age attribute can be defined as below −"
},
{
"code": null,
"e": 5505,
"s": 5431,
"text": "@Column(\"int\") age: integer; // OR @Column({ type: \"int\" }) age: integer;"
},
{
"code": null,
"e": 5511,
"s": 5505,
"text": "Here,"
},
{
"code": null,
"e": 5624,
"s": 5511,
"text": "age is the attribute of the entity. In other word, age is a field / column in the student table in the database."
},
{
"code": null,
"e": 5682,
"s": 5624,
"text": "int represent the type of the age column in the database."
},
{
"code": null,
"e": 5918,
"s": 5682,
"text": "TypeORM supports nearly all the types available in the popular database engine. Actually, TypeORM enables different set of types for each database engine. We can use any database type supported by our database engine without any issue."
},
{
"code": null,
"e": 6008,
"s": 5918,
"text": "For example, the type supported by TypeORM for postgresql database engine is as follows −"
},
{
"code": null,
"e": 6607,
"s": 6008,
"text": "int, int2, int4, int8, smallint, integer, bigint, decimal, numeric, real, float, float4, float8, double precision, money, character varying,\n\nvarchar, character, char, text, citext, hstore, bytea, bit, varbit, bit\n\nvarying, timetz, timestamptz, timestamp, timestamp without time zone, timestamp with time zone, date, time, time without time zone, time with time zone, interval, bool, boolean, enum, point, line, lseg, box, path, polygon, circle, cidr, inet, macaddr, tsvector, tsquery, uuid, xml, json, jsonb, int4range, int8range, numrange, tsrange, tstzrange, daterange, geometry, geography, cube"
},
{
"code": null,
"e": 6674,
"s": 6607,
"text": "Similarly, TypeORM supports a different set of datatype for MySQL."
},
{
"code": null,
"e": 6861,
"s": 6674,
"text": "TypeORM provides an extensive set of options other than type to describe the column. For example, length option refers the length of the database field and it can be specified as below −"
},
{
"code": null,
"e": 6898,
"s": 6861,
"text": "@Column(\"varchar\", { length: 100 })\n"
},
{
"code": null,
"e": 6954,
"s": 6898,
"text": "Some of the most common column options are as follows −"
},
{
"code": null,
"e": 6998,
"s": 6954,
"text": "name − Name of the database field / column."
},
{
"code": null,
"e": 7046,
"s": 6998,
"text": "length − Length of the database field / column."
},
{
"code": null,
"e": 7121,
"s": 7046,
"text": "nullable − Specify whether the database field / column allows null or not."
},
{
"code": null,
"e": 7177,
"s": 7121,
"text": "default − Default value of the database field / column."
},
{
"code": null,
"e": 7260,
"s": 7177,
"text": "primary − Specify whether the database field / column is primary key of the table."
},
{
"code": null,
"e": 7323,
"s": 7260,
"text": "unique − Specify whether the database field / column is unique"
},
{
"code": null,
"e": 7379,
"s": 7323,
"text": "*precision** − Precision of the database field / column"
},
{
"code": null,
"e": 7424,
"s": 7379,
"text": "scale − Scale of the database field / column"
},
{
"code": null,
"e": 7488,
"s": 7424,
"text": "comment − Comment or description of the database field / column"
},
{
"code": null,
"e": 7743,
"s": 7488,
"text": "TypeORM provides additional decorator, @Generated to auto generate the column values. For example, Universally Unique Identifier (UUID) is quite common to use in database to store unique value in a column. The sample code to generate UUID is as follows −"
},
{
"code": null,
"e": 7877,
"s": 7743,
"text": "@Entity() \nexport class Student {\n \n @PrimaryColumn() \n id: number; \n \n @Column() \n @Generated(\"uuid\") \n uuid: string; \n}"
},
{
"code": null,
"e": 7883,
"s": 7877,
"text": "Here,"
},
{
"code": null,
"e": 7947,
"s": 7883,
"text": "uuid is generated automatically and stored inside the database."
},
{
"code": null,
"e": 8106,
"s": 7947,
"text": "At least one primary column field is mandatory for any entity in database. It is classified into different types of decorators. We will discuss it one by one."
},
{
"code": null,
"e": 8123,
"s": 8106,
"text": "@PrimaryColumn()"
},
{
"code": null,
"e": 8237,
"s": 8123,
"text": "@PrimaryColumn() decorator is used to create primary column for any type of data. Simple example is shown below, "
},
{
"code": null,
"e": 8364,
"s": 8237,
"text": "import {Entity, PrimaryColumn} from \"typeorm\"; \n\n@Entity() \nexport class Student { \n@PrimaryColumn() \n id: number; \n}"
},
{
"code": null,
"e": 8370,
"s": 8364,
"text": "Here,"
},
{
"code": null,
"e": 8457,
"s": 8370,
"text": "id is an integer, which doesn’t accept duplicate values, but we need to assign values."
},
{
"code": null,
"e": 8544,
"s": 8457,
"text": "We can assign primary column for one or more fields as well, if the situation demands."
},
{
"code": null,
"e": 8759,
"s": 8544,
"text": "import {Entity, PrimaryColumn} from \"typeorm\"; \n\n@Entity() \nexport class Student { \n \n @PrimaryColumn() \n id: number; \n \n @PrimaryColumn() \n email: string; \n \n @PrimaryColumn() \n phone: number; \n}"
},
{
"code": null,
"e": 8911,
"s": 8759,
"text": "@PrimaryGeneratedColumn() field is used to specify the primary column as well as to auto generate the column value in the database. It is shown below −"
},
{
"code": null,
"e": 9051,
"s": 8911,
"text": "import {Entity, PrimaryGeneratedColumn} from \"typeorm\"; \n\n@Entity() \nexport class Student {\n\n @PrimaryGeneratedColumn() \n id: number;\n}"
},
{
"code": null,
"e": 9057,
"s": 9051,
"text": "Here,"
},
{
"code": null,
"e": 9165,
"s": 9057,
"text": "You don’t have to assign id value; it will be generated automatically by the TypeORM in the database table."
},
{
"code": null,
"e": 9308,
"s": 9165,
"text": "@PrimaryGeneratedColumn also accepts an argument to specify the type of generator. One of the main use is to generate unique id based on UUID."
},
{
"code": null,
"e": 9451,
"s": 9308,
"text": "import {Entity, PrimaryGeneratedColumn} from \"typeorm\";\n\n@Entity() \nexport class Student { \n @PrimaryGeneratedColumn(\"uuid\") id: string; \n}"
},
{
"code": null,
"e": 9664,
"s": 9451,
"text": "Advanced relational database supports array datatype. To support the array datatype, TypeORM provides a special column type, *simple-array\" to store primitive array values. A sample code to use it is as follows −"
},
{
"code": null,
"e": 9800,
"s": 9664,
"text": "@Entity() \nexport class Student { \n \n @PrimaryGeneratedColumn() \n id: number;\n\n @Column(\"simple-array\") \n names: string[]; \n}"
},
{
"code": null,
"e": 9964,
"s": 9800,
"text": "Lot of modern database engine supports JSON database. To use JSON datatype, TypeORM provides a special type, single-json. The sample code to use it is as follows −"
},
{
"code": null,
"e": 10149,
"s": 9964,
"text": "@Entity() \nexport class Student { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column(\"simple-json\")\n info: { firstName: string, middleName: string, lastName: string }; \n}"
},
{
"code": null,
"e": 10191,
"s": 10149,
"text": "This value can be defined in index.ts as,"
},
{
"code": null,
"e": 10297,
"s": 10191,
"text": "const stud = new Student(); \nstud.info = { firstName: \"John\", middleName: \"peter\", lastName: \"Michael\" };"
},
{
"code": null,
"e": 10344,
"s": 10297,
"text": "TypeORM supports the following special columns"
},
{
"code": null,
"e": 10433,
"s": 10344,
"text": "@CreateDateColumn − It is a special column to set entity’s insertion date automatically."
},
{
"code": null,
"e": 10511,
"s": 10433,
"text": "@UpdateDateColumn − It is used to set the entity’s update time automatically."
},
{
"code": null,
"e": 10573,
"s": 10511,
"text": "@VersionColumn − Set version number for entity automatically."
},
{
"code": null,
"e": 10664,
"s": 10573,
"text": "Entity inheritance is use to reduce duplication of entities. Consider the below entities −"
},
{
"code": null,
"e": 10869,
"s": 10664,
"text": "@Entity() \nexport class Result { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n title: string; \n \n @Column() \n description: string; \n \n @Column() \n eligible: string \n}"
},
{
"code": null,
"e": 10907,
"s": 10869,
"text": "The code for grade.ts is as follows −"
},
{
"code": null,
"e": 11151,
"s": 10907,
"text": "@Entity() \nexport class Grade {\n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n name: string; \n \n @Column() \n title: string; \n \n @Column() \n description: string;\n \n \n \n @Column() \n grading : string; \n}"
},
{
"code": null,
"e": 11157,
"s": 11151,
"text": "Here,"
},
{
"code": null,
"e": 11334,
"s": 11157,
"text": "The above two entities have columns id, title and description. Using entity inheritance, we create one base class Details and combine the above two entities as specified below."
},
{
"code": null,
"e": 11711,
"s": 11334,
"text": "export abstract class Details {\n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n title: string; \n \n @Column() \n description: string; \n} \n@Entity() \nexport class Result extends Details{ \n\n @Column() \n eligible: string \n} \n@Entity() \nexport class Grade extends Details{ \n\n @Column() \n name : string; \n \n @Column() \n grading : string; \n}"
},
{
"code": null,
"e": 11768,
"s": 11711,
"text": "Now start your server, you could see the below response,"
},
{
"code": null,
"e": 11858,
"s": 11768,
"text": "Now open your mysql server and move to your database, you could see the following tables,"
},
{
"code": null,
"e": 11890,
"s": 11858,
"text": "\n 19 Lectures \n 50 mins\n"
},
{
"code": null,
"e": 11904,
"s": 11890,
"text": " James Coonce"
},
{
"code": null,
"e": 11911,
"s": 11904,
"text": " Print"
},
{
"code": null,
"e": 11922,
"s": 11911,
"text": " Add Notes"
}
] |
fg command in Linux with examples - GeeksforGeeks
|
15 May, 2019
fg command in linux used to put a background job in foreground.
Syntax:
fg [job_spec]
job_spec may be:
%n : Refer to job number n.%str : Refer to a job which was started by a command beginning with str.%?str : Refer to a job which was started by a command containing str.%% or %+ : Refer to the current job. fg and bg will operate on this job if no job_spec is given.%- : Refer to the previous job.
Options for fg command :
fg [JOB_SPEC] : This command is used to put the mentioned job running inbackground to foreground.“sleep 500” is a command which is used to create a dummy job which runs for 500 seconds.
fg –help : It displays help information.
linux-command
Linux-system-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
'crontab' in Linux with Examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
|
[
{
"code": null,
"e": 24155,
"s": 24127,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 24219,
"s": 24155,
"text": "fg command in linux used to put a background job in foreground."
},
{
"code": null,
"e": 24227,
"s": 24219,
"text": "Syntax:"
},
{
"code": null,
"e": 24241,
"s": 24227,
"text": "fg [job_spec]"
},
{
"code": null,
"e": 24258,
"s": 24241,
"text": "job_spec may be:"
},
{
"code": null,
"e": 24554,
"s": 24258,
"text": "%n : Refer to job number n.%str : Refer to a job which was started by a command beginning with str.%?str : Refer to a job which was started by a command containing str.%% or %+ : Refer to the current job. fg and bg will operate on this job if no job_spec is given.%- : Refer to the previous job."
},
{
"code": null,
"e": 24579,
"s": 24554,
"text": "Options for fg command :"
},
{
"code": null,
"e": 24765,
"s": 24579,
"text": "fg [JOB_SPEC] : This command is used to put the mentioned job running inbackground to foreground.“sleep 500” is a command which is used to create a dummy job which runs for 500 seconds."
},
{
"code": null,
"e": 24806,
"s": 24765,
"text": "fg –help : It displays help information."
},
{
"code": null,
"e": 24820,
"s": 24806,
"text": "linux-command"
},
{
"code": null,
"e": 24842,
"s": 24820,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 24849,
"s": 24842,
"text": "Picked"
},
{
"code": null,
"e": 24873,
"s": 24849,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 24884,
"s": 24873,
"text": "Linux-Unix"
},
{
"code": null,
"e": 24903,
"s": 24884,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25001,
"s": 24903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25010,
"s": 25001,
"text": "Comments"
},
{
"code": null,
"e": 25023,
"s": 25010,
"text": "Old Comments"
},
{
"code": null,
"e": 25058,
"s": 25023,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 25094,
"s": 25058,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 25132,
"s": 25094,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 25168,
"s": 25132,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 25206,
"s": 25168,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 25241,
"s": 25206,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 25274,
"s": 25241,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 25311,
"s": 25274,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 25347,
"s": 25311,
"text": "echo command in Linux with Examples"
}
] |
Find shortest safe route in a path with landmines - GeeksforGeeks
|
05 Aug, 2021
Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left, right, above and below) as they are also unsafe. We are allowed to move to only adjacent cells which are not landmines. i.e. the route cannot contains any diagonal moves.
Examples:
Input:
A 12 x 10 matrix with landmines marked as 0
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 0 1 1 1 1 1 1 1 1 ]
[ 1 1 1 0 1 1 1 1 1 1 ]
[ 1 1 1 1 0 1 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 1 1 0 1 1 1 1 ]
[ 1 0 1 1 1 1 1 1 0 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 0 1 1 1 1 0 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 0 1 1 1 1 1 1 ]
Output:
Length of shortest safe route is 13 (Highlighted in Bold)
The idea is to use Backtracking. We first mark all adjacent cells of the landmines as unsafe. Then for each safe cell of first column of the matrix, we move forward in all allowed directions and recursively checks if they leads to the destination or not. If destination is found, we update the value of shortest path else if none of the above solutions work we return false from our function.
Below is the implementation of above idea –
C++
Java
Python3
C#
Javascript
// C++ program to find shortest safe Route in// the matrix with landmines#include <bits/stdc++.h>using namespace std;#define R 12#define C 10 // These arrays are used to get row and column// numbers of 4 neighbours of a given cellint rowNum[] = { -1, 0, 0, 1 };int colNum[] = { 0, -1, 1, 0 }; // A function to check if a given cell (x, y)// can be visited or notbool isSafe(int mat[R][C], int visited[R][C], int x, int y){ if (mat[x][y] == 0 || visited[x][y]) return false; return true;} // A function to check if a given cell (x, y) is// a valid cell or notbool isValid(int x, int y){ if (x < R && y < C && x >= 0 && y >= 0) return true; return false;} // A function to mark all adjacent cells of// landmines as unsafe. Landmines are shown with// number 0void markUnsafeCells(int mat[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // if a landmines is found if (mat[i][j] == 0) { // mark all adjacent cells for (int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } } // mark all found adjacent cells as unsafe for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } // Uncomment below lines to print the path /*for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { cout << std::setw(3) << mat[i][j]; } cout << endl; }*/} // Function to find shortest safe Route in the// matrix with landmines// mat[][] - binary input matrix with safe cells marked as 1// visited[][] - store info about cells already visited in// current route// (i, j) are coordinates of the current cell// min_dist --> stores minimum cost of shortest path so far// dist --> stores current path costvoid findShortestPathUtil(int mat[R][C], int visited[R][C], int i, int j, int &min_dist, int dist){ // if destination is reached if (j == C-1) { // update shortest path found so far min_dist = min(dist, min_dist); return; } // if current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i][j] = 1; // Recurse for all safe adjacent neighbours for (int k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], min_dist, dist + 1); } } // Backtrack visited[i][j] = 0;} // A wrapper function over findshortestPathUtil()void findShortestPath(int mat[R][C]){ // stores minimum cost of shortest path so far int min_dist = INT_MAX; // create a boolean matrix to store info about // cells already visited in current route int visited[R][C]; // mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // start from first column and take minimum for (int i = 0; i < R; i++) { // if path is safe from current cell if (mat[i][0] == 1) { // initialize visited to false memset(visited, 0, sizeof visited); // find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, min_dist, 0); // if min distance is already found if(min_dist == C - 1) break; } } // if destination can be reached if (min_dist != INT_MAX) cout << "Length of shortest safe route is " << min_dist; else // if the destination is not reachable cout << "Destination not reachable from " << "given source";} // Driver codeint main(){ // input matrix with landmines shown with number 0 int mat[R][C] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // find shortest path findShortestPath(mat); return 0;}
// Java program to find shortest safe Route// in the matrix with landminesimport java.util.Arrays; class GFG{ static final int R = 12;static final int C = 10; // These arrays are used to get row and column// numbers of 4 neighbours of a given cellstatic int rowNum[] = { -1, 0, 0, 1 };static int colNum[] = { 0, -1, 1, 0 }; static int min_dist; // A function to check if a given cell (x, y)// can be visited or notstatic boolean isSafe(int[][] mat, boolean[][] visited, int x, int y){ if (mat[x][y] == 0 || visited[x][y]) return false; return true;} // A function to check if a given cell (x, y) is// a valid cell or notstatic boolean isValid(int x, int y){ if (x < R && y < C && x >= 0 && y >= 0) return true; return false;} // A function to mark all adjacent cells of// landmines as unsafe. Landmines are shown with// number 0static void markUnsafeCells(int[][] mat){ for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // If a landmines is found if (mat[i][j] == 0) { // Mark all adjacent cells for(int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } } // Mark all found adjacent cells as unsafe for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } // Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } */} // Function to find shortest safe Route in the// matrix with landmines// mat[][] - binary input matrix with safe cells marked as 1// visited[][] - store info about cells already visited in// current route// (i, j) are coordinates of the current cell// min_dist --> stores minimum cost of shortest path so far// dist --> stores current path coststatic void findShortestPathUtil(int[][] mat, boolean[][] visited, int i, int j, int dist){ // If destination is reached if (j == C - 1) { // Update shortest path found so far min_dist = Math.min(dist, min_dist); return; } // If current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i][j] = true; // Recurse for all safe adjacent neighbours for(int k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1); } } // Backtrack visited[i][j] = false;} // A wrapper function over findshortestPathUtil()static void findShortestPath(int[][] mat){ // Stores minimum cost of shortest path so far min_dist = Integer.MAX_VALUE; // Create a boolean matrix to store info about // cells already visited in current route boolean[][] visited = new boolean[R][C]; // Mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // Start from first column and take minimum for(int i = 0; i < R; i++) { // If path is safe from current cell if (mat[i][0] == 1) { // Initialize visited to false for(int k = 0; k < R; k++) { Arrays.fill(visited[k], false); } // Find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0); // If min distance is already found if (min_dist == C - 1) break; } } // If destination can be reached if (min_dist != Integer.MAX_VALUE) System.out.println("Length of shortest " + "safe route is " + min_dist); else // If the destination is not reachable System.out.println("Destination not " + "reachable from given source");} // Driver codepublic static void main(String[] args){ // Input matrix with landmines shown with number 0 int[][] mat = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // Find shortest path findShortestPath(mat);}} // This code is contributed by sanjeev2552
# Python3 program to find shortest safe Route# in the matrix with landminesimport sys R = 12C = 10 # These arrays are used to get row and column# numbers of 4 neighbours of a given cellrowNum = [ -1, 0, 0, 1 ]colNum = [ 0, -1, 1, 0 ] min_dist = sys.maxsize # A function to check if a given cell (x, y)# can be visited or notdef isSafe(mat, visited, x, y): if (mat[x][y] == 0 or visited[x][y]): return False return True # A function to check if a given cell (x, y) is# a valid cell or notdef isValid(x, y): if (x < R and y < C and x >= 0 and y >= 0): return True return False # A function to mark all adjacent cells of# landmines as unsafe. Landmines are shown with# number 0def markUnsafeCells(mat): for i in range(R): for j in range(C): # If a landmines is found if (mat[i][j] == 0): # Mark all adjacent cells for k in range(4): if (isValid(i + rowNum[k], j + colNum[k])): mat[i + rowNum[k]][j + colNum[k]] = -1 # Mark all found adjacent cells as unsafe for i in range(R): for j in range(C): if (mat[i][j] == -1): mat[i][j] = 0 """ Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } *""" # Function to find shortest safe Route in the# matrix with landmines# mat[][] - binary input matrix with safe cells marked as 1# visited[][] - store info about cells already visited in# current route# (i, j) are coordinates of the current cell# min_dist --> stores minimum cost of shortest path so far# dist --> stores current path costdef findShortestPathUtil(mat, visited, i, j, dist): global min_dist # If destination is reached if (j == C - 1): # Update shortest path found so far min_dist = min(dist, min_dist) return # If current path cost exceeds minimum so far if (dist > min_dist): return # include (i, j) in current path visited[i][j] = True # Recurse for all safe adjacent neighbours for k in range(4): if (isValid(i + rowNum[k], j + colNum[k]) and isSafe(mat, visited, i + rowNum[k], j + colNum[k])): findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1) # Backtrack visited[i][j] = False # A wrapper function over findshortestPathUtil()def findShortestPath(mat): global min_dist # Stores minimum cost of shortest path so far min_dist = sys.maxsize # Create a boolean matrix to store info about # cells already visited in current route visited = [[False for i in range(C)] for j in range(R)] # Mark adjacent cells of landmines as unsafe markUnsafeCells(mat) # Start from first column and take minimum for i in range(R): # If path is safe from current cell if (mat[i][0] == 1): # Find shortest route from (i, 0) to any # cell of last column (x, C - 1) where # 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0) # If min distance is already found if (min_dist == C - 1): break # If destination can be reached if (min_dist != sys.maxsize): print("Length of shortest safe route is", min_dist) else: # If the destination is not reachable print("Destination not reachable from given source") mat = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ] # Find shortest pathfindShortestPath(mat) # This code is contributed by mukesh07.
// C# program to find shortest safe Route// in the matrix with landminesusing System;using System.Collections.Generic;class GFG { static int R = 12; static int C = 10; // These arrays are used to get row and column // numbers of 4 neighbours of a given cell static int[] rowNum = { -1, 0, 0, 1 }; static int[] colNum = { 0, -1, 1, 0 }; static int min_dist; // A function to check if a given cell (x, y) // can be visited or not static bool isSafe(int[,] mat, bool[,] visited, int x, int y) { if (mat[x,y] == 0 || visited[x,y]) return false; return true; } // A function to check if a given cell (x, y) is // a valid cell or not static bool isValid(int x, int y) { if (x < R && y < C && x >= 0 && y >= 0) return true; return false; } // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 static void markUnsafeCells(int[,] mat) { for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // If a landmines is found if (mat[i,j] == 0) { // Mark all adjacent cells for(int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k],j + colNum[k]] = -1; } } } // Mark all found adjacent cells as unsafe for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { if (mat[i,j] == -1) mat[i,j] = 0; } } // Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } */ } // Function to find shortest safe Route in the // matrix with landmines // mat[][] - binary input matrix with safe cells marked as 1 // visited[][] - store info about cells already visited in // current route // (i, j) are coordinates of the current cell // min_dist --> stores minimum cost of shortest path so far // dist --> stores current path cost static void findShortestPathUtil(int[,] mat, bool[,] visited, int i, int j, int dist) { // If destination is reached if (j == C - 1) { // Update shortest path found so far min_dist = Math.Min(dist, min_dist); return; } // If current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i,j] = true; // Recurse for all safe adjacent neighbours for(int k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1); } } // Backtrack visited[i,j] = false; } // A wrapper function over findshortestPathUtil() static void findShortestPath(int[,] mat) { // Stores minimum cost of shortest path so far min_dist = Int32.MaxValue; // Create a boolean matrix to store info about // cells already visited in current route bool[,] visited = new bool[R,C]; // Mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // Start from first column and take minimum for(int i = 0; i < R; i++) { // If path is safe from current cell if (mat[i,0] == 1) { // Find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0); // If min distance is already found if (min_dist == C - 1) break; } } // If destination can be reached if (min_dist != Int32.MaxValue) Console.WriteLine("Length of shortest " + "safe route is " + min_dist); else // If the destination is not reachable Console.WriteLine("Destination not " + "reachable from given source"); } static void Main() { // Input matrix with landmines shown with number 0 int[,] mat = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // Find shortest path findShortestPath(mat); }} // This code is contributed by rameshtravel07.
<script> // Javascript program to find shortest safe Route // in the matrix with landmines let R = 12; let C = 10; // These arrays are used to get row and column // numbers of 4 neighbours of a given cell let rowNum = [ -1, 0, 0, 1 ]; let colNum = [ 0, -1, 1, 0 ]; let min_dist; // A function to check if a given cell (x, y) // can be visited or not function isSafe(mat, visited, x, y) { if (mat[x][y] == 0 || visited[x][y]) return false; return true; } // A function to check if a given cell (x, y) is // a valid cell or not function isValid(x, y) { if (x < R && y < C && x >= 0 && y >= 0) return true; return false; } // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 function markUnsafeCells(mat) { for(let i = 0; i < R; i++) { for(let j = 0; j < C; j++) { // If a landmines is found if (mat[i][j] == 0) { // Mark all adjacent cells for(let k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } } // Mark all found adjacent cells as unsafe for(let i = 0; i < R; i++) { for(let j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } // Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } */ } // Function to find shortest safe Route in the // matrix with landmines // mat[][] - binary input matrix with safe cells marked as 1 // visited[][] - store info about cells already visited in // current route // (i, j) are coordinates of the current cell // min_dist --> stores minimum cost of shortest path so far // dist --> stores current path cost function findShortestPathUtil(mat, visited, i, j, dist) { // If destination is reached if (j == C - 1) { // Update shortest path found so far min_dist = Math.min(dist, min_dist); return; } // If current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i][j] = true; // Recurse for all safe adjacent neighbours for(let k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1); } } // Backtrack visited[i][j] = false; } // A wrapper function over findshortestPathUtil() function findShortestPath(mat) { // Stores minimum cost of shortest path so far min_dist = Number.MAX_VALUE; // Create a boolean matrix to store info about // cells already visited in current route let visited = new Array(R); for(let i = 0; i < R; i++) { visited[i] = new Array(C); for(let j = 0; j < C; j++) { visited[i][j] = false; } } // Mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // Start from first column and take minimum for(let i = 0; i < R; i++) { // If path is safe from current cell if (mat[i][0] == 1) { // Find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0); // If min distance is already found if (min_dist == C - 1) break; } } // If destination can be reached if (min_dist != Number.MAX_VALUE) document.write("Length of shortest " + "safe route is " + min_dist + "</br>"); else // If the destination is not reachable document.write("Destination not " + "reachable from given source" + "</br>"); } // Input matrix with landmines shown with number 0 let mat = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ]; // Find shortest path findShortestPath(mat); // This code is contributed by decode2207.</script>
Output:
Length of shortest safe route is 13
Another method: It can be solved in polynomial time with the help of Breadth First Search. Enqueue the cells with 1 value in the queue with the distance as 0. As the BFS proceeds, shortest path to each cell from the first column is computed. Finally for the reachable cells in the last column, output the minimum distance.
The implementation in C++ is as follows:
C++
// C++ program to find shortest safe Route in// the matrix with landmines#include <bits/stdc++.h>using namespace std; #define R 12#define C 10 struct Key{ int x,y; Key(int i,int j){ x=i;y=j;};}; // These arrays are used to get row and column// numbers of 4 neighbours of a given cellint rowNum[] = { -1, 0, 0, 1 };int colNum[] = { 0, -1, 1, 0 }; // A function to check if a given cell (x, y) is// a valid cell or notbool isValid(int x, int y){ if (x < R && y < C && x >= 0 && y >= 0) return true; return false;} // A function to mark all adjacent cells of// landmines as unsafe. Landmines are shown with// number 0void findShortestPath(int mat[R][C]){ int i,j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { // if a landmines is found if (mat[i][j] == 0) { // mark all adjacent cells for (int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } }// mark all found adjacent cells as unsafe for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } int dist[R][C]; for(i=0;i<R;i++){ for(j=0;j<C;j++) dist[i][j] = -1; } queue<Key> q; for(i=0;i<R;i++){ if(mat[i][0] == 1){ q.push(Key(i,0)); dist[i][0] = 0; } } while(!q.empty()){ Key k = q.front(); q.pop(); int d = dist[k.x][k.y]; int x = k.x; int y = k.y; for (int k = 0; k < 4; k++) { int xp = x + rowNum[k]; int yp = y + colNum[k]; if(isValid(xp,yp) && dist[xp][yp] == -1 && mat[xp][yp] == 1){ dist[xp][yp] = d+1; q.push(Key(xp,yp)); } } } // stores minimum cost of shortest path so far int ans = INT_MAX; // start from first column and take minimum for(i=0;i<R;i++){ if(mat[i][C-1] == 1 && dist[i][C-1] != -1){ ans = min(ans,dist[i][C-1]); } } // if destination can be reached if(ans == INT_MAX) cout << "NOT POSSIBLE\n"; else// if the destination is not reachable cout << "Length of shortest safe route is " << ans << endl;} // Driver codeint main(){ // input matrix with landmines shown with number 0 int mat[R][C] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // find shortest path findShortestPath(mat);}
Output:
Length of shortest safe route is 13
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.
geekoverflow
sanjeev2552
ruhelaa48
varshagumber28
decode2207
rameshtravel07
mukesh07
Shortest Path
Backtracking
Matrix
Matrix
Shortest Path
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Backtracking | Introduction
m Coloring Problem | Backtracking-5
Print all paths from a given source to a destination
Subset Sum | Backtracking-4
Backtracking to find all subsets
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 25082,
"s": 25054,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 25554,
"s": 25082,
"text": "Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left, right, above and below) as they are also unsafe. We are allowed to move to only adjacent cells which are not landmines. i.e. the route cannot contains any diagonal moves."
},
{
"code": null,
"e": 25566,
"s": 25554,
"text": "Examples: "
},
{
"code": null,
"e": 26084,
"s": 25566,
"text": "Input: \nA 12 x 10 matrix with landmines marked as 0\n\n[ 1 1 1 1 1 1 1 1 1 1 ]\n[ 1 0 1 1 1 1 1 1 1 1 ]\n[ 1 1 1 0 1 1 1 1 1 1 ]\n[ 1 1 1 1 0 1 1 1 1 1 ]\n[ 1 1 1 1 1 1 1 1 1 1 ]\n[ 1 1 1 1 1 0 1 1 1 1 ]\n[ 1 0 1 1 1 1 1 1 0 1 ]\n[ 1 1 1 1 1 1 1 1 1 1 ]\n[ 1 1 1 1 1 1 1 1 1 1 ]\n[ 0 1 1 1 1 0 1 1 1 1 ]\n[ 1 1 1 1 1 1 1 1 1 1 ]\n[ 1 1 1 0 1 1 1 1 1 1 ]\n\nOutput: \nLength of shortest safe route is 13 (Highlighted in Bold)"
},
{
"code": null,
"e": 26477,
"s": 26084,
"text": "The idea is to use Backtracking. We first mark all adjacent cells of the landmines as unsafe. Then for each safe cell of first column of the matrix, we move forward in all allowed directions and recursively checks if they leads to the destination or not. If destination is found, we update the value of shortest path else if none of the above solutions work we return false from our function."
},
{
"code": null,
"e": 26521,
"s": 26477,
"text": "Below is the implementation of above idea –"
},
{
"code": null,
"e": 26525,
"s": 26521,
"text": "C++"
},
{
"code": null,
"e": 26530,
"s": 26525,
"text": "Java"
},
{
"code": null,
"e": 26538,
"s": 26530,
"text": "Python3"
},
{
"code": null,
"e": 26541,
"s": 26538,
"text": "C#"
},
{
"code": null,
"e": 26552,
"s": 26541,
"text": "Javascript"
},
{
"code": "// C++ program to find shortest safe Route in// the matrix with landmines#include <bits/stdc++.h>using namespace std;#define R 12#define C 10 // These arrays are used to get row and column// numbers of 4 neighbours of a given cellint rowNum[] = { -1, 0, 0, 1 };int colNum[] = { 0, -1, 1, 0 }; // A function to check if a given cell (x, y)// can be visited or notbool isSafe(int mat[R][C], int visited[R][C], int x, int y){ if (mat[x][y] == 0 || visited[x][y]) return false; return true;} // A function to check if a given cell (x, y) is// a valid cell or notbool isValid(int x, int y){ if (x < R && y < C && x >= 0 && y >= 0) return true; return false;} // A function to mark all adjacent cells of// landmines as unsafe. Landmines are shown with// number 0void markUnsafeCells(int mat[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // if a landmines is found if (mat[i][j] == 0) { // mark all adjacent cells for (int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } } // mark all found adjacent cells as unsafe for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } // Uncomment below lines to print the path /*for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { cout << std::setw(3) << mat[i][j]; } cout << endl; }*/} // Function to find shortest safe Route in the// matrix with landmines// mat[][] - binary input matrix with safe cells marked as 1// visited[][] - store info about cells already visited in// current route// (i, j) are coordinates of the current cell// min_dist --> stores minimum cost of shortest path so far// dist --> stores current path costvoid findShortestPathUtil(int mat[R][C], int visited[R][C], int i, int j, int &min_dist, int dist){ // if destination is reached if (j == C-1) { // update shortest path found so far min_dist = min(dist, min_dist); return; } // if current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i][j] = 1; // Recurse for all safe adjacent neighbours for (int k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], min_dist, dist + 1); } } // Backtrack visited[i][j] = 0;} // A wrapper function over findshortestPathUtil()void findShortestPath(int mat[R][C]){ // stores minimum cost of shortest path so far int min_dist = INT_MAX; // create a boolean matrix to store info about // cells already visited in current route int visited[R][C]; // mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // start from first column and take minimum for (int i = 0; i < R; i++) { // if path is safe from current cell if (mat[i][0] == 1) { // initialize visited to false memset(visited, 0, sizeof visited); // find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, min_dist, 0); // if min distance is already found if(min_dist == C - 1) break; } } // if destination can be reached if (min_dist != INT_MAX) cout << \"Length of shortest safe route is \" << min_dist; else // if the destination is not reachable cout << \"Destination not reachable from \" << \"given source\";} // Driver codeint main(){ // input matrix with landmines shown with number 0 int mat[R][C] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // find shortest path findShortestPath(mat); return 0;}",
"e": 31241,
"s": 26552,
"text": null
},
{
"code": "// Java program to find shortest safe Route// in the matrix with landminesimport java.util.Arrays; class GFG{ static final int R = 12;static final int C = 10; // These arrays are used to get row and column// numbers of 4 neighbours of a given cellstatic int rowNum[] = { -1, 0, 0, 1 };static int colNum[] = { 0, -1, 1, 0 }; static int min_dist; // A function to check if a given cell (x, y)// can be visited or notstatic boolean isSafe(int[][] mat, boolean[][] visited, int x, int y){ if (mat[x][y] == 0 || visited[x][y]) return false; return true;} // A function to check if a given cell (x, y) is// a valid cell or notstatic boolean isValid(int x, int y){ if (x < R && y < C && x >= 0 && y >= 0) return true; return false;} // A function to mark all adjacent cells of// landmines as unsafe. Landmines are shown with// number 0static void markUnsafeCells(int[][] mat){ for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // If a landmines is found if (mat[i][j] == 0) { // Mark all adjacent cells for(int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } } // Mark all found adjacent cells as unsafe for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } // Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } */} // Function to find shortest safe Route in the// matrix with landmines// mat[][] - binary input matrix with safe cells marked as 1// visited[][] - store info about cells already visited in// current route// (i, j) are coordinates of the current cell// min_dist --> stores minimum cost of shortest path so far// dist --> stores current path coststatic void findShortestPathUtil(int[][] mat, boolean[][] visited, int i, int j, int dist){ // If destination is reached if (j == C - 1) { // Update shortest path found so far min_dist = Math.min(dist, min_dist); return; } // If current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i][j] = true; // Recurse for all safe adjacent neighbours for(int k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1); } } // Backtrack visited[i][j] = false;} // A wrapper function over findshortestPathUtil()static void findShortestPath(int[][] mat){ // Stores minimum cost of shortest path so far min_dist = Integer.MAX_VALUE; // Create a boolean matrix to store info about // cells already visited in current route boolean[][] visited = new boolean[R][C]; // Mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // Start from first column and take minimum for(int i = 0; i < R; i++) { // If path is safe from current cell if (mat[i][0] == 1) { // Initialize visited to false for(int k = 0; k < R; k++) { Arrays.fill(visited[k], false); } // Find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0); // If min distance is already found if (min_dist == C - 1) break; } } // If destination can be reached if (min_dist != Integer.MAX_VALUE) System.out.println(\"Length of shortest \" + \"safe route is \" + min_dist); else // If the destination is not reachable System.out.println(\"Destination not \" + \"reachable from given source\");} // Driver codepublic static void main(String[] args){ // Input matrix with landmines shown with number 0 int[][] mat = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // Find shortest path findShortestPath(mat);}} // This code is contributed by sanjeev2552",
"e": 36341,
"s": 31241,
"text": null
},
{
"code": "# Python3 program to find shortest safe Route# in the matrix with landminesimport sys R = 12C = 10 # These arrays are used to get row and column# numbers of 4 neighbours of a given cellrowNum = [ -1, 0, 0, 1 ]colNum = [ 0, -1, 1, 0 ] min_dist = sys.maxsize # A function to check if a given cell (x, y)# can be visited or notdef isSafe(mat, visited, x, y): if (mat[x][y] == 0 or visited[x][y]): return False return True # A function to check if a given cell (x, y) is# a valid cell or notdef isValid(x, y): if (x < R and y < C and x >= 0 and y >= 0): return True return False # A function to mark all adjacent cells of# landmines as unsafe. Landmines are shown with# number 0def markUnsafeCells(mat): for i in range(R): for j in range(C): # If a landmines is found if (mat[i][j] == 0): # Mark all adjacent cells for k in range(4): if (isValid(i + rowNum[k], j + colNum[k])): mat[i + rowNum[k]][j + colNum[k]] = -1 # Mark all found adjacent cells as unsafe for i in range(R): for j in range(C): if (mat[i][j] == -1): mat[i][j] = 0 \"\"\" Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } *\"\"\" # Function to find shortest safe Route in the# matrix with landmines# mat[][] - binary input matrix with safe cells marked as 1# visited[][] - store info about cells already visited in# current route# (i, j) are coordinates of the current cell# min_dist --> stores minimum cost of shortest path so far# dist --> stores current path costdef findShortestPathUtil(mat, visited, i, j, dist): global min_dist # If destination is reached if (j == C - 1): # Update shortest path found so far min_dist = min(dist, min_dist) return # If current path cost exceeds minimum so far if (dist > min_dist): return # include (i, j) in current path visited[i][j] = True # Recurse for all safe adjacent neighbours for k in range(4): if (isValid(i + rowNum[k], j + colNum[k]) and isSafe(mat, visited, i + rowNum[k], j + colNum[k])): findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1) # Backtrack visited[i][j] = False # A wrapper function over findshortestPathUtil()def findShortestPath(mat): global min_dist # Stores minimum cost of shortest path so far min_dist = sys.maxsize # Create a boolean matrix to store info about # cells already visited in current route visited = [[False for i in range(C)] for j in range(R)] # Mark adjacent cells of landmines as unsafe markUnsafeCells(mat) # Start from first column and take minimum for i in range(R): # If path is safe from current cell if (mat[i][0] == 1): # Find shortest route from (i, 0) to any # cell of last column (x, C - 1) where # 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0) # If min distance is already found if (min_dist == C - 1): break # If destination can be reached if (min_dist != sys.maxsize): print(\"Length of shortest safe route is\", min_dist) else: # If the destination is not reachable print(\"Destination not reachable from given source\") mat = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ] # Find shortest pathfindShortestPath(mat) # This code is contributed by mukesh07.",
"e": 40410,
"s": 36341,
"text": null
},
{
"code": "// C# program to find shortest safe Route// in the matrix with landminesusing System;using System.Collections.Generic;class GFG { static int R = 12; static int C = 10; // These arrays are used to get row and column // numbers of 4 neighbours of a given cell static int[] rowNum = { -1, 0, 0, 1 }; static int[] colNum = { 0, -1, 1, 0 }; static int min_dist; // A function to check if a given cell (x, y) // can be visited or not static bool isSafe(int[,] mat, bool[,] visited, int x, int y) { if (mat[x,y] == 0 || visited[x,y]) return false; return true; } // A function to check if a given cell (x, y) is // a valid cell or not static bool isValid(int x, int y) { if (x < R && y < C && x >= 0 && y >= 0) return true; return false; } // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 static void markUnsafeCells(int[,] mat) { for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // If a landmines is found if (mat[i,j] == 0) { // Mark all adjacent cells for(int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k],j + colNum[k]] = -1; } } } // Mark all found adjacent cells as unsafe for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { if (mat[i,j] == -1) mat[i,j] = 0; } } // Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } */ } // Function to find shortest safe Route in the // matrix with landmines // mat[][] - binary input matrix with safe cells marked as 1 // visited[][] - store info about cells already visited in // current route // (i, j) are coordinates of the current cell // min_dist --> stores minimum cost of shortest path so far // dist --> stores current path cost static void findShortestPathUtil(int[,] mat, bool[,] visited, int i, int j, int dist) { // If destination is reached if (j == C - 1) { // Update shortest path found so far min_dist = Math.Min(dist, min_dist); return; } // If current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i,j] = true; // Recurse for all safe adjacent neighbours for(int k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1); } } // Backtrack visited[i,j] = false; } // A wrapper function over findshortestPathUtil() static void findShortestPath(int[,] mat) { // Stores minimum cost of shortest path so far min_dist = Int32.MaxValue; // Create a boolean matrix to store info about // cells already visited in current route bool[,] visited = new bool[R,C]; // Mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // Start from first column and take minimum for(int i = 0; i < R; i++) { // If path is safe from current cell if (mat[i,0] == 1) { // Find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0); // If min distance is already found if (min_dist == C - 1) break; } } // If destination can be reached if (min_dist != Int32.MaxValue) Console.WriteLine(\"Length of shortest \" + \"safe route is \" + min_dist); else // If the destination is not reachable Console.WriteLine(\"Destination not \" + \"reachable from given source\"); } static void Main() { // Input matrix with landmines shown with number 0 int[,] mat = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // Find shortest path findShortestPath(mat); }} // This code is contributed by rameshtravel07.",
"e": 45863,
"s": 40410,
"text": null
},
{
"code": "<script> // Javascript program to find shortest safe Route // in the matrix with landmines let R = 12; let C = 10; // These arrays are used to get row and column // numbers of 4 neighbours of a given cell let rowNum = [ -1, 0, 0, 1 ]; let colNum = [ 0, -1, 1, 0 ]; let min_dist; // A function to check if a given cell (x, y) // can be visited or not function isSafe(mat, visited, x, y) { if (mat[x][y] == 0 || visited[x][y]) return false; return true; } // A function to check if a given cell (x, y) is // a valid cell or not function isValid(x, y) { if (x < R && y < C && x >= 0 && y >= 0) return true; return false; } // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 function markUnsafeCells(mat) { for(let i = 0; i < R; i++) { for(let j = 0; j < C; j++) { // If a landmines is found if (mat[i][j] == 0) { // Mark all adjacent cells for(let k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } } // Mark all found adjacent cells as unsafe for(let i = 0; i < R; i++) { for(let j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } // Uncomment below lines to print the path /* * for (int i = 0; i < R; i++) { * for (int j = 0; j < C; j++) { cout << * std::setw(3) << mat[i][j]; } cout << endl; } */ } // Function to find shortest safe Route in the // matrix with landmines // mat[][] - binary input matrix with safe cells marked as 1 // visited[][] - store info about cells already visited in // current route // (i, j) are coordinates of the current cell // min_dist --> stores minimum cost of shortest path so far // dist --> stores current path cost function findShortestPathUtil(mat, visited, i, j, dist) { // If destination is reached if (j == C - 1) { // Update shortest path found so far min_dist = Math.min(dist, min_dist); return; } // If current path cost exceeds minimum so far if (dist > min_dist) return; // include (i, j) in current path visited[i][j] = true; // Recurse for all safe adjacent neighbours for(let k = 0; k < 4; k++) { if (isValid(i + rowNum[k], j + colNum[k]) && isSafe(mat, visited, i + rowNum[k], j + colNum[k])) { findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1); } } // Backtrack visited[i][j] = false; } // A wrapper function over findshortestPathUtil() function findShortestPath(mat) { // Stores minimum cost of shortest path so far min_dist = Number.MAX_VALUE; // Create a boolean matrix to store info about // cells already visited in current route let visited = new Array(R); for(let i = 0; i < R; i++) { visited[i] = new Array(C); for(let j = 0; j < C; j++) { visited[i][j] = false; } } // Mark adjacent cells of landmines as unsafe markUnsafeCells(mat); // Start from first column and take minimum for(let i = 0; i < R; i++) { // If path is safe from current cell if (mat[i][0] == 1) { // Find shortest route from (i, 0) to any // cell of last column (x, C - 1) where // 0 <= x < R findShortestPathUtil(mat, visited, i, 0, 0); // If min distance is already found if (min_dist == C - 1) break; } } // If destination can be reached if (min_dist != Number.MAX_VALUE) document.write(\"Length of shortest \" + \"safe route is \" + min_dist + \"</br>\"); else // If the destination is not reachable document.write(\"Destination not \" + \"reachable from given source\" + \"</br>\"); } // Input matrix with landmines shown with number 0 let mat = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ]; // Find shortest path findShortestPath(mat); // This code is contributed by decode2207.</script>",
"e": 51138,
"s": 45863,
"text": null
},
{
"code": null,
"e": 51147,
"s": 51138,
"text": "Output: "
},
{
"code": null,
"e": 51183,
"s": 51147,
"text": "Length of shortest safe route is 13"
},
{
"code": null,
"e": 51506,
"s": 51183,
"text": "Another method: It can be solved in polynomial time with the help of Breadth First Search. Enqueue the cells with 1 value in the queue with the distance as 0. As the BFS proceeds, shortest path to each cell from the first column is computed. Finally for the reachable cells in the last column, output the minimum distance."
},
{
"code": null,
"e": 51548,
"s": 51506,
"text": "The implementation in C++ is as follows: "
},
{
"code": null,
"e": 51552,
"s": 51548,
"text": "C++"
},
{
"code": "// C++ program to find shortest safe Route in// the matrix with landmines#include <bits/stdc++.h>using namespace std; #define R 12#define C 10 struct Key{ int x,y; Key(int i,int j){ x=i;y=j;};}; // These arrays are used to get row and column// numbers of 4 neighbours of a given cellint rowNum[] = { -1, 0, 0, 1 };int colNum[] = { 0, -1, 1, 0 }; // A function to check if a given cell (x, y) is// a valid cell or notbool isValid(int x, int y){ if (x < R && y < C && x >= 0 && y >= 0) return true; return false;} // A function to mark all adjacent cells of// landmines as unsafe. Landmines are shown with// number 0void findShortestPath(int mat[R][C]){ int i,j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { // if a landmines is found if (mat[i][j] == 0) { // mark all adjacent cells for (int k = 0; k < 4; k++) if (isValid(i + rowNum[k], j + colNum[k])) mat[i + rowNum[k]][j + colNum[k]] = -1; } } }// mark all found adjacent cells as unsafe for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == -1) mat[i][j] = 0; } } int dist[R][C]; for(i=0;i<R;i++){ for(j=0;j<C;j++) dist[i][j] = -1; } queue<Key> q; for(i=0;i<R;i++){ if(mat[i][0] == 1){ q.push(Key(i,0)); dist[i][0] = 0; } } while(!q.empty()){ Key k = q.front(); q.pop(); int d = dist[k.x][k.y]; int x = k.x; int y = k.y; for (int k = 0; k < 4; k++) { int xp = x + rowNum[k]; int yp = y + colNum[k]; if(isValid(xp,yp) && dist[xp][yp] == -1 && mat[xp][yp] == 1){ dist[xp][yp] = d+1; q.push(Key(xp,yp)); } } } // stores minimum cost of shortest path so far int ans = INT_MAX; // start from first column and take minimum for(i=0;i<R;i++){ if(mat[i][C-1] == 1 && dist[i][C-1] != -1){ ans = min(ans,dist[i][C-1]); } } // if destination can be reached if(ans == INT_MAX) cout << \"NOT POSSIBLE\\n\"; else// if the destination is not reachable cout << \"Length of shortest safe route is \" << ans << endl;} // Driver codeint main(){ // input matrix with landmines shown with number 0 int mat[R][C] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } }; // find shortest path findShortestPath(mat);}",
"e": 54580,
"s": 51552,
"text": null
},
{
"code": null,
"e": 54589,
"s": 54580,
"text": "Output: "
},
{
"code": null,
"e": 54625,
"s": 54589,
"text": "Length of shortest safe route is 13"
},
{
"code": null,
"e": 55045,
"s": 54625,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 55058,
"s": 55045,
"text": "geekoverflow"
},
{
"code": null,
"e": 55070,
"s": 55058,
"text": "sanjeev2552"
},
{
"code": null,
"e": 55080,
"s": 55070,
"text": "ruhelaa48"
},
{
"code": null,
"e": 55095,
"s": 55080,
"text": "varshagumber28"
},
{
"code": null,
"e": 55106,
"s": 55095,
"text": "decode2207"
},
{
"code": null,
"e": 55121,
"s": 55106,
"text": "rameshtravel07"
},
{
"code": null,
"e": 55130,
"s": 55121,
"text": "mukesh07"
},
{
"code": null,
"e": 55144,
"s": 55130,
"text": "Shortest Path"
},
{
"code": null,
"e": 55157,
"s": 55144,
"text": "Backtracking"
},
{
"code": null,
"e": 55164,
"s": 55157,
"text": "Matrix"
},
{
"code": null,
"e": 55171,
"s": 55164,
"text": "Matrix"
},
{
"code": null,
"e": 55185,
"s": 55171,
"text": "Shortest Path"
},
{
"code": null,
"e": 55198,
"s": 55185,
"text": "Backtracking"
},
{
"code": null,
"e": 55296,
"s": 55198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 55305,
"s": 55296,
"text": "Comments"
},
{
"code": null,
"e": 55318,
"s": 55305,
"text": "Old Comments"
},
{
"code": null,
"e": 55346,
"s": 55318,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 55382,
"s": 55346,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 55435,
"s": 55382,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 55463,
"s": 55435,
"text": "Subset Sum | Backtracking-4"
},
{
"code": null,
"e": 55496,
"s": 55463,
"text": "Backtracking to find all subsets"
},
{
"code": null,
"e": 55531,
"s": 55496,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 55575,
"s": 55531,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 55611,
"s": 55575,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 55673,
"s": 55611,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
}
] |
Calculating the completeness score using sklearn in Python - GeeksforGeeks
|
26 May, 2021
An entirely complete clustering is one where each cluster has information that directs a place toward a similar class cluster. Completeness portrays the closeness of the clustering algorithm to this (completeness_score) perfection.
This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way.
Syntax: sklearn.metrics.completeness_score(labels_true, labels_pred)
Parameters:
labels_true:<int array, shape = [n_samples]>: It accepts the ground truth class labels to be used as a reference.
labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate.
Returns: completeness score between 0.0 and 1.0. 1.0 stands for perfectly completeness labeling.
Switching label_true with label_pred will return the homogeneity_score.
Example 1:
Python3
# Importing the modules
import pandas as pd
from sklearn import datasets
from sklearn.cluster import KMeans
from sklearn.metrics import completeness_score
# Loading the data
digits = datasets.load_digits()
# Separating the dependent and independent variables
Y = digits.target
X = digits.data
# Building the clustering model
kmeans = KMeans(n_clusters = 2)
# Training the clustering model
kmeans.fit(X)
# Storing the predicted Clustering labels
labels = kmeans.predict(X)
# Evaluating the performance
print(completeness_score(Y, labels))
Output:
0.8471148027985769
Example 2: Perfectly completeness:
Python3
# Importing the module
from sklearn.metrics.cluster import completeness_score
# Evaluating the score
Cscore = completeness_score([0, 1, 0, 1],
[1, 0, 1, 0])
print(Cscore)
Output:
1.0
Example 3: Non-perfect labeling that further split classes into more clusters can be perfectly completeness:
Python3
# Importing the module
from sklearn.metrics.cluster import completeness_score
# Evaluating the score
Cscore = completeness_score([0, 1, 2, 3],
[0, 0, 1, 1])
print(Cscore)
Output:
0.9999999999999999
Example 4: Include samples from different classes don’t make for completeness labeling:
Python3
# Importing the module
from sklearn.metrics.cluster import completeness_score
# Evaluating the score
Cscore = completeness_score([0, 0, 0, 0],
[0, 1, 2, 3])
print(Cscore)
Output:
0.0
sweetyty
ML-Clustering
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
|
[
{
"code": null,
"e": 25627,
"s": 25596,
"text": " \n26 May, 2021\n"
},
{
"code": null,
"e": 25860,
"s": 25627,
"text": "An entirely complete clustering is one where each cluster has information that directs a place toward a similar class cluster. Completeness portrays the closeness of the clustering algorithm to this (completeness_score) perfection. "
},
{
"code": null,
"e": 26007,
"s": 25860,
"text": "This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way."
},
{
"code": null,
"e": 26076,
"s": 26007,
"text": "Syntax: sklearn.metrics.completeness_score(labels_true, labels_pred)"
},
{
"code": null,
"e": 26088,
"s": 26076,
"text": "Parameters:"
},
{
"code": null,
"e": 26202,
"s": 26088,
"text": "labels_true:<int array, shape = [n_samples]>: It accepts the ground truth class labels to be used as a reference."
},
{
"code": null,
"e": 26294,
"s": 26202,
"text": "labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate."
},
{
"code": null,
"e": 26391,
"s": 26294,
"text": "Returns: completeness score between 0.0 and 1.0. 1.0 stands for perfectly completeness labeling."
},
{
"code": null,
"e": 26463,
"s": 26391,
"text": "Switching label_true with label_pred will return the homogeneity_score."
},
{
"code": null,
"e": 26474,
"s": 26463,
"text": "Example 1:"
},
{
"code": null,
"e": 26482,
"s": 26474,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Importing the modules\nimport pandas as pd \nfrom sklearn import datasets\nfrom sklearn.cluster import KMeans \nfrom sklearn.metrics import completeness_score\n \n# Loading the data \ndigits = datasets.load_digits()\n \n# Separating the dependent and independent variables \nY = digits.target\nX = digits.data\n \n# Building the clustering model \nkmeans = KMeans(n_clusters = 2) \n \n# Training the clustering model \nkmeans.fit(X) \n \n# Storing the predicted Clustering labels \nlabels = kmeans.predict(X) \n \n# Evaluating the performance \nprint(completeness_score(Y, labels))\n\n\n\n\n\n",
"e": 27077,
"s": 26492,
"text": null
},
{
"code": null,
"e": 27085,
"s": 27077,
"text": "Output:"
},
{
"code": null,
"e": 27104,
"s": 27085,
"text": "0.8471148027985769"
},
{
"code": null,
"e": 27139,
"s": 27104,
"text": "Example 2: Perfectly completeness:"
},
{
"code": null,
"e": 27147,
"s": 27139,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Importing the module\nfrom sklearn.metrics.cluster import completeness_score\n \n# Evaluating the score\nCscore = completeness_score([0, 1, 0, 1], \n [1, 0, 1, 0])\nprint(Cscore)\n\n\n\n\n\n",
"e": 27372,
"s": 27157,
"text": null
},
{
"code": null,
"e": 27382,
"s": 27372,
"text": " Output: "
},
{
"code": null,
"e": 27387,
"s": 27382,
"text": "1.0 "
},
{
"code": null,
"e": 27496,
"s": 27387,
"text": "Example 3: Non-perfect labeling that further split classes into more clusters can be perfectly completeness:"
},
{
"code": null,
"e": 27504,
"s": 27496,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Importing the module\nfrom sklearn.metrics.cluster import completeness_score\n \n# Evaluating the score\nCscore = completeness_score([0, 1, 2, 3], \n [0, 0, 1, 1])\nprint(Cscore)\n\n\n\n\n\n",
"e": 27729,
"s": 27514,
"text": null
},
{
"code": null,
"e": 27737,
"s": 27729,
"text": "Output:"
},
{
"code": null,
"e": 27756,
"s": 27737,
"text": "0.9999999999999999"
},
{
"code": null,
"e": 27844,
"s": 27756,
"text": "Example 4: Include samples from different classes don’t make for completeness labeling:"
},
{
"code": null,
"e": 27852,
"s": 27844,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Importing the module\nfrom sklearn.metrics.cluster import completeness_score\n \n# Evaluating the score\nCscore = completeness_score([0, 0, 0, 0], \n [0, 1, 2, 3])\nprint(Cscore)\n\n\n\n\n\n",
"e": 28077,
"s": 27862,
"text": null
},
{
"code": null,
"e": 28085,
"s": 28077,
"text": "Output:"
},
{
"code": null,
"e": 28089,
"s": 28085,
"text": "0.0"
},
{
"code": null,
"e": 28100,
"s": 28091,
"text": "sweetyty"
},
{
"code": null,
"e": 28116,
"s": 28100,
"text": "\nML-Clustering\n"
},
{
"code": null,
"e": 28125,
"s": 28116,
"text": "\nPython\n"
},
{
"code": null,
"e": 28330,
"s": 28125,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 28362,
"s": 28330,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28404,
"s": 28362,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28446,
"s": 28404,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28502,
"s": 28446,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28529,
"s": 28502,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28560,
"s": 28529,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28589,
"s": 28560,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28628,
"s": 28589,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28664,
"s": 28628,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Java Program to Find if a Given Year is a Leap Year - GeeksforGeeks
|
26 Jan, 2022
Leap Year contains 366 days, which comes once every four years. Every leap year corresponds to these facts :
A century year is a year ending with 00. A century year is a leap year only if it is divisible by 400.
A leap year (except a century year) can be identified if it is exactly divisible by 4.
A century year should be divisible by 4 and 100 both.
A non-century year should be divisible only by 4.
Let’s find out whether a year is a leap year or not.
Without Using Scanner Class
As the name suggests here user is bound not to select a year of his choice. The following program illustrates the way to find out if a year is a leap year:
Java
// Java program to find a leap year // Importing Classes/Filesimport java.io.*; // Class for leap-year dealingpublic class GeeksforGeeks { // Method to check leap year public static void isLeapYear(int year) { // flag to take a non-leap year by default boolean is_leap_year = false; // If year is divisible by 4 if (year % 4 == 0) { is_leap_year = true; // To identify whether it // is a century year or // not if (year % 100 == 0) { // Checking if year is divisible by 400 // therefore century leap year if (year % 400 == 0) is_leap_year = true; else is_leap_year = false; } } // We land here when corresponding if fails // If year is not divisible by 4 else // Flag dealing- Non leap-year is_leap_year = false; if (!is_leap_year) System.out.println(year + " : Non Leap-year"); else System.out.println(year + " : Leap-year"); } // Main Driver Code public static void main(String[] args) { // Calling our function by // passing century year not divisible by 400 isLeapYear(2000); // Calling our function by // passing Non-century year isLeapYear(2002); }}
2000 : Leap-year
2002 : Non Leap-year
2000 is a century year divisible by 100 and 4. 2002 is not divisible by 4, therefore not a leap year.
Using Scanner Class
Here the user is provided the flexibility to enter the year of own choice as Scanner Class is imported here rest the if-else blocks are also combined in a single statement to check if the input year is a leap year. The following program illustrates the way to find out if a year is a leap year:
Java
// Java program to check Leap-year// by taking input from user // Importing Classes/Filesimport java.io.*; // Importing Scanner Classimport java.util.Scanner; // Class to check leap-year or notpublic class GFG { // Driver Main code public static void main(String[] args) { // Considering any random year int year; // Taking input from user using Scanner Class // scn is an object made of Scanner Class Scanner scn = new Scanner(System.in); year = scn.nextInt(); // 1st condition check- It is century leap year // 2nd condition check- It is leap year and not // century year if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { // Both conditions true- Print leap year System.out.println(year + " : Leap Year"); } else { // Any condition fails- Print Non-leap year System.out.println(year + " : Non - Leap Year"); } }}
Input:
2012
Output:
2012 : Leap Year
simranarora5sos
amanmalakar007
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
Initializing a List in Java
Convert a String to Character array in Java
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 24876,
"s": 24848,
"text": "\n26 Jan, 2022"
},
{
"code": null,
"e": 24986,
"s": 24876,
"text": "Leap Year contains 366 days, which comes once every four years. Every leap year corresponds to these facts : "
},
{
"code": null,
"e": 25089,
"s": 24986,
"text": "A century year is a year ending with 00. A century year is a leap year only if it is divisible by 400."
},
{
"code": null,
"e": 25176,
"s": 25089,
"text": "A leap year (except a century year) can be identified if it is exactly divisible by 4."
},
{
"code": null,
"e": 25230,
"s": 25176,
"text": "A century year should be divisible by 4 and 100 both."
},
{
"code": null,
"e": 25280,
"s": 25230,
"text": "A non-century year should be divisible only by 4."
},
{
"code": null,
"e": 25333,
"s": 25280,
"text": "Let’s find out whether a year is a leap year or not."
},
{
"code": null,
"e": 25361,
"s": 25333,
"text": "Without Using Scanner Class"
},
{
"code": null,
"e": 25518,
"s": 25361,
"text": "As the name suggests here user is bound not to select a year of his choice. The following program illustrates the way to find out if a year is a leap year: "
},
{
"code": null,
"e": 25523,
"s": 25518,
"text": "Java"
},
{
"code": "// Java program to find a leap year // Importing Classes/Filesimport java.io.*; // Class for leap-year dealingpublic class GeeksforGeeks { // Method to check leap year public static void isLeapYear(int year) { // flag to take a non-leap year by default boolean is_leap_year = false; // If year is divisible by 4 if (year % 4 == 0) { is_leap_year = true; // To identify whether it // is a century year or // not if (year % 100 == 0) { // Checking if year is divisible by 400 // therefore century leap year if (year % 400 == 0) is_leap_year = true; else is_leap_year = false; } } // We land here when corresponding if fails // If year is not divisible by 4 else // Flag dealing- Non leap-year is_leap_year = false; if (!is_leap_year) System.out.println(year + \" : Non Leap-year\"); else System.out.println(year + \" : Leap-year\"); } // Main Driver Code public static void main(String[] args) { // Calling our function by // passing century year not divisible by 400 isLeapYear(2000); // Calling our function by // passing Non-century year isLeapYear(2002); }}",
"e": 26926,
"s": 25523,
"text": null
},
{
"code": null,
"e": 26965,
"s": 26926,
"text": "2000 : Leap-year\n2002 : Non Leap-year\n"
},
{
"code": null,
"e": 27068,
"s": 26965,
"text": "2000 is a century year divisible by 100 and 4. 2002 is not divisible by 4, therefore not a leap year. "
},
{
"code": null,
"e": 27088,
"s": 27068,
"text": "Using Scanner Class"
},
{
"code": null,
"e": 27384,
"s": 27088,
"text": "Here the user is provided the flexibility to enter the year of own choice as Scanner Class is imported here rest the if-else blocks are also combined in a single statement to check if the input year is a leap year. The following program illustrates the way to find out if a year is a leap year: "
},
{
"code": null,
"e": 27389,
"s": 27384,
"text": "Java"
},
{
"code": "// Java program to check Leap-year// by taking input from user // Importing Classes/Filesimport java.io.*; // Importing Scanner Classimport java.util.Scanner; // Class to check leap-year or notpublic class GFG { // Driver Main code public static void main(String[] args) { // Considering any random year int year; // Taking input from user using Scanner Class // scn is an object made of Scanner Class Scanner scn = new Scanner(System.in); year = scn.nextInt(); // 1st condition check- It is century leap year // 2nd condition check- It is leap year and not // century year if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { // Both conditions true- Print leap year System.out.println(year + \" : Leap Year\"); } else { // Any condition fails- Print Non-leap year System.out.println(year + \" : Non - Leap Year\"); } }}",
"e": 28396,
"s": 27389,
"text": null
},
{
"code": null,
"e": 28404,
"s": 28396,
"text": " Input:"
},
{
"code": null,
"e": 28409,
"s": 28404,
"text": "2012"
},
{
"code": null,
"e": 28417,
"s": 28409,
"text": "Output:"
},
{
"code": null,
"e": 28434,
"s": 28417,
"text": "2012 : Leap Year"
},
{
"code": null,
"e": 28450,
"s": 28434,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28465,
"s": 28450,
"text": "amanmalakar007"
},
{
"code": null,
"e": 28470,
"s": 28465,
"text": "Java"
},
{
"code": null,
"e": 28484,
"s": 28470,
"text": "Java Programs"
},
{
"code": null,
"e": 28489,
"s": 28484,
"text": "Java"
},
{
"code": null,
"e": 28587,
"s": 28489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28596,
"s": 28587,
"text": "Comments"
},
{
"code": null,
"e": 28609,
"s": 28596,
"text": "Old Comments"
},
{
"code": null,
"e": 28641,
"s": 28609,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28671,
"s": 28641,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28690,
"s": 28671,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28741,
"s": 28690,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28759,
"s": 28741,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28787,
"s": 28759,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 28831,
"s": 28787,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28878,
"s": 28831,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28912,
"s": 28878,
"text": "Convert Double to Integer in Java"
}
] |
Ruby | Array select() function - GeeksforGeeks
|
06 Dec, 2019
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value.
Syntax: Array.select()
Parameter: Array
Return: A new array containing all elements of array for which the given block returns a true value.
Example #1 :
# Ruby code for select() method # declaring arraya = [18, 22, 33, 3, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 3, 3, 50, 6] # selectputs "select method : #{a.select {|num| num > 10 }}\n\n" # selectputs "select method : #{b.select {|x| x.odd? }}\n\n"
Output :
select method : [18, 22, 33]
select method : [1, 1, 1, 9]
Example #2 :
# Ruby code for select() method # declaring arraya = [18, 22, 33, 3, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 3, 3, 53, 6] # selectputs "select method : #{c.select {|num| num > 10 }}\n\n" # selectputs "select method : #{c.select {|num| num.even? }}\n\n"
Output :
select method : [18, 22, 53]
select method : [18, 22, 6]
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Enumerator each_with_index function
Ruby | Data Types
Ruby | Numeric round() function
Ruby For Beginners
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
|
[
{
"code": null,
"e": 25614,
"s": 25586,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 25771,
"s": 25614,
"text": "Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value."
},
{
"code": null,
"e": 25794,
"s": 25771,
"text": "Syntax: Array.select()"
},
{
"code": null,
"e": 25811,
"s": 25794,
"text": "Parameter: Array"
},
{
"code": null,
"e": 25912,
"s": 25811,
"text": "Return: A new array containing all elements of array for which the given block returns a true value."
},
{
"code": null,
"e": 25925,
"s": 25912,
"text": "Example #1 :"
},
{
"code": "# Ruby code for select() method # declaring arraya = [18, 22, 33, 3, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 3, 3, 50, 6] # selectputs \"select method : #{a.select {|num| num > 10 }}\\n\\n\" # selectputs \"select method : #{b.select {|x| x.odd? }}\\n\\n\"",
"e": 26215,
"s": 25925,
"text": null
},
{
"code": null,
"e": 26224,
"s": 26215,
"text": "Output :"
},
{
"code": null,
"e": 26285,
"s": 26224,
"text": "select method : [18, 22, 33]\n\nselect method : [1, 1, 1, 9]\n\n"
},
{
"code": null,
"e": 26298,
"s": 26285,
"text": "Example #2 :"
},
{
"code": "# Ruby code for select() method # declaring arraya = [18, 22, 33, 3, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 3, 3, 53, 6] # selectputs \"select method : #{c.select {|num| num > 10 }}\\n\\n\" # selectputs \"select method : #{c.select {|num| num.even? }}\\n\\n\"",
"e": 26593,
"s": 26298,
"text": null
},
{
"code": null,
"e": 26602,
"s": 26593,
"text": "Output :"
},
{
"code": null,
"e": 26662,
"s": 26602,
"text": "select method : [18, 22, 53]\n\nselect method : [18, 22, 6]\n\n"
},
{
"code": null,
"e": 26679,
"s": 26662,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 26692,
"s": 26679,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 26697,
"s": 26692,
"text": "Ruby"
},
{
"code": null,
"e": 26795,
"s": 26697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26826,
"s": 26795,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 26856,
"s": 26826,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 26883,
"s": 26856,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 26907,
"s": 26883,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 26937,
"s": 26907,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 26980,
"s": 26937,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26998,
"s": 26980,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 27030,
"s": 26998,
"text": "Ruby | Numeric round() function"
},
{
"code": null,
"e": 27049,
"s": 27030,
"text": "Ruby For Beginners"
}
] |
Introduction to Semantic UI - GeeksforGeeks
|
21 Jan, 2022
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing.How to use Semantic UI ? Just google CDN semantic UI and you will get the CDN link for semantic UI and just put it in your head tag of your HTML and you are good to go.Let’s see the code for how to put semantic UI CDN in HTML.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <h1>This is How to integrate semantic-ui</h1> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html>
And you can remove the link from the head to see the difference.The second way of using is downloading the min.css file of the Semantic UI whose link you can find on semantic UI official site and use it directly and it helps offline.Now let’s see an example of using Semantic-UI.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <p>This is a simple example of using semantic-ui</p> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html>
Output:
Let’s see another example of Semantic-UI loader.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="ui inverted segment"> <div class="ui active inverted loader"></div> <br> <br> <br> <br> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html>
Output:
You can directly run these examples by clicking on run on IDE.
clintra
Semantic-UI
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 40451,
"s": 40423,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 40894,
"s": 40451,
"text": "Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing.How to use Semantic UI ? Just google CDN semantic UI and you will get the CDN link for semantic UI and just put it in your head tag of your HTML and you are good to go.Let’s see the code for how to put semantic UI CDN in HTML. "
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <h1>This is How to integrate semantic-ui</h1> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>",
"e": 41286,
"s": 40894,
"text": null
},
{
"code": null,
"e": 41568,
"s": 41286,
"text": "And you can remove the link from the head to see the difference.The second way of using is downloading the min.css file of the Semantic UI whose link you can find on semantic UI official site and use it directly and it helps offline.Now let’s see an example of using Semantic-UI. "
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <p>This is a simple example of using semantic-ui</p> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>",
"e": 42051,
"s": 41568,
"text": null
},
{
"code": null,
"e": 42061,
"s": 42051,
"text": "Output: "
},
{
"code": null,
"e": 42112,
"s": 42061,
"text": "Let’s see another example of Semantic-UI loader. "
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"ui inverted segment\"> <div class=\"ui active inverted loader\"></div> <br> <br> <br> <br> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>",
"e": 42630,
"s": 42112,
"text": null
},
{
"code": null,
"e": 42640,
"s": 42630,
"text": "Output: "
},
{
"code": null,
"e": 42704,
"s": 42640,
"text": "You can directly run these examples by clicking on run on IDE. "
},
{
"code": null,
"e": 42712,
"s": 42704,
"text": "clintra"
},
{
"code": null,
"e": 42724,
"s": 42712,
"text": "Semantic-UI"
},
{
"code": null,
"e": 42728,
"s": 42724,
"text": "CSS"
},
{
"code": null,
"e": 42745,
"s": 42728,
"text": "Web Technologies"
},
{
"code": null,
"e": 42843,
"s": 42745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42893,
"s": 42843,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 42955,
"s": 42893,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 43003,
"s": 42955,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 43061,
"s": 43003,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 43116,
"s": 43061,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 43156,
"s": 43116,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 43189,
"s": 43156,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 43234,
"s": 43189,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 43277,
"s": 43234,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Introduction to Convolution Neural Network
|
08 Jul, 2022
It is assumed that the reader knows the concept of Neural networks.When it comes to Machine Learning, Artificial Neural Networks perform really well. Artificial Neural Networks are used in various classification tasks like image, audio, words. Different types of Neural Networks are used for different purposes, for example for predicting the sequence of words we use Recurrent Neural Networks more precisely an LSTM, similarly for image classification we use Convolution Neural networks. In this blog, we are going to build a basic building block for CNN.Before diving into the Convolution Neural Network, let us first revisit some concepts of Neural Network. In a regular Neural Network there are three types of layers:
Input Layers: It’s the layer in which we give input to our model. The number of neurons in this layer is equal to the total number of features in our data (number of pixels in the case of an image).Hidden Layer: The input from the Input layer is then feed into the hidden layer. There can be many hidden layers depending upon our model and data size. Each hidden layer can have different numbers of neurons which are generally greater than the number of features. The output from each layer is computed by matrix multiplication of output of the previous layer with learnable weights of that layer and then by the addition of learnable biases followed by activation function which makes the network nonlinear.Output Layer: The output from the hidden layer is then fed into a logistic function like sigmoid or softmax which converts the output of each class into the probability score of each class.
Input Layers: It’s the layer in which we give input to our model. The number of neurons in this layer is equal to the total number of features in our data (number of pixels in the case of an image).
Hidden Layer: The input from the Input layer is then feed into the hidden layer. There can be many hidden layers depending upon our model and data size. Each hidden layer can have different numbers of neurons which are generally greater than the number of features. The output from each layer is computed by matrix multiplication of output of the previous layer with learnable weights of that layer and then by the addition of learnable biases followed by activation function which makes the network nonlinear.
Output Layer: The output from the hidden layer is then fed into a logistic function like sigmoid or softmax which converts the output of each class into the probability score of each class.
The data is then fed into the model and output from each layer is obtained this step is called feedforward, we then calculate the error using an error function, some common error functions are cross-entropy, square loss error, etc. After that, we backpropagate into the model by calculating the derivatives. This step is called Backpropagation which basically is used to minimize the loss.Here’s the basic python code for a neural network with random inputs and two hidden layers.
Python
activation = lambda x: 1.0/(1.0 + np.exp(-x)) # sigmoid functioninput = np.random.randn(3, 1)hidden_1 = activation(np.dot(W1, input) + b1)hidden_2 = activation(np.dot(W2, hidden_1) + b2)output = np.dot(W3, hidden_2) + b3
W1,W2,W3,b1,b2,b3 are learnable parameter of the model.
Image source: cs231n.stanford.edu
Convolution Neural Network
Convolution Neural Networks or covnets are neural networks that share their parameters. Imagine you have an image. It can be represented as a cuboid having its length, width (dimension of the image), and height (as images generally have red, green, and blue channels).
Now imagine taking a small patch of this image and running a small neural network on it, with say, k outputs and represent them vertically. Now slide that neural network across the whole image, as a result, we will get another image with different width, height, and depth. Instead of just R, G, and B channels now we have more channels but lesser width and height. This operation is called Convolution. If the patch size is the same as that of the image it will be a regular neural network. Because of this small patch, we have fewer weights.
Image source: Deep Learning Udacity
Now let’s talk about a bit of mathematics that is involved in the whole convolution process.
Convolution layers consist of a set of learnable filters (a patch in the above image). Every filter has small width and height and the same depth as that of input volume (3 if the input layer is image input).
For example, if we have to run convolution on an image with dimension 34x34x3. The possible size of filters can be axax3, where ‘a’ can be 3, 5, 7, etc but small as compared to image dimension.
During forward pass, we slide each filter across the whole input volume step by step where each step is called stride (which can have value 2 or 3 or even 4 for high dimensional images) and compute the dot product between the weights of filters and patch from input volume.
As we slide our filters we’ll get a 2-D output for each filter and we’ll stack them together and as a result, we’ll get output volume having a depth equal to the number of filters. The network will learn all the filters.
Layers used to build ConvNets
A covnets is a sequence of layers, and every layer transforms one volume to another through a differentiable function. Types of layers: Let’s take an example by running a covnets on of image of dimension 32 x 32 x 3.
Input Layer: This layer holds the raw input of the image with width 32, height 32, and depth 3.Convolution Layer: This layer computes the output volume by computing the dot product between all filters and image patches. Suppose we use a total of 12 filters for this layer we’ll get output volume of dimension 32 x 32 x 12.Activation Function Layer: This layer will apply an element-wise activation function to the output of the convolution layer. Some common activation functions are RELU: max(0, x), Sigmoid: 1/(1+e^-x), Tanh, Leaky RELU, etc. The volume remains unchanged hence output volume will have dimension 32 x 32 x 12.Pool Layer: This layer is periodically inserted in the covnets and its main function is to reduce the size of volume which makes the computation fast reduces memory and also prevents overfitting. Two common types of pooling layers are max pooling and average pooling. If we use a max pool with 2 x 2 filters and stride 2, the resultant volume will be of dimension 16x16x12.
Input Layer: This layer holds the raw input of the image with width 32, height 32, and depth 3.
Convolution Layer: This layer computes the output volume by computing the dot product between all filters and image patches. Suppose we use a total of 12 filters for this layer we’ll get output volume of dimension 32 x 32 x 12.
Activation Function Layer: This layer will apply an element-wise activation function to the output of the convolution layer. Some common activation functions are RELU: max(0, x), Sigmoid: 1/(1+e^-x), Tanh, Leaky RELU, etc. The volume remains unchanged hence output volume will have dimension 32 x 32 x 12.
Pool Layer: This layer is periodically inserted in the covnets and its main function is to reduce the size of volume which makes the computation fast reduces memory and also prevents overfitting. Two common types of pooling layers are max pooling and average pooling. If we use a max pool with 2 x 2 filters and stride 2, the resultant volume will be of dimension 16x16x12.
Image source: cs231n.stanford.edu
Fully-Connected Layer: This layer is a regular neural network layer that takes input from the previous layer and computes the class scores and outputs the 1-D array of size equal to the number of classes.
Fully-Connected Layer: This layer is a regular neural network layer that takes input from the previous layer and computes the class scores and outputs the 1-D array of size equal to the number of classes.
Image source: cs231n.stanford.edu
References: Stanford Convolution Neural Network Course (CS231n)This article is contributed by Akhand Pratap Mishra. 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.
kushkunal077
23620uday2021
Neural Network
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hypervisor
Advantages and Disadvantages of OOP
Introduction to Electronic Mail
Cloud Computing
Analog to Digital Conversion
array::size() in C++ STL
Characteristics of Cloud Computing
Bubble Sort algorithm using JavaScript
Introduction to Deep Learning
Types of Cloud
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 775,
"s": 52,
"text": "It is assumed that the reader knows the concept of Neural networks.When it comes to Machine Learning, Artificial Neural Networks perform really well. Artificial Neural Networks are used in various classification tasks like image, audio, words. Different types of Neural Networks are used for different purposes, for example for predicting the sequence of words we use Recurrent Neural Networks more precisely an LSTM, similarly for image classification we use Convolution Neural networks. In this blog, we are going to build a basic building block for CNN.Before diving into the Convolution Neural Network, let us first revisit some concepts of Neural Network. In a regular Neural Network there are three types of layers: "
},
{
"code": null,
"e": 1673,
"s": 775,
"text": "Input Layers: It’s the layer in which we give input to our model. The number of neurons in this layer is equal to the total number of features in our data (number of pixels in the case of an image).Hidden Layer: The input from the Input layer is then feed into the hidden layer. There can be many hidden layers depending upon our model and data size. Each hidden layer can have different numbers of neurons which are generally greater than the number of features. The output from each layer is computed by matrix multiplication of output of the previous layer with learnable weights of that layer and then by the addition of learnable biases followed by activation function which makes the network nonlinear.Output Layer: The output from the hidden layer is then fed into a logistic function like sigmoid or softmax which converts the output of each class into the probability score of each class."
},
{
"code": null,
"e": 1872,
"s": 1673,
"text": "Input Layers: It’s the layer in which we give input to our model. The number of neurons in this layer is equal to the total number of features in our data (number of pixels in the case of an image)."
},
{
"code": null,
"e": 2383,
"s": 1872,
"text": "Hidden Layer: The input from the Input layer is then feed into the hidden layer. There can be many hidden layers depending upon our model and data size. Each hidden layer can have different numbers of neurons which are generally greater than the number of features. The output from each layer is computed by matrix multiplication of output of the previous layer with learnable weights of that layer and then by the addition of learnable biases followed by activation function which makes the network nonlinear."
},
{
"code": null,
"e": 2573,
"s": 2383,
"text": "Output Layer: The output from the hidden layer is then fed into a logistic function like sigmoid or softmax which converts the output of each class into the probability score of each class."
},
{
"code": null,
"e": 3056,
"s": 2573,
"text": "The data is then fed into the model and output from each layer is obtained this step is called feedforward, we then calculate the error using an error function, some common error functions are cross-entropy, square loss error, etc. After that, we backpropagate into the model by calculating the derivatives. This step is called Backpropagation which basically is used to minimize the loss.Here’s the basic python code for a neural network with random inputs and two hidden layers. "
},
{
"code": null,
"e": 3063,
"s": 3056,
"text": "Python"
},
{
"code": "activation = lambda x: 1.0/(1.0 + np.exp(-x)) # sigmoid functioninput = np.random.randn(3, 1)hidden_1 = activation(np.dot(W1, input) + b1)hidden_2 = activation(np.dot(W2, hidden_1) + b2)output = np.dot(W3, hidden_2) + b3",
"e": 3284,
"s": 3063,
"text": null
},
{
"code": null,
"e": 3342,
"s": 3284,
"text": "W1,W2,W3,b1,b2,b3 are learnable parameter of the model. "
},
{
"code": null,
"e": 3376,
"s": 3342,
"text": "Image source: cs231n.stanford.edu"
},
{
"code": null,
"e": 3405,
"s": 3378,
"text": "Convolution Neural Network"
},
{
"code": null,
"e": 3676,
"s": 3405,
"text": "Convolution Neural Networks or covnets are neural networks that share their parameters. Imagine you have an image. It can be represented as a cuboid having its length, width (dimension of the image), and height (as images generally have red, green, and blue channels). "
},
{
"code": null,
"e": 4222,
"s": 3676,
"text": "Now imagine taking a small patch of this image and running a small neural network on it, with say, k outputs and represent them vertically. Now slide that neural network across the whole image, as a result, we will get another image with different width, height, and depth. Instead of just R, G, and B channels now we have more channels but lesser width and height. This operation is called Convolution. If the patch size is the same as that of the image it will be a regular neural network. Because of this small patch, we have fewer weights. "
},
{
"code": null,
"e": 4258,
"s": 4222,
"text": "Image source: Deep Learning Udacity"
},
{
"code": null,
"e": 4353,
"s": 4258,
"text": "Now let’s talk about a bit of mathematics that is involved in the whole convolution process. "
},
{
"code": null,
"e": 4562,
"s": 4353,
"text": "Convolution layers consist of a set of learnable filters (a patch in the above image). Every filter has small width and height and the same depth as that of input volume (3 if the input layer is image input)."
},
{
"code": null,
"e": 4756,
"s": 4562,
"text": "For example, if we have to run convolution on an image with dimension 34x34x3. The possible size of filters can be axax3, where ‘a’ can be 3, 5, 7, etc but small as compared to image dimension."
},
{
"code": null,
"e": 5030,
"s": 4756,
"text": "During forward pass, we slide each filter across the whole input volume step by step where each step is called stride (which can have value 2 or 3 or even 4 for high dimensional images) and compute the dot product between the weights of filters and patch from input volume."
},
{
"code": null,
"e": 5251,
"s": 5030,
"text": "As we slide our filters we’ll get a 2-D output for each filter and we’ll stack them together and as a result, we’ll get output volume having a depth equal to the number of filters. The network will learn all the filters."
},
{
"code": null,
"e": 5283,
"s": 5253,
"text": "Layers used to build ConvNets"
},
{
"code": null,
"e": 5502,
"s": 5283,
"text": "A covnets is a sequence of layers, and every layer transforms one volume to another through a differentiable function. Types of layers: Let’s take an example by running a covnets on of image of dimension 32 x 32 x 3. "
},
{
"code": null,
"e": 6505,
"s": 5502,
"text": "Input Layer: This layer holds the raw input of the image with width 32, height 32, and depth 3.Convolution Layer: This layer computes the output volume by computing the dot product between all filters and image patches. Suppose we use a total of 12 filters for this layer we’ll get output volume of dimension 32 x 32 x 12.Activation Function Layer: This layer will apply an element-wise activation function to the output of the convolution layer. Some common activation functions are RELU: max(0, x), Sigmoid: 1/(1+e^-x), Tanh, Leaky RELU, etc. The volume remains unchanged hence output volume will have dimension 32 x 32 x 12.Pool Layer: This layer is periodically inserted in the covnets and its main function is to reduce the size of volume which makes the computation fast reduces memory and also prevents overfitting. Two common types of pooling layers are max pooling and average pooling. If we use a max pool with 2 x 2 filters and stride 2, the resultant volume will be of dimension 16x16x12. "
},
{
"code": null,
"e": 6601,
"s": 6505,
"text": "Input Layer: This layer holds the raw input of the image with width 32, height 32, and depth 3."
},
{
"code": null,
"e": 6829,
"s": 6601,
"text": "Convolution Layer: This layer computes the output volume by computing the dot product between all filters and image patches. Suppose we use a total of 12 filters for this layer we’ll get output volume of dimension 32 x 32 x 12."
},
{
"code": null,
"e": 7135,
"s": 6829,
"text": "Activation Function Layer: This layer will apply an element-wise activation function to the output of the convolution layer. Some common activation functions are RELU: max(0, x), Sigmoid: 1/(1+e^-x), Tanh, Leaky RELU, etc. The volume remains unchanged hence output volume will have dimension 32 x 32 x 12."
},
{
"code": null,
"e": 7511,
"s": 7135,
"text": "Pool Layer: This layer is periodically inserted in the covnets and its main function is to reduce the size of volume which makes the computation fast reduces memory and also prevents overfitting. Two common types of pooling layers are max pooling and average pooling. If we use a max pool with 2 x 2 filters and stride 2, the resultant volume will be of dimension 16x16x12. "
},
{
"code": null,
"e": 7545,
"s": 7511,
"text": "Image source: cs231n.stanford.edu"
},
{
"code": null,
"e": 7752,
"s": 7545,
"text": "Fully-Connected Layer: This layer is a regular neural network layer that takes input from the previous layer and computes the class scores and outputs the 1-D array of size equal to the number of classes. "
},
{
"code": null,
"e": 7959,
"s": 7752,
"text": "Fully-Connected Layer: This layer is a regular neural network layer that takes input from the previous layer and computes the class scores and outputs the 1-D array of size equal to the number of classes. "
},
{
"code": null,
"e": 7993,
"s": 7959,
"text": "Image source: cs231n.stanford.edu"
},
{
"code": null,
"e": 8489,
"s": 7997,
"text": "References: Stanford Convolution Neural Network Course (CS231n)This article is contributed by Akhand Pratap Mishra. 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": 8502,
"s": 8489,
"text": "kushkunal077"
},
{
"code": null,
"e": 8516,
"s": 8502,
"text": "23620uday2021"
},
{
"code": null,
"e": 8531,
"s": 8516,
"text": "Neural Network"
},
{
"code": null,
"e": 8536,
"s": 8531,
"text": "Misc"
},
{
"code": null,
"e": 8541,
"s": 8536,
"text": "Misc"
},
{
"code": null,
"e": 8546,
"s": 8541,
"text": "Misc"
},
{
"code": null,
"e": 8644,
"s": 8546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8655,
"s": 8644,
"text": "Hypervisor"
},
{
"code": null,
"e": 8691,
"s": 8655,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 8723,
"s": 8691,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 8739,
"s": 8723,
"text": "Cloud Computing"
},
{
"code": null,
"e": 8768,
"s": 8739,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 8793,
"s": 8768,
"text": "array::size() in C++ STL"
},
{
"code": null,
"e": 8828,
"s": 8793,
"text": "Characteristics of Cloud Computing"
},
{
"code": null,
"e": 8867,
"s": 8828,
"text": "Bubble Sort algorithm using JavaScript"
},
{
"code": null,
"e": 8897,
"s": 8867,
"text": "Introduction to Deep Learning"
}
] |
Groovy - xxxValue()
|
This method takes on the Number as the parameter and returns a primitive type based on the method which is invoked. Following are the list of methods available −
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
Parameters − No parameters required.
Return Value − The return value is the primitive type returned depending on the value function which is called.
Following is an example of the usage of the method values.
class Example {
static void main(String[] args) {
Integer x = 5;
// Converting the number to double primitive type
println(x.doubleValue());
// Converting the number to byte primitive type
println(x.byteValue());
// Converting the number to float primitive type
println(x.floatValue());
// Converting the number to long primitive type
println(x.longValue());
// Converting the number to short primitive type
println(x.shortValue());
// Converting the number to int primitive type
println(x.intValue());
}
}
When we run the above program, we will get the following result −
|
[
{
"code": null,
"e": 2534,
"s": 2372,
"text": "This method takes on the Number as the parameter and returns a primitive type based on the method which is invoked. Following are the list of methods available −"
},
{
"code": null,
"e": 2647,
"s": 2534,
"text": "byte byteValue() \nshort shortValue() \nint intValue() \nlong longValue() \nfloat floatValue() \ndouble doubleValue()"
},
{
"code": null,
"e": 2684,
"s": 2647,
"text": "Parameters − No parameters required."
},
{
"code": null,
"e": 2796,
"s": 2684,
"text": "Return Value − The return value is the primitive type returned depending on the value function which is called."
},
{
"code": null,
"e": 2855,
"s": 2796,
"text": "Following is an example of the usage of the method values."
},
{
"code": null,
"e": 3480,
"s": 2855,
"text": "class Example { \n static void main(String[] args) { \n Integer x = 5; \n\t\t\n // Converting the number to double primitive type\n println(x.doubleValue()); \n\t\t\n // Converting the number to byte primitive type \n println(x.byteValue()); \n\t\t\n // Converting the number to float primitive type \n println(x.floatValue());\n\t\t\n // Converting the number to long primitive type \n println(x.longValue()); \n\t\t\n // Converting the number to short primitive type \n println(x.shortValue()); \n\t\t\n // Converting the number to int primitive type \n println(x.intValue()); \n } \n}"
}
] |
Program to print half diamond Number-Star pattern
|
06 Jun, 2022
Given a number N which represents the number of rows. The task is to print a half diamond Number-Star pattern as shown in the below examples.Note: N is always an even number.Examples:
Input: N = 4
Output: 2*2
1
1
2*2
Input: N = 6
Output: 3*3*3
2*2
1
1
2*2
3*3*3
On carefully observing the above pattern, it can be broken down into two different triangles:
An upside down right angled triangle.
A normal right angled triangle.
For the first triangle pattern:
Run two loops, first will take care of the number of rows and other will take care of the ‘*’ and numbers being printed.
Inside the loops check whether the iterations of inner loop has reached to the given number of rows or not.
If yes, print only number, otherwise print ‘*’ and number both.
The same approach will be followed for the second triangle pattern with a slight change that here the condition will be checked where the inner iteration is equal to 0 or not.Below is the implementation of above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to print half diamond// number star pattern#include <iostream>using namespace std; // Function to print the given patternvoid printPattern(int r){ r = r / 2; int count = r; // loop to print upper half pattern for (int i = 0; i < r; i++) { for (int j = r; j > i; j--) { if (j != r) { cout << "*" << count; } else { cout << count; } } count--; cout << endl; } count++; // loop to print lower half pattern for (int i = 0; i < r; i++) { for (int j = 0; j <= i; j++) { if (j != 0) { cout << "*" << count; } else { cout << count; } } count++; cout << endl; }} // Driver codeint main(){ int n; n = 6; printPattern(n); return 0;}
// Java program to print half// diamond number star patternclass GFG{// Function to print// the given patternstatic void printPattern(int r){ r = r / 2; int count = r; // loop to print // upper half pattern for (int i = 0; i < r; i++) { for (int j = r; j > i; j--) { if (j != r) { System.out.print("*" + count); } else { System.out.print(count); } } count--; System.out.print("\n"); } count++; // loop to print lower // half pattern for (int i = 0; i < r; i++) { for (int j = 0; j <= i; j++) { if (j != 0) { System.out.print("*" + count); } else { System.out.print(count); } } count++; System.out.print("\n"); }} // Driver codepublic static void main(String [] args){ int n; n = 6; printPattern(n);}} // This code is contributed// by Smitha
# Python 3 program to# print half diamond# number star pattern # Function to print the# given patterndef printPattern(r) : r = r // 2 count = r # loop to print upper # half pattern for i in range(r) : for j in range(r, i, -1) : if j != r : print("*" + str(count), end = "") else : print(count, end = "") count -= 1 print() count += 1 # loop to print lower # half pattern for i in range(r) : for j in range(i + 1): if j != 0 : print("*" + str(count), end = "") else : print(count, end = "") count += 1 print() # Driver Codeif __name__ == "__main__" : n = 6 printPattern(n) # This code is contributed# by ANKITRAI1
// C++ program to print half diamond// number star pattern using System; public class GFG{// Function to print the given patternstatic void printPattern(int r){ r = r / 2; int count = r; // loop to print upper half pattern for (int i = 0; i < r; i++) { for (int j = r; j > i; j--) { if (j != r) { Console.Write("*" + count); } else { Console.Write( count); } } count--; Console.WriteLine(); } count++; // loop to print lower half pattern for (int i = 0; i < r; i++) { for (int j = 0; j <= i; j++) { if (j != 0) { Console.Write("*" + count); } else { Console.Write( count); } } count++; Console.WriteLine(); }} // Driver codepublic static void Main(){ int n; n = 6; printPattern(n); }}
<?php// PHP program to print half// diamond number star pattern // Function to print the// given patternfunction printPattern($r){ $r = $r / 2; $count = $r; // loop to print upper half pattern for ($i = 0; $i < $r; $i++) { for ($j = $r; $j > $i; $j--) { if ($j != $r) { echo "*" . $count; } else { echo $count; } } $count--; echo "\n"; } $count++; // loop to print lower half pattern for ($i = 0; $i < $r; $i++) { for ($j = 0; $j <= $i; $j++) { if ($j != 0) { echo "*" . $count; } else { echo $count; } } $count++; echo "\n"; }} // Driver code$n = 6; printPattern($n); // This code is contributed// by Arnab Kundu?>
<script> // JavaScript program to print half diamond // number star pattern // Function to print the given pattern function printPattern(r) { r = r / 2; var count = parseInt(r); // loop to print upper half pattern for (var i = 0; i < r; i++) { for (var j = r; j > i; j--) { if (j != r) { document.write("*" + count); } else { document.write(count); } } count--; document.write("<br>"); } count++; // loop to print lower half pattern for (var i = 0; i < r; i++) { for (var j = 0; j <= i; j++) { if (j != 0) { document.write("*" + count); } else { document.write(count); } } count++; document.write("<br>"); } } // Driver code var n; n = 6; printPattern(n); </script>
3*3*3
2*2
1
1
2*2
3*3*3
Time Complexity: O(r2), where r represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant.
Smitha Dinesh Semwal
tufan_gupta2000
andrew1234
ankthon
prataher
rdtank
tamanna17122007
pattern-printing
C++ Programs
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
C++ Program to check if a given String is Palindrome or not
How to find the minimum and maximum element of a Vector using STL in C++?
C++ Program for QuickSort
C Program to Swap two Numbers
cin in C++
Passing a function as a parameter in C++
Const keyword in C++
Enumerated Types or Enums in C++
Program to implement Singly Linked List in C++ using class
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "Given a number N which represents the number of rows. The task is to print a half diamond Number-Star pattern as shown in the below examples.Note: N is always an even number.Examples: "
},
{
"code": null,
"e": 361,
"s": 214,
"text": "Input: N = 4\nOutput: 2*2\n 1\n 1\n 2*2\n\nInput: N = 6\nOutput: 3*3*3\n 2*2\n 1\n 1\n 2*2\n 3*3*3"
},
{
"code": null,
"e": 459,
"s": 363,
"text": "On carefully observing the above pattern, it can be broken down into two different triangles: "
},
{
"code": null,
"e": 497,
"s": 459,
"text": "An upside down right angled triangle."
},
{
"code": null,
"e": 529,
"s": 497,
"text": "A normal right angled triangle."
},
{
"code": null,
"e": 563,
"s": 529,
"text": "For the first triangle pattern: "
},
{
"code": null,
"e": 684,
"s": 563,
"text": "Run two loops, first will take care of the number of rows and other will take care of the ‘*’ and numbers being printed."
},
{
"code": null,
"e": 792,
"s": 684,
"text": "Inside the loops check whether the iterations of inner loop has reached to the given number of rows or not."
},
{
"code": null,
"e": 856,
"s": 792,
"text": "If yes, print only number, otherwise print ‘*’ and number both."
},
{
"code": null,
"e": 1080,
"s": 856,
"text": "The same approach will be followed for the second triangle pattern with a slight change that here the condition will be checked where the inner iteration is equal to 0 or not.Below is the implementation of above approach: "
},
{
"code": null,
"e": 1084,
"s": 1080,
"text": "C++"
},
{
"code": null,
"e": 1089,
"s": 1084,
"text": "Java"
},
{
"code": null,
"e": 1098,
"s": 1089,
"text": "Python 3"
},
{
"code": null,
"e": 1101,
"s": 1098,
"text": "C#"
},
{
"code": null,
"e": 1105,
"s": 1101,
"text": "PHP"
},
{
"code": null,
"e": 1116,
"s": 1105,
"text": "Javascript"
},
{
"code": "// C++ program to print half diamond// number star pattern#include <iostream>using namespace std; // Function to print the given patternvoid printPattern(int r){ r = r / 2; int count = r; // loop to print upper half pattern for (int i = 0; i < r; i++) { for (int j = r; j > i; j--) { if (j != r) { cout << \"*\" << count; } else { cout << count; } } count--; cout << endl; } count++; // loop to print lower half pattern for (int i = 0; i < r; i++) { for (int j = 0; j <= i; j++) { if (j != 0) { cout << \"*\" << count; } else { cout << count; } } count++; cout << endl; }} // Driver codeint main(){ int n; n = 6; printPattern(n); return 0;}",
"e": 2013,
"s": 1116,
"text": null
},
{
"code": "// Java program to print half// diamond number star patternclass GFG{// Function to print// the given patternstatic void printPattern(int r){ r = r / 2; int count = r; // loop to print // upper half pattern for (int i = 0; i < r; i++) { for (int j = r; j > i; j--) { if (j != r) { System.out.print(\"*\" + count); } else { System.out.print(count); } } count--; System.out.print(\"\\n\"); } count++; // loop to print lower // half pattern for (int i = 0; i < r; i++) { for (int j = 0; j <= i; j++) { if (j != 0) { System.out.print(\"*\" + count); } else { System.out.print(count); } } count++; System.out.print(\"\\n\"); }} // Driver codepublic static void main(String [] args){ int n; n = 6; printPattern(n);}} // This code is contributed// by Smitha",
"e": 3076,
"s": 2013,
"text": null
},
{
"code": "# Python 3 program to# print half diamond# number star pattern # Function to print the# given patterndef printPattern(r) : r = r // 2 count = r # loop to print upper # half pattern for i in range(r) : for j in range(r, i, -1) : if j != r : print(\"*\" + str(count), end = \"\") else : print(count, end = \"\") count -= 1 print() count += 1 # loop to print lower # half pattern for i in range(r) : for j in range(i + 1): if j != 0 : print(\"*\" + str(count), end = \"\") else : print(count, end = \"\") count += 1 print() # Driver Codeif __name__ == \"__main__\" : n = 6 printPattern(n) # This code is contributed# by ANKITRAI1",
"e": 3944,
"s": 3076,
"text": null
},
{
"code": "// C++ program to print half diamond// number star pattern using System; public class GFG{// Function to print the given patternstatic void printPattern(int r){ r = r / 2; int count = r; // loop to print upper half pattern for (int i = 0; i < r; i++) { for (int j = r; j > i; j--) { if (j != r) { Console.Write(\"*\" + count); } else { Console.Write( count); } } count--; Console.WriteLine(); } count++; // loop to print lower half pattern for (int i = 0; i < r; i++) { for (int j = 0; j <= i; j++) { if (j != 0) { Console.Write(\"*\" + count); } else { Console.Write( count); } } count++; Console.WriteLine(); }} // Driver codepublic static void Main(){ int n; n = 6; printPattern(n); }}",
"e": 4891,
"s": 3944,
"text": null
},
{
"code": "<?php// PHP program to print half// diamond number star pattern // Function to print the// given patternfunction printPattern($r){ $r = $r / 2; $count = $r; // loop to print upper half pattern for ($i = 0; $i < $r; $i++) { for ($j = $r; $j > $i; $j--) { if ($j != $r) { echo \"*\" . $count; } else { echo $count; } } $count--; echo \"\\n\"; } $count++; // loop to print lower half pattern for ($i = 0; $i < $r; $i++) { for ($j = 0; $j <= $i; $j++) { if ($j != 0) { echo \"*\" . $count; } else { echo $count; } } $count++; echo \"\\n\"; }} // Driver code$n = 6; printPattern($n); // This code is contributed// by Arnab Kundu?>",
"e": 5804,
"s": 4891,
"text": null
},
{
"code": "<script> // JavaScript program to print half diamond // number star pattern // Function to print the given pattern function printPattern(r) { r = r / 2; var count = parseInt(r); // loop to print upper half pattern for (var i = 0; i < r; i++) { for (var j = r; j > i; j--) { if (j != r) { document.write(\"*\" + count); } else { document.write(count); } } count--; document.write(\"<br>\"); } count++; // loop to print lower half pattern for (var i = 0; i < r; i++) { for (var j = 0; j <= i; j++) { if (j != 0) { document.write(\"*\" + count); } else { document.write(count); } } count++; document.write(\"<br>\"); } } // Driver code var n; n = 6; printPattern(n); </script>",
"e": 6779,
"s": 5804,
"text": null
},
{
"code": null,
"e": 6803,
"s": 6779,
"text": "3*3*3\n2*2\n1\n1\n2*2\n3*3*3"
},
{
"code": null,
"e": 6936,
"s": 6805,
"text": "Time Complexity: O(r2), where r represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 6957,
"s": 6936,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 6973,
"s": 6957,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 6984,
"s": 6973,
"text": "andrew1234"
},
{
"code": null,
"e": 6992,
"s": 6984,
"text": "ankthon"
},
{
"code": null,
"e": 7001,
"s": 6992,
"text": "prataher"
},
{
"code": null,
"e": 7008,
"s": 7001,
"text": "rdtank"
},
{
"code": null,
"e": 7024,
"s": 7008,
"text": "tamanna17122007"
},
{
"code": null,
"e": 7041,
"s": 7024,
"text": "pattern-printing"
},
{
"code": null,
"e": 7054,
"s": 7041,
"text": "C++ Programs"
},
{
"code": null,
"e": 7071,
"s": 7054,
"text": "pattern-printing"
},
{
"code": null,
"e": 7169,
"s": 7071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7203,
"s": 7169,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 7263,
"s": 7203,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 7337,
"s": 7263,
"text": "How to find the minimum and maximum element of a Vector using STL in C++?"
},
{
"code": null,
"e": 7363,
"s": 7337,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 7393,
"s": 7363,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 7404,
"s": 7393,
"text": "cin in C++"
},
{
"code": null,
"e": 7445,
"s": 7404,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 7466,
"s": 7445,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 7499,
"s": 7466,
"text": "Enumerated Types or Enums in C++"
}
] |
First() and Last()Function in MS Access
|
14 Sep, 2020
1. First() Function :In MS Access, the First() function is used to return a field value from the first record in the result set returned by a query.
Syntax :
First(expr)
Parameter :
expr : It represents a string expression identifying the field that contains the data we want to use or an expression that performs a calculation using the data in that field.
Returns : It returns the first record in the result set.
Example-1 :
SELECT First(Emp_id) AS EmployeeId FROM Employee_Details;
Output :
Example-2 :
SELECT First(Emp_Name) AS FirstEmployee FROM Employee_Details;
Output :
2. Last() Function :In MS Access, the Last() function is used to return a field value from the last record in the result set returned by a query.
Syntax :
Last(expr)
Parameter :
expr : It represents a string expression identifying the field that contains the data we want to use or an expression that performs a calculation using the data in that field.
Returns : It returns the last record in the result set.
Example-2 :
SELECT Last(Emp_id) AS EmployeeId FROM Employee_Details;
Output :
Example-2 :
SELECT Last(Emp_Name) AS LastEmployee FROM Employee_Details;
Output :
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
SQL | GROUP BY
Window functions in SQL
SQL Correlated Subqueries
Difference between DELETE and TRUNCATE
SQL | Sub queries in From Clause
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "1. First() Function :In MS Access, the First() function is used to return a field value from the first record in the result set returned by a query."
},
{
"code": null,
"e": 186,
"s": 177,
"text": "Syntax :"
},
{
"code": null,
"e": 199,
"s": 186,
"text": "First(expr)\n"
},
{
"code": null,
"e": 211,
"s": 199,
"text": "Parameter :"
},
{
"code": null,
"e": 387,
"s": 211,
"text": "expr : It represents a string expression identifying the field that contains the data we want to use or an expression that performs a calculation using the data in that field."
},
{
"code": null,
"e": 444,
"s": 387,
"text": "Returns : It returns the first record in the result set."
},
{
"code": null,
"e": 456,
"s": 444,
"text": "Example-1 :"
},
{
"code": null,
"e": 515,
"s": 456,
"text": "SELECT First(Emp_id) AS EmployeeId FROM Employee_Details;\n"
},
{
"code": null,
"e": 524,
"s": 515,
"text": "Output :"
},
{
"code": null,
"e": 536,
"s": 524,
"text": "Example-2 :"
},
{
"code": null,
"e": 600,
"s": 536,
"text": "SELECT First(Emp_Name) AS FirstEmployee FROM Employee_Details;\n"
},
{
"code": null,
"e": 609,
"s": 600,
"text": "Output :"
},
{
"code": null,
"e": 755,
"s": 609,
"text": "2. Last() Function :In MS Access, the Last() function is used to return a field value from the last record in the result set returned by a query."
},
{
"code": null,
"e": 764,
"s": 755,
"text": "Syntax :"
},
{
"code": null,
"e": 776,
"s": 764,
"text": "Last(expr)\n"
},
{
"code": null,
"e": 788,
"s": 776,
"text": "Parameter :"
},
{
"code": null,
"e": 964,
"s": 788,
"text": "expr : It represents a string expression identifying the field that contains the data we want to use or an expression that performs a calculation using the data in that field."
},
{
"code": null,
"e": 1020,
"s": 964,
"text": "Returns : It returns the last record in the result set."
},
{
"code": null,
"e": 1032,
"s": 1020,
"text": "Example-2 :"
},
{
"code": null,
"e": 1090,
"s": 1032,
"text": "SELECT Last(Emp_id) AS EmployeeId FROM Employee_Details;\n"
},
{
"code": null,
"e": 1099,
"s": 1090,
"text": "Output :"
},
{
"code": null,
"e": 1111,
"s": 1099,
"text": "Example-2 :"
},
{
"code": null,
"e": 1173,
"s": 1111,
"text": "SELECT Last(Emp_Name) AS LastEmployee FROM Employee_Details;\n"
},
{
"code": null,
"e": 1182,
"s": 1173,
"text": "Output :"
},
{
"code": null,
"e": 1191,
"s": 1182,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1195,
"s": 1191,
"text": "SQL"
},
{
"code": null,
"e": 1199,
"s": 1195,
"text": "SQL"
},
{
"code": null,
"e": 1297,
"s": 1199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1363,
"s": 1297,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1387,
"s": 1363,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 1432,
"s": 1387,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 1464,
"s": 1432,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 1503,
"s": 1464,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 1518,
"s": 1503,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 1542,
"s": 1518,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1568,
"s": 1542,
"text": "SQL Correlated Subqueries"
},
{
"code": null,
"e": 1607,
"s": 1568,
"text": "Difference between DELETE and TRUNCATE"
}
] |
SARSA Reinforcement Learning
|
24 Jun, 2021
Prerequisites: Q-Learning techniqueSARSA algorithm is a slight variation of the popular Q-Learning algorithm. For a learning agent in any Reinforcement Learning algorithm it’s policy can be of two types:-
On Policy: In this, the learning agent learns the value function according to the current action derived from the policy currently being used.Off Policy: In this, the learning agent learns the value function according to the action derived from another policy.
On Policy: In this, the learning agent learns the value function according to the current action derived from the policy currently being used.
Off Policy: In this, the learning agent learns the value function according to the action derived from another policy.
Q-Learning technique is an Off Policy technique and uses the greedy approach to learn the Q-value. SARSA technique, on the other hand, is an On Policy and uses the action performed by the current policy to learn the Q-value.This difference is visible in the difference of the update statements for each technique:-
Q-Learning: SARSA:
Q-Learning:
SARSA:
Here, the update equation for SARSA depends on the current state, current action, reward obtained, next state and next action. This observation lead to the naming of the learning technique as SARSA stands for State Action Reward State Action which symbolizes the tuple (s, a, r, s’, a’).The following Python code demonstrates how to implement the SARSA algorithm using the OpenAI’s gym module to load the environment.Step 1: Importing the required libraries
Python3
import numpy as npimport gym
Step 2: Building the environmentHere, we will be using the ‘FrozenLake-v0’ environment which is preloaded into gym. You can read about the environment description here.
Python3
#Building the environmentenv = gym.make('FrozenLake-v0')
Step 3: Initializing different parameters
Python3
#Defining the different parametersepsilon = 0.9total_episodes = 10000max_steps = 100alpha = 0.85gamma = 0.95 #Initializing the Q-matrixQ = np.zeros((env.observation_space.n, env.action_space.n))
Step 4: Defining utility functions to be used in the learning process
Python3
#Function to choose the next actiondef choose_action(state): action=0 if np.random.uniform(0, 1) < epsilon: action = env.action_space.sample() else: action = np.argmax(Q[state, :]) return action #Function to learn the Q-valuedef update(state, state2, reward, action, action2): predict = Q[state, action] target = reward + gamma * Q[state2, action2] Q[state, action] = Q[state, action] + alpha * (target - predict)
Step 5: Training the learning agent
Python3
#Initializing the rewardreward=0 # Starting the SARSA learningfor episode in range(total_episodes): t = 0 state1 = env.reset() action1 = choose_action(state1) while t < max_steps: #Visualizing the training env.render() #Getting the next state state2, reward, done, info = env.step(action1) #Choosing the next action action2 = choose_action(state2) #Learning the Q-value update(state1, state2, reward, action1, action2) state1 = state2 action1 = action2 #Updating the respective vaLues t += 1 reward += 1 #If at the end of learning process if done: break
In the above output, the red mark determines the current position of the agent in the environment while the direction given in brackets gives the direction of movement that the agent will make next. Note that the agent stays at it’s position if goes out of bounds.Step 6: Evaluating the performance
Python3
#Evaluating the performanceprint ("Performance : ", reward/total_episodes) #Visualizing the Q-matrixprint(Q)
rajeev0719singh
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 261,
"s": 54,
"text": "Prerequisites: Q-Learning techniqueSARSA algorithm is a slight variation of the popular Q-Learning algorithm. For a learning agent in any Reinforcement Learning algorithm it’s policy can be of two types:- "
},
{
"code": null,
"e": 522,
"s": 261,
"text": "On Policy: In this, the learning agent learns the value function according to the current action derived from the policy currently being used.Off Policy: In this, the learning agent learns the value function according to the action derived from another policy."
},
{
"code": null,
"e": 665,
"s": 522,
"text": "On Policy: In this, the learning agent learns the value function according to the current action derived from the policy currently being used."
},
{
"code": null,
"e": 784,
"s": 665,
"text": "Off Policy: In this, the learning agent learns the value function according to the action derived from another policy."
},
{
"code": null,
"e": 1101,
"s": 784,
"text": "Q-Learning technique is an Off Policy technique and uses the greedy approach to learn the Q-value. SARSA technique, on the other hand, is an On Policy and uses the action performed by the current policy to learn the Q-value.This difference is visible in the difference of the update statements for each technique:- "
},
{
"code": null,
"e": 1121,
"s": 1101,
"text": "Q-Learning: SARSA: "
},
{
"code": null,
"e": 1134,
"s": 1121,
"text": "Q-Learning: "
},
{
"code": null,
"e": 1142,
"s": 1134,
"text": "SARSA: "
},
{
"code": null,
"e": 1601,
"s": 1142,
"text": "Here, the update equation for SARSA depends on the current state, current action, reward obtained, next state and next action. This observation lead to the naming of the learning technique as SARSA stands for State Action Reward State Action which symbolizes the tuple (s, a, r, s’, a’).The following Python code demonstrates how to implement the SARSA algorithm using the OpenAI’s gym module to load the environment.Step 1: Importing the required libraries "
},
{
"code": null,
"e": 1609,
"s": 1601,
"text": "Python3"
},
{
"code": "import numpy as npimport gym",
"e": 1638,
"s": 1609,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1638,
"text": "Step 2: Building the environmentHere, we will be using the ‘FrozenLake-v0’ environment which is preloaded into gym. You can read about the environment description here. "
},
{
"code": null,
"e": 1816,
"s": 1808,
"text": "Python3"
},
{
"code": "#Building the environmentenv = gym.make('FrozenLake-v0')",
"e": 1873,
"s": 1816,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1873,
"text": "Step 3: Initializing different parameters "
},
{
"code": null,
"e": 1924,
"s": 1916,
"text": "Python3"
},
{
"code": "#Defining the different parametersepsilon = 0.9total_episodes = 10000max_steps = 100alpha = 0.85gamma = 0.95 #Initializing the Q-matrixQ = np.zeros((env.observation_space.n, env.action_space.n))",
"e": 2119,
"s": 1924,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2119,
"text": "Step 4: Defining utility functions to be used in the learning process "
},
{
"code": null,
"e": 2198,
"s": 2190,
"text": "Python3"
},
{
"code": "#Function to choose the next actiondef choose_action(state): action=0 if np.random.uniform(0, 1) < epsilon: action = env.action_space.sample() else: action = np.argmax(Q[state, :]) return action #Function to learn the Q-valuedef update(state, state2, reward, action, action2): predict = Q[state, action] target = reward + gamma * Q[state2, action2] Q[state, action] = Q[state, action] + alpha * (target - predict)",
"e": 2647,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2684,
"s": 2647,
"text": "Step 5: Training the learning agent "
},
{
"code": null,
"e": 2692,
"s": 2684,
"text": "Python3"
},
{
"code": "#Initializing the rewardreward=0 # Starting the SARSA learningfor episode in range(total_episodes): t = 0 state1 = env.reset() action1 = choose_action(state1) while t < max_steps: #Visualizing the training env.render() #Getting the next state state2, reward, done, info = env.step(action1) #Choosing the next action action2 = choose_action(state2) #Learning the Q-value update(state1, state2, reward, action1, action2) state1 = state2 action1 = action2 #Updating the respective vaLues t += 1 reward += 1 #If at the end of learning process if done: break",
"e": 3413,
"s": 2692,
"text": null
},
{
"code": null,
"e": 3713,
"s": 3413,
"text": "In the above output, the red mark determines the current position of the agent in the environment while the direction given in brackets gives the direction of movement that the agent will make next. Note that the agent stays at it’s position if goes out of bounds.Step 6: Evaluating the performance "
},
{
"code": null,
"e": 3721,
"s": 3713,
"text": "Python3"
},
{
"code": "#Evaluating the performanceprint (\"Performance : \", reward/total_episodes) #Visualizing the Q-matrixprint(Q)",
"e": 3830,
"s": 3721,
"text": null
},
{
"code": null,
"e": 3846,
"s": 3830,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 3863,
"s": 3846,
"text": "Machine Learning"
},
{
"code": null,
"e": 3870,
"s": 3863,
"text": "Python"
},
{
"code": null,
"e": 3887,
"s": 3870,
"text": "Machine Learning"
},
{
"code": null,
"e": 3985,
"s": 3887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4025,
"s": 3985,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 4049,
"s": 4025,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 4087,
"s": 4049,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4128,
"s": 4087,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4161,
"s": 4128,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4189,
"s": 4161,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4211,
"s": 4189,
"text": "Python map() function"
},
{
"code": null,
"e": 4261,
"s": 4211,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4279,
"s": 4261,
"text": "Python Dictionary"
}
] |
objdump - Unix, Linux Command
|
objfile... are the object files to be examined. When you
specify archives, objdump shows information on each of the member
object files.
For example,
objdump -b oasys -m vax -h fu.o
displays summary information from the section headers (-h) of
fu.o, which is explicitly identified (-m) as a VAX object
file in the format produced by Oasys compilers. You can list the
formats available with the -i option.
File segments may be relocated to nonstandard addresses, for example by
using the -Ttext, -Tdata, or -Tbss options to
ld. However, some object file formats, such as a.out, do not
store the starting address of the file segments. In those situations,
although ld relocates the sections correctly, using objdump
-h to list the file section headers cannot show the correct addresses.
Instead, it shows the usual addresses, which are implicit for the
target.
If the target is an ARM architecture then this switch can be used to
select which register name set is used during disassembler. Specifying
-M reg-names-std (the default) will select the register names as
used in ARM’s instruction set documentation, but with register 13 called
’sp’, register 14 called ’lr’ and register 15 called ’pc’. Specifying
-M reg-names-apcs will select the name set used by the ARM
Procedure Call Standard, whilst specifying -M reg-names-raw will
just use r followed by the register number.
There are also two variants on the APCS register naming scheme enabled
by -M reg-names-atpcs and -M reg-names-special-atpcs which
use the ARM/Thumb Procedure Call Standard naming conventions. (Either
with the normal register names or the special register names).
This option can also be used for ARM architectures to force the
disassembler to interpret all instructions as Thumb instructions by
using the switch --disassembler-options=force-thumb. This can be
useful when attempting to disassemble thumb code produced by other
compilers.
For the x86, some of the options duplicate functions of the -m
switch, but allow finer grained control. Multiple selections from the
following may be specified as a comma separated string.
x86-64, i386 and i8086 select disassembly for
the given architecture. intel and att select between
intel syntax mode and AT&T syntax mode. addr32,
addr16, data32 and data16 specify the default
address size and operand size. These four options will be overridden if
x86-64, i386 or i8086 appear later in the
option string. Lastly, suffix, when in AT&T mode,
instructs the disassembler to print a mnemonic suffix even when the
suffix could be inferred by the operands.
For PPC, booke, booke32 and booke64 select
disassembly of BookE instructions. 32 and 64 select
PowerPC and PowerPC64 disassembly, respectively. e300 selects
disassembly for the e300 family.
For MIPS, this option controls the printing of instruction mnemonic
names and register names in disassembled instructions. Multiple
selections from the following may be specified as a comma separated
string, and invalid options are ignored:
For any of the options listed above, ABI or
ARCH may be specified as numeric to have numbers printed
rather than names, for the selected types of registers.
You can list the available values of ABI and ARCH using
the --help option.
For VAX, you can specify function entry addresses with -M
entry:0xf00ba. You can use this multiple times to properly
disassemble VAX binary files that don’t contain symbol tables (like
ROM dumps). In these cases, the function entry mask would otherwise
be decoded as VAX instructions, which would probably lead the rest
of the function being wrongly disassembled.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including a
backslash) may be included by prefixing the character to be included
with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled GNU Free Documentation License.
|
[
{
"code": null,
"e": 10851,
"s": 10711,
"text": "\nobjfile... are the object files to be examined. When you\nspecify archives, objdump shows information on each of the member\nobject files.\n"
},
{
"code": null,
"e": 10867,
"s": 10851,
"text": "\n\nFor example,\n"
},
{
"code": null,
"e": 10912,
"s": 10870,
"text": "\n objdump -b oasys -m vax -h fu.o\n"
},
{
"code": null,
"e": 11139,
"s": 10912,
"text": "\n\ndisplays summary information from the section headers (-h) of\nfu.o, which is explicitly identified (-m) as a VAX object\nfile in the format produced by Oasys compilers. You can list the\nformats available with the -i option.\n"
},
{
"code": null,
"e": 11598,
"s": 11139,
"text": "\n\nFile segments may be relocated to nonstandard addresses, for example by\nusing the -Ttext, -Tdata, or -Tbss options to\nld. However, some object file formats, such as a.out, do not\nstore the starting address of the file segments. In those situations,\nalthough ld relocates the sections correctly, using objdump\n-h to list the file section headers cannot show the correct addresses.\nInstead, it shows the usual addresses, which are implicit for the\ntarget.\n"
},
{
"code": null,
"e": 12119,
"s": 11598,
"text": "\n\nIf the target is an ARM architecture then this switch can be used to\nselect which register name set is used during disassembler. Specifying\n-M reg-names-std (the default) will select the register names as\nused in ARM’s instruction set documentation, but with register 13 called\n’sp’, register 14 called ’lr’ and register 15 called ’pc’. Specifying\n-M reg-names-apcs will select the name set used by the ARM\nProcedure Call Standard, whilst specifying -M reg-names-raw will\njust use r followed by the register number.\n"
},
{
"code": null,
"e": 12386,
"s": 12119,
"text": "\n\nThere are also two variants on the APCS register naming scheme enabled\nby -M reg-names-atpcs and -M reg-names-special-atpcs which\nuse the ARM/Thumb Procedure Call Standard naming conventions. (Either\nwith the normal register names or the special register names).\n"
},
{
"code": null,
"e": 12665,
"s": 12386,
"text": "\n\nThis option can also be used for ARM architectures to force the\ndisassembler to interpret all instructions as Thumb instructions by\nusing the switch --disassembler-options=force-thumb. This can be\nuseful when attempting to disassemble thumb code produced by other\ncompilers.\n"
},
{
"code": null,
"e": 13329,
"s": 12665,
"text": "\n\nFor the x86, some of the options duplicate functions of the -m\nswitch, but allow finer grained control. Multiple selections from the\nfollowing may be specified as a comma separated string.\nx86-64, i386 and i8086 select disassembly for\nthe given architecture. intel and att select between\nintel syntax mode and AT&T syntax mode. addr32,\naddr16, data32 and data16 specify the default\naddress size and operand size. These four options will be overridden if\nx86-64, i386 or i8086 appear later in the\noption string. Lastly, suffix, when in AT&T mode,\ninstructs the disassembler to print a mnemonic suffix even when the\nsuffix could be inferred by the operands.\n"
},
{
"code": null,
"e": 13524,
"s": 13329,
"text": "\n\nFor PPC, booke, booke32 and booke64 select\ndisassembly of BookE instructions. 32 and 64 select\nPowerPC and PowerPC64 disassembly, respectively. e300 selects\ndisassembly for the e300 family.\n"
},
{
"code": null,
"e": 13770,
"s": 13524,
"text": "\n\nFor MIPS, this option controls the printing of instruction mnemonic\nnames and register names in disassembled instructions. Multiple\nselections from the following may be specified as a comma separated\nstring, and invalid options are ignored:\n\n"
},
{
"code": null,
"e": 14005,
"s": 13770,
"text": "\n\nFor any of the options listed above, ABI or\nARCH may be specified as numeric to have numbers printed\nrather than names, for the selected types of registers.\nYou can list the available values of ABI and ARCH using\nthe --help option.\n"
},
{
"code": null,
"e": 14374,
"s": 14005,
"text": "\n\nFor VAX, you can specify function entry addresses with -M\nentry:0xf00ba. You can use this multiple times to properly\ndisassemble VAX binary files that don’t contain symbol tables (like\nROM dumps). In these cases, the function entry mask would otherwise\nbe decoded as VAX instructions, which would probably lead the rest\nof the function being wrongly disassembled.\n"
},
{
"code": null,
"e": 14761,
"s": 14374,
"text": "\n\nOptions in file are separated by whitespace. A whitespace\ncharacter may be included in an option by surrounding the entire\noption in either single or double quotes. Any character (including a\nbackslash) may be included by prefixing the character to be included\nwith a backslash. The file may itself contain additional\n@file options; any such options will be processed recursively.\n"
}
] |
Program to generate an array having convolution of two given arrays
|
04 Aug, 2021
Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to construct a convolution array C[] of size (N + M – 1).
The convolution of 2 arrays is defined as C[i + j] = ∑(a[i] * b[j]) for every i and j.
Note: If the value for any index becomes very large, then print it to modulo 998244353.
Examples:
Input: A[] = {1, 2, 3, 4}, B[] = {5, 6, 7, 8, 9}Output: {5, 16, 34, 60, 70, 70, 59, 36}Explanation:Size of array, C[] = N + M – 1 = 8.C[0] = A[0] * B[0] = 1 * 5 = 5C[1] = A[0] * B[1] + A[1] * B[0] = 1 * 6 + 2 * 5 = 16C[2] = A[0] * B[2] + A[1] * B[1] + A[2] * B[0] = 1 * 7 + 2 * 6 + 3 * 5 = 34Similarly, C[3] = 60, C[4] = 70, C[5] = 70, C[6] = 59, C[7] = 36.
Input: A[] = {10000000}, B[] = {10000000}Output: {871938225}Explanation:Size of array, C[] = N + M – 1 = 1.C[0] = A[0] * B[0] = (10000000 * 10000000) % 998244353 = 871938225
Naive Approach: In the convolution array, each term C[i + j] = (a[i] * b[j]) % 998244353. Therefore, the simplest approach is to iterate over both the arrays A[] and B[] using two nested loops to find the resulting convoluted array C[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;constexpr int MOD = 998244353; // Function to generate a convolution// array of two given arraysvoid findConvolution(const vector<int>& a, const vector<int>& b){ // Stores the size of arrays int n = a.size(), m = b.size(); // Stores the final array vector<long long> c(n + m - 1); // Traverse the two given arrays for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Update the convolution array c[i + j] += 1LL*(a[i] * b[j]) % MOD; } } // Print the convolution array c[] for (int k = 0; k < c.size(); ++k) { c[k] %= MOD; cout << c[k] << " "; }} // Driver Codeint main(){ vector<int> A = { 1, 2, 3, 4 }; vector<int> B = { 5, 6, 7, 8, 9 }; findConvolution(A, B); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ static int MOD = 998244353; // Function to generate a convolution// array of two given arraysstatic void findConvolution(int[] a, int[] b){ // Stores the size of arrays int n = a.length, m = b.length; // Stores the final array int[] c = new int[(n + m - 1)]; // Traverse the two given arrays for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { // Update the convolution array c[i + j] += (a[i] * b[j]) % MOD; } } // Print the convolution array c[] for(int k = 0; k < c.length; ++k) { c[k] %= MOD; System.out.print(c[k] + " "); }} // Driver Codepublic static void main(String args[]){ int[] A = { 1, 2, 3, 4 }; int[] B = { 5, 6, 7, 8, 9 }; findConvolution(A, B);}} // This code is contributed by souravghosh0416
# Python3 program for the above approachMOD = 998244353 # Function to generate a convolution# array of two given arraysdef findConvolution(a, b): global MOD # Stores the size of arrays n, m = len(a), len(b) # Stores the final array c = [0] * (n + m - 1) # Traverse the two given arrays for i in range(n): for j in range(m): # Update the convolution array c[i + j] += (a[i] * b[j]) % MOD # Print the convolution array c[] for k in range(len(c)): c[k] %= MOD print(c[k], end = " ") # Driver Codeif __name__ == '__main__': A = [1, 2, 3, 4] B = [5, 6, 7, 8, 9] findConvolution(A, B) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ static int MOD = 998244353; // Function to generate a convolution// array of two given arraysstatic void findConvolution(int[] a, int[] b){ // Stores the size of arrays int n = a.Length, m = b.Length; // Stores the final array int[] c = new int[(n + m - 1)]; // Traverse the two given arrays for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Update the convolution array c[i + j] += (a[i] * b[j]) % MOD; } } // Print the convolution array c[] for (int k = 0; k < c.Length; ++k) { c[k] %= MOD; Console.Write(c[k] + " "); }} // Driver Codepublic static void Main(String[] args){ int[] A = { 1, 2, 3, 4 }; int[] B = { 5, 6, 7, 8, 9 }; findConvolution(A, B);}} // This code is contributed by code_hunt.
<script> // Javascript program for the above approach let MOD = 998244353; // Function to generate a convolution// array of two given arraysfunction findConvolution(a, b){ // Stores the size of arrays let n = a.length, m = b.length; // Stores the final array let c = []; for(let i = 0; i < n + m - 1; ++i) { c[i] = 0; } // Traverse the two given arrays for(let i = 0; i < n; ++i) { for(let j = 0; j < m; ++j) { // Update the convolution array c[i + j] += (a[i] * b[j]) % MOD; } } // Print the convolution array c[] for(let k = 0; k < c.length; ++k) { c[k] %= MOD; document.write(c[k] + " "); }} // Driver Code let A = [ 1, 2, 3, 4 ]; let B = [ 5, 6, 7, 8, 9 ]; findConvolution(A, B); </script>
5 16 34 60 70 70 59 36
Time Complexity: O(N*M)Auxiliary Space: O(N+M)
Efficient Approach: To optimize the above approach, the idea is to use the Number-Theoretic Transform (NTT) which is similar to Fast Fourier transform (FFT) for polynomial multiplication, which can work under modulo operations. The problem can be solved by using the same concept of iterative FFT to perform NTT on the given arrays as the same properties hold for the Nth roots of unity in modular arithmetic.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; #define ll long long const ll mod = 998244353, maxn = 3e6;ll a[maxn], b[maxn]; // Iterative FFT function to compute// the DFT of given coefficient vectorvoid fft(ll w0, ll n, ll* a){ // Do bit reversal of the given array for (ll i = 0, j = 0; i < n; i++) { // Swap a[i] and a[j] if (i < j) swap(a[i], a[j]); // Right Shift N by 1 ll bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; } // Perform the iterative FFT for (ll len = 2; len <= n; len <<= 1) { ll wlen = w0; for (ll aux = n; aux > len; aux >>= 1) { wlen = wlen * wlen % mod; } for (ll bat = 0; bat + len <= n; bat += len) { for (ll i = bat, w = 1; i < bat + len / 2; i++, w = w * wlen % mod) { ll u = a[i], v = w * a[i + len / 2] % mod; // Update the value of a[i] a[i] = (u + v) % mod, // Update the value // of a[i + len/2] a[i + len / 2] = ((u - v) % mod + mod) % mod; } } }} // Function to find (a ^ x) % modll binpow(ll a, ll x){ // Stores the result of a ^ x ll ans = 1; // Iterate over the value of x for (; x; x /= 2, a = a * a % mod) { // If x is odd if (x & 1) ans = ans * a % mod; } // Return the resultant value return ans;} // Function to find the// inverse of a % modll inv(ll a) { return binpow(a, mod - 2); } // Function to find the// convolution of two arraysvoid findConvolution(ll a[], ll b[], ll n, ll m){ // Stores the first power of 2 // greater than or equal to n + m ll _n = 1ll << 64 - __builtin_clzll(n + m); // Stores the primitive root ll w = 15311432; for (ll aux = 1 << 23; aux > _n; aux >>= 1) w = w * w % mod; // Convert arrays a[] and // b[] to point value form fft(w, _n, a); fft(w, _n, b); // Perform multiplication for (ll i = 0; i < _n; i++) a[i] = a[i] * b[i] % mod; // Perform inverse fft to // recover final array fft(inv(w), _n, a); for (ll i = 0; i < _n; i++) a[i] = a[i] * inv(_n) % mod; // Print the convolution for (ll i = 0; i < n + m - 1; i++) cout << a[i] << " ";} // Driver Codeint main(){ // Given size of the arrays ll N = 4, M = 5; // Fill the arrays for (ll i = 0; i < N; i++) a[i] = i + 1; for (ll i = 0; i < M; i++) b[i] = 5 + i; findConvolution(a, b, N, M); return 0;}
5 16 34 60 70 70 59 36
Time Complexity: O(N*log(N))Auxiliary Space: O(N + M)
mohit kumar 29
code_hunt
souravghosh0416
avijitmondal1998
gabaa406
Technical Scripter 2020
Arrays
Mathematical
Technical Scripter
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
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
Coin Change | DP-7
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to construct a convolution array C[] of size (N + M – 1). "
},
{
"code": null,
"e": 261,
"s": 173,
"text": "The convolution of 2 arrays is defined as C[i + j] = ∑(a[i] * b[j]) for every i and j. "
},
{
"code": null,
"e": 349,
"s": 261,
"text": "Note: If the value for any index becomes very large, then print it to modulo 998244353."
},
{
"code": null,
"e": 359,
"s": 349,
"text": "Examples:"
},
{
"code": null,
"e": 717,
"s": 359,
"text": "Input: A[] = {1, 2, 3, 4}, B[] = {5, 6, 7, 8, 9}Output: {5, 16, 34, 60, 70, 70, 59, 36}Explanation:Size of array, C[] = N + M – 1 = 8.C[0] = A[0] * B[0] = 1 * 5 = 5C[1] = A[0] * B[1] + A[1] * B[0] = 1 * 6 + 2 * 5 = 16C[2] = A[0] * B[2] + A[1] * B[1] + A[2] * B[0] = 1 * 7 + 2 * 6 + 3 * 5 = 34Similarly, C[3] = 60, C[4] = 70, C[5] = 70, C[6] = 59, C[7] = 36."
},
{
"code": null,
"e": 891,
"s": 717,
"text": "Input: A[] = {10000000}, B[] = {10000000}Output: {871938225}Explanation:Size of array, C[] = N + M – 1 = 1.C[0] = A[0] * B[0] = (10000000 * 10000000) % 998244353 = 871938225"
},
{
"code": null,
"e": 1128,
"s": 891,
"text": "Naive Approach: In the convolution array, each term C[i + j] = (a[i] * b[j]) % 998244353. Therefore, the simplest approach is to iterate over both the arrays A[] and B[] using two nested loops to find the resulting convoluted array C[]."
},
{
"code": null,
"e": 1179,
"s": 1128,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1183,
"s": 1179,
"text": "C++"
},
{
"code": null,
"e": 1188,
"s": 1183,
"text": "Java"
},
{
"code": null,
"e": 1196,
"s": 1188,
"text": "Python3"
},
{
"code": null,
"e": 1199,
"s": 1196,
"text": "C#"
},
{
"code": null,
"e": 1210,
"s": 1199,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;constexpr int MOD = 998244353; // Function to generate a convolution// array of two given arraysvoid findConvolution(const vector<int>& a, const vector<int>& b){ // Stores the size of arrays int n = a.size(), m = b.size(); // Stores the final array vector<long long> c(n + m - 1); // Traverse the two given arrays for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Update the convolution array c[i + j] += 1LL*(a[i] * b[j]) % MOD; } } // Print the convolution array c[] for (int k = 0; k < c.size(); ++k) { c[k] %= MOD; cout << c[k] << \" \"; }} // Driver Codeint main(){ vector<int> A = { 1, 2, 3, 4 }; vector<int> B = { 5, 6, 7, 8, 9 }; findConvolution(A, B); return 0;}",
"e": 2106,
"s": 1210,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ static int MOD = 998244353; // Function to generate a convolution// array of two given arraysstatic void findConvolution(int[] a, int[] b){ // Stores the size of arrays int n = a.length, m = b.length; // Stores the final array int[] c = new int[(n + m - 1)]; // Traverse the two given arrays for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { // Update the convolution array c[i + j] += (a[i] * b[j]) % MOD; } } // Print the convolution array c[] for(int k = 0; k < c.length; ++k) { c[k] %= MOD; System.out.print(c[k] + \" \"); }} // Driver Codepublic static void main(String args[]){ int[] A = { 1, 2, 3, 4 }; int[] B = { 5, 6, 7, 8, 9 }; findConvolution(A, B);}} // This code is contributed by souravghosh0416",
"e": 3045,
"s": 2106,
"text": null
},
{
"code": "# Python3 program for the above approachMOD = 998244353 # Function to generate a convolution# array of two given arraysdef findConvolution(a, b): global MOD # Stores the size of arrays n, m = len(a), len(b) # Stores the final array c = [0] * (n + m - 1) # Traverse the two given arrays for i in range(n): for j in range(m): # Update the convolution array c[i + j] += (a[i] * b[j]) % MOD # Print the convolution array c[] for k in range(len(c)): c[k] %= MOD print(c[k], end = \" \") # Driver Codeif __name__ == '__main__': A = [1, 2, 3, 4] B = [5, 6, 7, 8, 9] findConvolution(A, B) # This code is contributed by mohit kumar 29",
"e": 3784,
"s": 3045,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ static int MOD = 998244353; // Function to generate a convolution// array of two given arraysstatic void findConvolution(int[] a, int[] b){ // Stores the size of arrays int n = a.Length, m = b.Length; // Stores the final array int[] c = new int[(n + m - 1)]; // Traverse the two given arrays for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Update the convolution array c[i + j] += (a[i] * b[j]) % MOD; } } // Print the convolution array c[] for (int k = 0; k < c.Length; ++k) { c[k] %= MOD; Console.Write(c[k] + \" \"); }} // Driver Codepublic static void Main(String[] args){ int[] A = { 1, 2, 3, 4 }; int[] B = { 5, 6, 7, 8, 9 }; findConvolution(A, B);}} // This code is contributed by code_hunt.",
"e": 4687,
"s": 3784,
"text": null
},
{
"code": "<script> // Javascript program for the above approach let MOD = 998244353; // Function to generate a convolution// array of two given arraysfunction findConvolution(a, b){ // Stores the size of arrays let n = a.length, m = b.length; // Stores the final array let c = []; for(let i = 0; i < n + m - 1; ++i) { c[i] = 0; } // Traverse the two given arrays for(let i = 0; i < n; ++i) { for(let j = 0; j < m; ++j) { // Update the convolution array c[i + j] += (a[i] * b[j]) % MOD; } } // Print the convolution array c[] for(let k = 0; k < c.length; ++k) { c[k] %= MOD; document.write(c[k] + \" \"); }} // Driver Code let A = [ 1, 2, 3, 4 ]; let B = [ 5, 6, 7, 8, 9 ]; findConvolution(A, B); </script>",
"e": 5531,
"s": 4687,
"text": null
},
{
"code": null,
"e": 5554,
"s": 5531,
"text": "5 16 34 60 70 70 59 36"
},
{
"code": null,
"e": 5603,
"s": 5556,
"text": "Time Complexity: O(N*M)Auxiliary Space: O(N+M)"
},
{
"code": null,
"e": 6014,
"s": 5603,
"text": "Efficient Approach: To optimize the above approach, the idea is to use the Number-Theoretic Transform (NTT) which is similar to Fast Fourier transform (FFT) for polynomial multiplication, which can work under modulo operations. The problem can be solved by using the same concept of iterative FFT to perform NTT on the given arrays as the same properties hold for the Nth roots of unity in modular arithmetic. "
},
{
"code": null,
"e": 6065,
"s": 6014,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 6069,
"s": 6065,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; #define ll long long const ll mod = 998244353, maxn = 3e6;ll a[maxn], b[maxn]; // Iterative FFT function to compute// the DFT of given coefficient vectorvoid fft(ll w0, ll n, ll* a){ // Do bit reversal of the given array for (ll i = 0, j = 0; i < n; i++) { // Swap a[i] and a[j] if (i < j) swap(a[i], a[j]); // Right Shift N by 1 ll bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; } // Perform the iterative FFT for (ll len = 2; len <= n; len <<= 1) { ll wlen = w0; for (ll aux = n; aux > len; aux >>= 1) { wlen = wlen * wlen % mod; } for (ll bat = 0; bat + len <= n; bat += len) { for (ll i = bat, w = 1; i < bat + len / 2; i++, w = w * wlen % mod) { ll u = a[i], v = w * a[i + len / 2] % mod; // Update the value of a[i] a[i] = (u + v) % mod, // Update the value // of a[i + len/2] a[i + len / 2] = ((u - v) % mod + mod) % mod; } } }} // Function to find (a ^ x) % modll binpow(ll a, ll x){ // Stores the result of a ^ x ll ans = 1; // Iterate over the value of x for (; x; x /= 2, a = a * a % mod) { // If x is odd if (x & 1) ans = ans * a % mod; } // Return the resultant value return ans;} // Function to find the// inverse of a % modll inv(ll a) { return binpow(a, mod - 2); } // Function to find the// convolution of two arraysvoid findConvolution(ll a[], ll b[], ll n, ll m){ // Stores the first power of 2 // greater than or equal to n + m ll _n = 1ll << 64 - __builtin_clzll(n + m); // Stores the primitive root ll w = 15311432; for (ll aux = 1 << 23; aux > _n; aux >>= 1) w = w * w % mod; // Convert arrays a[] and // b[] to point value form fft(w, _n, a); fft(w, _n, b); // Perform multiplication for (ll i = 0; i < _n; i++) a[i] = a[i] * b[i] % mod; // Perform inverse fft to // recover final array fft(inv(w), _n, a); for (ll i = 0; i < _n; i++) a[i] = a[i] * inv(_n) % mod; // Print the convolution for (ll i = 0; i < n + m - 1; i++) cout << a[i] << \" \";} // Driver Codeint main(){ // Given size of the arrays ll N = 4, M = 5; // Fill the arrays for (ll i = 0; i < N; i++) a[i] = i + 1; for (ll i = 0; i < M; i++) b[i] = 5 + i; findConvolution(a, b, N, M); return 0;}",
"e": 8711,
"s": 6069,
"text": null
},
{
"code": null,
"e": 8734,
"s": 8711,
"text": "5 16 34 60 70 70 59 36"
},
{
"code": null,
"e": 8790,
"s": 8736,
"text": "Time Complexity: O(N*log(N))Auxiliary Space: O(N + M)"
},
{
"code": null,
"e": 8807,
"s": 8792,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8817,
"s": 8807,
"text": "code_hunt"
},
{
"code": null,
"e": 8833,
"s": 8817,
"text": "souravghosh0416"
},
{
"code": null,
"e": 8850,
"s": 8833,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 8859,
"s": 8850,
"text": "gabaa406"
},
{
"code": null,
"e": 8883,
"s": 8859,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8890,
"s": 8883,
"text": "Arrays"
},
{
"code": null,
"e": 8903,
"s": 8890,
"text": "Mathematical"
},
{
"code": null,
"e": 8922,
"s": 8903,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8929,
"s": 8922,
"text": "Arrays"
},
{
"code": null,
"e": 8942,
"s": 8929,
"text": "Mathematical"
},
{
"code": null,
"e": 9040,
"s": 8942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9108,
"s": 9040,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9152,
"s": 9108,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9184,
"s": 9152,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9232,
"s": 9184,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9246,
"s": 9232,
"text": "Linear Search"
},
{
"code": null,
"e": 9289,
"s": 9246,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9349,
"s": 9289,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9364,
"s": 9349,
"text": "C++ Data Types"
},
{
"code": null,
"e": 9388,
"s": 9364,
"text": "Merge two sorted arrays"
}
] |
ISO 9000 Certification in Software Engineering
|
23 Nov, 2020
The International organization for Standardization is a world wide federation of national standard bodies. The International standards organization (ISO) is a standard which serves as a for contract between independent parties. It specifies guidelines for development of quality system.
Quality system of an organization means the various activities related to its products or services. Standard of ISO addresses to both aspects i.e. operational and organizational aspects which includes responsibilities, reporting etc. An ISO 9000 standard contains set of guidelines of production process without considering product itself.
ISO 9000 Certification
Why ISO Certification required by Software Industry?There are several reasons why software industry must get an ISO certification. Some of reasons are as follows :
This certification has become a standards for international bidding.
It helps in designing high-quality repeatable software products.
It emphasis need for proper documentation.
It facilitates development of optimal processes and totally quality measurements.
Features of ISO 9001 Requirements :
Document control –All documents concerned with the development of a software product should be properly managed and controlled.
Planning –Proper plans should be prepared and monitored.
Review –For effectiveness and correctness all important documents across all phases should be independently checked and reviewed .
Testing –The product should be tested against specification.
Organizational Aspects –Various organizational aspects should be addressed e.g., management reporting of the quality team.
Advantages of ISO 9000 Certification :Some of the advantages of the ISO 9000 certification process are following :
Business ISO-9000 certification forces a corporation to specialize in “how they are doing business”. Each procedure and work instruction must be documented and thus becomes a springboard for continuous improvement.
Employees morale is increased as they’re asked to require control of their processes and document their work processes
Better products and services result from continuous improvement process.
Increased employee participation, involvement, awareness and systematic employee training are reduced problems.
Shortcomings of ISO 9000 Certification :Some of the shortcoming of the ISO 9000 certification process are following :
ISO 9000 does not give any guideline for defining an appropriate process and does not give guarantee for high quality process.
ISO 9000 certification process have no international accreditation agency exists.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unit Testing | Software Testing
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Difference between Spring and Spring Boot
Software Engineering | Requirements Engineering Process
Software Testing Life Cycle (STLC)
Difference between IAAS, PAAS and SAAS
Equivalence Partitioning Method
Software Engineering | SDLC V-Model
Levels in Data Flow Diagrams (DFD)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 341,
"s": 54,
"text": "The International organization for Standardization is a world wide federation of national standard bodies. The International standards organization (ISO) is a standard which serves as a for contract between independent parties. It specifies guidelines for development of quality system."
},
{
"code": null,
"e": 681,
"s": 341,
"text": "Quality system of an organization means the various activities related to its products or services. Standard of ISO addresses to both aspects i.e. operational and organizational aspects which includes responsibilities, reporting etc. An ISO 9000 standard contains set of guidelines of production process without considering product itself."
},
{
"code": null,
"e": 704,
"s": 681,
"text": "ISO 9000 Certification"
},
{
"code": null,
"e": 868,
"s": 704,
"text": "Why ISO Certification required by Software Industry?There are several reasons why software industry must get an ISO certification. Some of reasons are as follows :"
},
{
"code": null,
"e": 937,
"s": 868,
"text": "This certification has become a standards for international bidding."
},
{
"code": null,
"e": 1002,
"s": 937,
"text": "It helps in designing high-quality repeatable software products."
},
{
"code": null,
"e": 1045,
"s": 1002,
"text": "It emphasis need for proper documentation."
},
{
"code": null,
"e": 1127,
"s": 1045,
"text": "It facilitates development of optimal processes and totally quality measurements."
},
{
"code": null,
"e": 1163,
"s": 1127,
"text": "Features of ISO 9001 Requirements :"
},
{
"code": null,
"e": 1291,
"s": 1163,
"text": "Document control –All documents concerned with the development of a software product should be properly managed and controlled."
},
{
"code": null,
"e": 1348,
"s": 1291,
"text": "Planning –Proper plans should be prepared and monitored."
},
{
"code": null,
"e": 1479,
"s": 1348,
"text": "Review –For effectiveness and correctness all important documents across all phases should be independently checked and reviewed ."
},
{
"code": null,
"e": 1540,
"s": 1479,
"text": "Testing –The product should be tested against specification."
},
{
"code": null,
"e": 1663,
"s": 1540,
"text": "Organizational Aspects –Various organizational aspects should be addressed e.g., management reporting of the quality team."
},
{
"code": null,
"e": 1778,
"s": 1663,
"text": "Advantages of ISO 9000 Certification :Some of the advantages of the ISO 9000 certification process are following :"
},
{
"code": null,
"e": 1993,
"s": 1778,
"text": "Business ISO-9000 certification forces a corporation to specialize in “how they are doing business”. Each procedure and work instruction must be documented and thus becomes a springboard for continuous improvement."
},
{
"code": null,
"e": 2112,
"s": 1993,
"text": "Employees morale is increased as they’re asked to require control of their processes and document their work processes"
},
{
"code": null,
"e": 2185,
"s": 2112,
"text": "Better products and services result from continuous improvement process."
},
{
"code": null,
"e": 2297,
"s": 2185,
"text": "Increased employee participation, involvement, awareness and systematic employee training are reduced problems."
},
{
"code": null,
"e": 2415,
"s": 2297,
"text": "Shortcomings of ISO 9000 Certification :Some of the shortcoming of the ISO 9000 certification process are following :"
},
{
"code": null,
"e": 2542,
"s": 2415,
"text": "ISO 9000 does not give any guideline for defining an appropriate process and does not give guarantee for high quality process."
},
{
"code": null,
"e": 2624,
"s": 2542,
"text": "ISO 9000 certification process have no international accreditation agency exists."
},
{
"code": null,
"e": 2645,
"s": 2624,
"text": "Software Engineering"
},
{
"code": null,
"e": 2743,
"s": 2645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2775,
"s": 2743,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 2824,
"s": 2775,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 2872,
"s": 2824,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 2914,
"s": 2872,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 2970,
"s": 2914,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 3005,
"s": 2970,
"text": "Software Testing Life Cycle (STLC)"
},
{
"code": null,
"e": 3044,
"s": 3005,
"text": "Difference between IAAS, PAAS and SAAS"
},
{
"code": null,
"e": 3076,
"s": 3044,
"text": "Equivalence Partitioning Method"
},
{
"code": null,
"e": 3112,
"s": 3076,
"text": "Software Engineering | SDLC V-Model"
}
] |
Program for length of the longest word in a sentence
|
16 Aug, 2021
Given a string, we have to find the longest word in the input string and then calculate the number of characters in this word.
Examples:
Input : A computer science portal for geeks
Output : Longest word's length = 8
Input : I am an intern at geeksforgeeks
Output : Longest word's length = 13
The idea is simple, we traverse the given string. If we find end of word, we compare length of ended word with result. Else, we increment length of current word.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the number of// charters in the longest word in// the sentence.#include <iostream>using namespace std; int LongestWordLength(string str){ int n = str.length(); int res = 0, curr_len = 0, i; for (int i = 0; i < n; i++) { // If current character is // not end of current word. if (str[i] != ' ') curr_len++; // If end of word is found else { res = max(res, curr_len); curr_len = 0; } } // We do max one more time to // consider last word as there // won't be any space after // last word. return max(res, curr_len);} // Driver functionint main(){ string s = "I am an intern at geeksforgeeks"; cout << LongestWordLength(s); return 0;} // This code is contributed by// Smitha Dinesh Semwal.
// Java program to find the number of charters// in the longest word in the sentence.import java.util.*; class LongestWordLength{ static int LongestWordLength(String str) { int n = str.length(); int res = 0, curr_len = 0; for (int i = 0; i < n; i++) { // If current character is not // end of current word. if (str.charAt(i) != ' ') curr_len++; // If end of word is found else { res = Math.max(res, curr_len); curr_len = 0; } } // We do max one more time to consider // last word as there won't be any space // after last word. return Math.max(res, curr_len); } public static void main(String[] args) { String s = "I am an intern at geeksforgeeks"; System.out.println(LongestWordLength(s)); }}
# Python3 program to find the# number of charters in the# longest word in the sentence.def LongestWordLength(str): n = len(str) res = 0; curr_len = 0 for i in range(0, n): # If current character is # not end of current word. if (str[i] != ' '): curr_len += 1 # If end of word is found else: res = max(res, curr_len) curr_len = 0 # We do max one more time to consider # last word as there won't be any space # after last word. return max(res, curr_len) # Driver Codes = "I am an intern at geeksforgeeks"print(LongestWordLength(s)) # This code is contribute by Smitha Dinesh Semwal.
// C# program to find the number of charters// in the longest word in the sentence.using System; class GFG { static int LongestWordLength(string str) { int n = str.Length; int res = 0, curr_len = 0; for (int i = 0; i < n; i++) { // If current character is not // end of current word. if (str[i] != ' ') curr_len++; // If end of word is found else { res = Math.Max(res, curr_len); curr_len = 0; } } // We do max one more time to consider // last word as there won't be any space // after last word. return Math.Max(res, curr_len); } public static void Main() { string s = "I am an intern at geeksforgeeks"; Console.Write(LongestWordLength(s)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find the// number of charters in// the longest word in the// sentence. function LongestWordLength($str){ $n = strlen($str); $res = 0; $curr_len = 0; for ($i = 0; $i < $n; $i++) { // If current character is // not end of current word. if ($str[$i] != ' ') $curr_len++; // If end of word is found else { $res = max($res, $curr_len); $curr_len = 0; } } // We do max one more // time to consider last // word as there won't // be any space after // last word. return max($res, $curr_len);} // Driver Code$s = "I am an intern at geeksforgeeks"; echo (LongestWordLength($s)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // JavaScript program to find the number of charters // in the longest word in the sentence. function LongestWordLength(str) { var n = str.length; var res = 0, curr_len = 0; for (var i = 0; i < n; i++) { // If current character is not // end of current word. if (str[i] !== " ") curr_len++; // If end of word is found else { res = Math.max(res, curr_len); curr_len = 0; } } // We do max one more time to consider // last word as there won't be any space // after last word. return Math.max(res, curr_len); } var s = "I am an intern at geeksforgeeks"; document.write(LongestWordLength(s)); // This code is contributed by rdtank. </script>
13
Another Approach:
C++14
Java
Python3
C#
// C++ program to find the number of charters// in the longest word in the sentence.#include<bits/stdc++.h>using namespace std; int LongestWordLength(string str){ int counter = 0; string words[100]; for (short i = 0; i < str.length(); i++) { if (str[i] == ' ') counter++; else words[counter] += str[i]; } int length = 0; for(string word:words) { if(length < word.length()) { length = word.length(); } } return length;} // Driver codeint main(){ string str = "I am an intern at geeksforgeeks"; cout << (LongestWordLength(str));} // This code contributed by Rajput-Ji
// Java program to find the number of charters// in the longest word in the sentence.class GFG { static int LongestWordLength(String str) { String[] words = str.split(" "); int length = 0; for(String word:words){ if(length < word.length()){ length = word.length(); } } return length; } // Driver code public static void main(String args[]) { String str = "I am an intern at geeksforgeeks"; System.out.println(LongestWordLength(str)); }}
# Python program to find the number of characters# in the longest word in the sentence. def longestWordLength(string): length = 0 # Finding longest word in sentence for word in string.split(): if(len(word) > length): length = len(word) return length # Driver Codestring = "I am an intern at geeksforgeeks"print(longestWordLength(string)) # This code is contributed by Vivekkumar Singh
// C# program to find the// number of charters in// the longest word in// the sentence.using System; class GFG{ static int LongestWordLength(string str) { String[] words = str.Split(' '); int length = 0; for(int i = 0; i < words.Length; i++) { if(length < words[i].Length) { length = words[i].Length; } } return length; } // Driver code static void Main() { string str = "I am an intern at geeksforgeeks"; Console.Write(LongestWordLength(str)); }} // This code is contributed by// Manish Shaw(manishshaw1)
13
Vigneshwaran A
nitin mittal
manishshaw1
Vivekkumar Singh
Rajput-Ji
rdtank
simmytarika5
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 179,
"s": 52,
"text": "Given a string, we have to find the longest word in the input string and then calculate the number of characters in this word."
},
{
"code": null,
"e": 190,
"s": 179,
"text": "Examples: "
},
{
"code": null,
"e": 271,
"s": 190,
"text": "Input : A computer science portal for geeks\nOutput : Longest word's length = 8 "
},
{
"code": null,
"e": 348,
"s": 271,
"text": "Input : I am an intern at geeksforgeeks\nOutput : Longest word's length = 13"
},
{
"code": null,
"e": 510,
"s": 348,
"text": "The idea is simple, we traverse the given string. If we find end of word, we compare length of ended word with result. Else, we increment length of current word."
},
{
"code": null,
"e": 514,
"s": 510,
"text": "C++"
},
{
"code": null,
"e": 519,
"s": 514,
"text": "Java"
},
{
"code": null,
"e": 527,
"s": 519,
"text": "Python3"
},
{
"code": null,
"e": 530,
"s": 527,
"text": "C#"
},
{
"code": null,
"e": 534,
"s": 530,
"text": "PHP"
},
{
"code": null,
"e": 545,
"s": 534,
"text": "Javascript"
},
{
"code": "// C++ program to find the number of// charters in the longest word in// the sentence.#include <iostream>using namespace std; int LongestWordLength(string str){ int n = str.length(); int res = 0, curr_len = 0, i; for (int i = 0; i < n; i++) { // If current character is // not end of current word. if (str[i] != ' ') curr_len++; // If end of word is found else { res = max(res, curr_len); curr_len = 0; } } // We do max one more time to // consider last word as there // won't be any space after // last word. return max(res, curr_len);} // Driver functionint main(){ string s = \"I am an intern at geeksforgeeks\"; cout << LongestWordLength(s); return 0;} // This code is contributed by// Smitha Dinesh Semwal.",
"e": 1411,
"s": 545,
"text": null
},
{
"code": "// Java program to find the number of charters// in the longest word in the sentence.import java.util.*; class LongestWordLength{ static int LongestWordLength(String str) { int n = str.length(); int res = 0, curr_len = 0; for (int i = 0; i < n; i++) { // If current character is not // end of current word. if (str.charAt(i) != ' ') curr_len++; // If end of word is found else { res = Math.max(res, curr_len); curr_len = 0; } } // We do max one more time to consider // last word as there won't be any space // after last word. return Math.max(res, curr_len); } public static void main(String[] args) { String s = \"I am an intern at geeksforgeeks\"; System.out.println(LongestWordLength(s)); }}",
"e": 2249,
"s": 1411,
"text": null
},
{
"code": "# Python3 program to find the# number of charters in the# longest word in the sentence.def LongestWordLength(str): n = len(str) res = 0; curr_len = 0 for i in range(0, n): # If current character is # not end of current word. if (str[i] != ' '): curr_len += 1 # If end of word is found else: res = max(res, curr_len) curr_len = 0 # We do max one more time to consider # last word as there won't be any space # after last word. return max(res, curr_len) # Driver Codes = \"I am an intern at geeksforgeeks\"print(LongestWordLength(s)) # This code is contribute by Smitha Dinesh Semwal.",
"e": 2936,
"s": 2249,
"text": null
},
{
"code": "// C# program to find the number of charters// in the longest word in the sentence.using System; class GFG { static int LongestWordLength(string str) { int n = str.Length; int res = 0, curr_len = 0; for (int i = 0; i < n; i++) { // If current character is not // end of current word. if (str[i] != ' ') curr_len++; // If end of word is found else { res = Math.Max(res, curr_len); curr_len = 0; } } // We do max one more time to consider // last word as there won't be any space // after last word. return Math.Max(res, curr_len); } public static void Main() { string s = \"I am an intern at geeksforgeeks\"; Console.Write(LongestWordLength(s)); }} // This code is contributed by nitin mittal.",
"e": 3873,
"s": 2936,
"text": null
},
{
"code": "<?php// PHP program to find the// number of charters in// the longest word in the// sentence. function LongestWordLength($str){ $n = strlen($str); $res = 0; $curr_len = 0; for ($i = 0; $i < $n; $i++) { // If current character is // not end of current word. if ($str[$i] != ' ') $curr_len++; // If end of word is found else { $res = max($res, $curr_len); $curr_len = 0; } } // We do max one more // time to consider last // word as there won't // be any space after // last word. return max($res, $curr_len);} // Driver Code$s = \"I am an intern at geeksforgeeks\"; echo (LongestWordLength($s)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 4678,
"s": 3873,
"text": null
},
{
"code": "<script> // JavaScript program to find the number of charters // in the longest word in the sentence. function LongestWordLength(str) { var n = str.length; var res = 0, curr_len = 0; for (var i = 0; i < n; i++) { // If current character is not // end of current word. if (str[i] !== \" \") curr_len++; // If end of word is found else { res = Math.max(res, curr_len); curr_len = 0; } } // We do max one more time to consider // last word as there won't be any space // after last word. return Math.max(res, curr_len); } var s = \"I am an intern at geeksforgeeks\"; document.write(LongestWordLength(s)); // This code is contributed by rdtank. </script>",
"e": 5543,
"s": 4678,
"text": null
},
{
"code": null,
"e": 5546,
"s": 5543,
"text": "13"
},
{
"code": null,
"e": 5567,
"s": 5548,
"text": "Another Approach: "
},
{
"code": null,
"e": 5573,
"s": 5567,
"text": "C++14"
},
{
"code": null,
"e": 5578,
"s": 5573,
"text": "Java"
},
{
"code": null,
"e": 5586,
"s": 5578,
"text": "Python3"
},
{
"code": null,
"e": 5589,
"s": 5586,
"text": "C#"
},
{
"code": "// C++ program to find the number of charters// in the longest word in the sentence.#include<bits/stdc++.h>using namespace std; int LongestWordLength(string str){ int counter = 0; string words[100]; for (short i = 0; i < str.length(); i++) { if (str[i] == ' ') counter++; else words[counter] += str[i]; } int length = 0; for(string word:words) { if(length < word.length()) { length = word.length(); } } return length;} // Driver codeint main(){ string str = \"I am an intern at geeksforgeeks\"; cout << (LongestWordLength(str));} // This code contributed by Rajput-Ji",
"e": 6278,
"s": 5589,
"text": null
},
{
"code": "// Java program to find the number of charters// in the longest word in the sentence.class GFG { static int LongestWordLength(String str) { String[] words = str.split(\" \"); int length = 0; for(String word:words){ if(length < word.length()){ length = word.length(); } } return length; } // Driver code public static void main(String args[]) { String str = \"I am an intern at geeksforgeeks\"; System.out.println(LongestWordLength(str)); }}",
"e": 6850,
"s": 6278,
"text": null
},
{
"code": "# Python program to find the number of characters# in the longest word in the sentence. def longestWordLength(string): length = 0 # Finding longest word in sentence for word in string.split(): if(len(word) > length): length = len(word) return length # Driver Codestring = \"I am an intern at geeksforgeeks\"print(longestWordLength(string)) # This code is contributed by Vivekkumar Singh",
"e": 7280,
"s": 6850,
"text": null
},
{
"code": "// C# program to find the// number of charters in// the longest word in// the sentence.using System; class GFG{ static int LongestWordLength(string str) { String[] words = str.Split(' '); int length = 0; for(int i = 0; i < words.Length; i++) { if(length < words[i].Length) { length = words[i].Length; } } return length; } // Driver code static void Main() { string str = \"I am an intern at geeksforgeeks\"; Console.Write(LongestWordLength(str)); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 7934,
"s": 7280,
"text": null
},
{
"code": null,
"e": 7937,
"s": 7934,
"text": "13"
},
{
"code": null,
"e": 7954,
"s": 7939,
"text": "Vigneshwaran A"
},
{
"code": null,
"e": 7967,
"s": 7954,
"text": "nitin mittal"
},
{
"code": null,
"e": 7979,
"s": 7967,
"text": "manishshaw1"
},
{
"code": null,
"e": 7996,
"s": 7979,
"text": "Vivekkumar Singh"
},
{
"code": null,
"e": 8006,
"s": 7996,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8013,
"s": 8006,
"text": "rdtank"
},
{
"code": null,
"e": 8026,
"s": 8013,
"text": "simmytarika5"
},
{
"code": null,
"e": 8034,
"s": 8026,
"text": "Strings"
},
{
"code": null,
"e": 8042,
"s": 8034,
"text": "Strings"
}
] |
Python unittest – assertIsNone() function
|
29 Aug, 2020
assertIsNone() in Python is a unittest library function that is used in unit testing to check that input value is None or not. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is equal to None assertIsNone() will return true else return false.
Syntax: assertIsNone(testValue, message)
Parameters: assertIsNone() accept two parameters which are listed below with explanation:
testValue: test variable as the input value to check equality with None
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function def test_negative(self): firstValue = "geeks" # error message in case if test case got failed message = "Test value is not none." # assertIsNone() to check that if input value is none self.assertIsNone(firstValue, message) if __name__ == '__main__': unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 14, in test_negative
self.assertIsNone(firstValue, message)
AssertionError: 'geeks' is not None : Test value is not none.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Example 2: Positive Test case
Python3
# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function def test_positive(self): firstValue = None # error message in case if test case got failed message = "Test value is not none." # assertIsNone() to check that if input value is none self.assertIsNone(firstValue, message) if __name__ == '__main__': unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "assertIsNone() in Python is a unittest library function that is used in unit testing to check that input value is None or not. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is equal to None assertIsNone() will return true else return false."
},
{
"code": null,
"e": 387,
"s": 346,
"text": "Syntax: assertIsNone(testValue, message)"
},
{
"code": null,
"e": 477,
"s": 387,
"text": "Parameters: assertIsNone() accept two parameters which are listed below with explanation:"
},
{
"code": null,
"e": 550,
"s": 477,
"text": "testValue: test variable as the input value to check equality with None"
},
{
"code": null,
"e": 641,
"s": 550,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 757,
"s": 641,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 787,
"s": 757,
"text": "Example 1: Negative Test case"
},
{
"code": null,
"e": 795,
"s": 787,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function def test_negative(self): firstValue = \"geeks\" # error message in case if test case got failed message = \"Test value is not none.\" # assertIsNone() to check that if input value is none self.assertIsNone(firstValue, message) if __name__ == '__main__': unittest.main()",
"e": 1220,
"s": 795,
"text": null
},
{
"code": null,
"e": 1228,
"s": 1220,
"text": "Output:"
},
{
"code": null,
"e": 1713,
"s": 1228,
"text": "F\n======================================================================\nFAIL: test_negative (__main__.TestMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 14, in test_negative\n self.assertIsNone(firstValue, message)\nAssertionError: 'geeks' is not None : Test value is not none.\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n"
},
{
"code": null,
"e": 1743,
"s": 1713,
"text": "Example 2: Positive Test case"
},
{
"code": null,
"e": 1751,
"s": 1743,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function def test_positive(self): firstValue = None # error message in case if test case got failed message = \"Test value is not none.\" # assertIsNone() to check that if input value is none self.assertIsNone(firstValue, message) if __name__ == '__main__': unittest.main()",
"e": 2173,
"s": 1751,
"text": null
},
{
"code": null,
"e": 2181,
"s": 2173,
"text": "Output:"
},
{
"code": null,
"e": 2281,
"s": 2181,
"text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n"
},
{
"code": null,
"e": 2340,
"s": 2281,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 2364,
"s": 2340,
"text": "Python unittest-library"
},
{
"code": null,
"e": 2371,
"s": 2364,
"text": "Python"
},
{
"code": null,
"e": 2469,
"s": 2371,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2501,
"s": 2469,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2528,
"s": 2501,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2559,
"s": 2528,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2580,
"s": 2559,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2636,
"s": 2580,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2659,
"s": 2636,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2701,
"s": 2659,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2743,
"s": 2701,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2782,
"s": 2743,
"text": "Python | datetime.timedelta() function"
}
] |
priority_queue::top() in C++ STL
|
21 Jun, 2022
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is wither the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest element by default. We can also make a priority queue with a minimum element at the top by passing a additional parameter while creating the priority queue. It is similar to min/max heap.
top() function is used to reference the top element of the priority queue. The top (by default) element is the largest element in C++ STL.
However in other programming languages like java, by default a min heap is created and the top() gives the minimum element.
Syntax :
pqueuename.top()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the top(by default it is the largest element)
element of the priority queue container.
Examples:
Input : pqueue.push(5);
pqueue.push(1);
pqueue.top();
Output : 5
Input : pqueue.push(5);
pqueue.push(1);
pqueue.push(7);
pqueue.top();
Output : 7
Errors and Exceptions 1. If the priority queue container is empty, it causes undefined behaviour 2. It has a no exception throw guarantee if the priority queue is not empty
CPP
// CPP program to illustrate// Implementation of top() function#include <iostream>#include <queue>using namespace std; int main(){ priority_queue<int> pqueue; pqueue.push(5); pqueue.push(1); pqueue.push(7); // Priority queue top cout << pqueue.top(); return 0;}
Output:
7
Time Complexity: O(1)
Auxiliary Space: O(n)
Application : Given a priority queue of integers, find the number of prime and non prime numbers.
Input : 8, 6, 3, 2, 1
Output: Prime - 2
Non Prime - 3
Algorithm 1. Enter the size of the priority queue into a variable. 2. Check if the priority queue is empty, check if the top element is prime, if prime increments the prime counter, and pop the top element. 3. Repeat this step until the priority queue is empty. 4. Print the final value of the variable prime and nonprime(size – prime).
CPP
// CPP program to illustrate// Application of top() function#include <iostream>#include <queue>using namespace std; int main(){ int prime = 0, nonprime = 0, size; priority_queue<int> pqueue; pqueue.push(1); pqueue.push(8); pqueue.push(3); pqueue.push(6); pqueue.push(2); size = pqueue.size(); // Priority queue becomes 1, 8, 3, 6, 2 while (!pqueue.empty()) { for (int i = 2; i <= pqueue.top() / 2; ++i) { if (pqueue.top() % i == 0) { prime++; break; } } pqueue.pop(); } cout << "Prime - " << prime << endl; cout << "Non Prime - " << size - prime; return 0;}
Output:
Prime - 2
Non Prime - 3
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
divyanshmishra101010
utkarshgupta110092
CPP-Library
cpp-priority-queue
cpp-queue
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 536,
"s": 52,
"text": "Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is wither the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest element by default. We can also make a priority queue with a minimum element at the top by passing a additional parameter while creating the priority queue. It is similar to min/max heap."
},
{
"code": null,
"e": 676,
"s": 536,
"text": "top() function is used to reference the top element of the priority queue. The top (by default) element is the largest element in C++ STL. "
},
{
"code": null,
"e": 800,
"s": 676,
"text": "However in other programming languages like java, by default a min heap is created and the top() gives the minimum element."
},
{
"code": null,
"e": 809,
"s": 800,
"text": "Syntax :"
},
{
"code": null,
"e": 1001,
"s": 809,
"text": "pqueuename.top()\nParameters :\nNo value is needed to pass as the parameter.\nReturns :\nDirect reference to the top(by default it is the largest element)\nelement of the priority queue container."
},
{
"code": null,
"e": 1011,
"s": 1001,
"text": "Examples:"
},
{
"code": null,
"e": 1205,
"s": 1011,
"text": "Input : pqueue.push(5);\n pqueue.push(1);\n pqueue.top();\nOutput : 5\n\nInput : pqueue.push(5);\n pqueue.push(1);\n pqueue.push(7);\n pqueue.top();\nOutput : 7"
},
{
"code": null,
"e": 1379,
"s": 1205,
"text": "Errors and Exceptions 1. If the priority queue container is empty, it causes undefined behaviour 2. It has a no exception throw guarantee if the priority queue is not empty "
},
{
"code": null,
"e": 1383,
"s": 1379,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of top() function#include <iostream>#include <queue>using namespace std; int main(){ priority_queue<int> pqueue; pqueue.push(5); pqueue.push(1); pqueue.push(7); // Priority queue top cout << pqueue.top(); return 0;}",
"e": 1667,
"s": 1383,
"text": null
},
{
"code": null,
"e": 1675,
"s": 1667,
"text": "Output:"
},
{
"code": null,
"e": 1677,
"s": 1675,
"text": "7"
},
{
"code": null,
"e": 1699,
"s": 1677,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 1721,
"s": 1699,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1819,
"s": 1721,
"text": "Application : Given a priority queue of integers, find the number of prime and non prime numbers."
},
{
"code": null,
"e": 1881,
"s": 1819,
"text": "Input : 8, 6, 3, 2, 1\nOutput: Prime - 2\n Non Prime - 3"
},
{
"code": null,
"e": 2219,
"s": 1881,
"text": "Algorithm 1. Enter the size of the priority queue into a variable. 2. Check if the priority queue is empty, check if the top element is prime, if prime increments the prime counter, and pop the top element. 3. Repeat this step until the priority queue is empty. 4. Print the final value of the variable prime and nonprime(size – prime). "
},
{
"code": null,
"e": 2223,
"s": 2219,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Application of top() function#include <iostream>#include <queue>using namespace std; int main(){ int prime = 0, nonprime = 0, size; priority_queue<int> pqueue; pqueue.push(1); pqueue.push(8); pqueue.push(3); pqueue.push(6); pqueue.push(2); size = pqueue.size(); // Priority queue becomes 1, 8, 3, 6, 2 while (!pqueue.empty()) { for (int i = 2; i <= pqueue.top() / 2; ++i) { if (pqueue.top() % i == 0) { prime++; break; } } pqueue.pop(); } cout << \"Prime - \" << prime << endl; cout << \"Non Prime - \" << size - prime; return 0;}",
"e": 2898,
"s": 2223,
"text": null
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 2930,
"s": 2906,
"text": "Prime - 2\nNon Prime - 3"
},
{
"code": null,
"e": 2956,
"s": 2930,
"text": "Time Complexity: O(nlogn)"
},
{
"code": null,
"e": 2978,
"s": 2956,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2999,
"s": 2978,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 3018,
"s": 2999,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 3030,
"s": 3018,
"text": "CPP-Library"
},
{
"code": null,
"e": 3049,
"s": 3030,
"text": "cpp-priority-queue"
},
{
"code": null,
"e": 3059,
"s": 3049,
"text": "cpp-queue"
},
{
"code": null,
"e": 3063,
"s": 3059,
"text": "STL"
},
{
"code": null,
"e": 3067,
"s": 3063,
"text": "C++"
},
{
"code": null,
"e": 3071,
"s": 3067,
"text": "STL"
},
{
"code": null,
"e": 3075,
"s": 3071,
"text": "CPP"
},
{
"code": null,
"e": 3173,
"s": 3075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3197,
"s": 3173,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3217,
"s": 3197,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3261,
"s": 3217,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3294,
"s": 3261,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3319,
"s": 3294,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3364,
"s": 3319,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3381,
"s": 3364,
"text": "std::find in C++"
},
{
"code": null,
"e": 3429,
"s": 3381,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3473,
"s": 3429,
"text": "List in C++ Standard Template Library (STL)"
}
] |
How to Append Pandas DataFrame to Existing CSV File?
|
22 Dec, 2021
In this article, we will discuss how to append Pandas dataframe to the existing CSV file using Python.
Appending dataframe means adding data rows to already existing files. To add a dataframe row-wise to an existing CSV file, we can write the dataframe to the CSV file in append mode by the parameter a using the pandas to_csv() function.
Syntax:
df.to_csv(‘existing.csv’, mode=’a’, index=False, header=False)
Parameters:
existing.csv: Name of the existing CSV file.
mode: By default mode is ‘w’ which will overwrite the file. Use ‘a’ to append data into the file.
index: False means do not include an index column when appending the new data. True means include an index column when appending the new data.
header: False means do not include a header when appending the new data. True means include a header when appending the new data.
Below are the steps to Append Pandas DataFrame to Existing CSV File.
First, find the CSV file in which we want to append the dataframe. We have an existing CSV file with player name and runs, wickets, and catch done by the player. And we want to append some more player data to this CSV file. This is how the existing CSV file looks:
Now let’s say we want to add more players to this CSV file. First create a dataframe of that player with their corresponding run, wicket, and catch. And make their pandas dataframe. We will append this to the existing CSV file.
Let’s append the dataframe to the existing CSV file. Below is the python code.
Python3
# Append Pandas DataFrame to Existing CSV File# importing pandas moduleimport pandas as pd # data of Player and their performancedata = { 'Name': ['Hardik', 'Pollard', 'Bravo'], 'Run': [50, 63, 15], 'Wicket': [0, 2, 3], 'Catch': [4, 2, 1]} # Make data frame of above datadf = pd.DataFrame(data) # append data frame to CSV filedf.to_csv('GFG.csv', mode='a', index=False, header=False) # print messageprint("Data appended successfully.")
Output:
surindertarika1234
Picked
Python pandas-io
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "In this article, we will discuss how to append Pandas dataframe to the existing CSV file using Python."
},
{
"code": null,
"e": 368,
"s": 132,
"text": "Appending dataframe means adding data rows to already existing files. To add a dataframe row-wise to an existing CSV file, we can write the dataframe to the CSV file in append mode by the parameter a using the pandas to_csv() function."
},
{
"code": null,
"e": 376,
"s": 368,
"text": "Syntax:"
},
{
"code": null,
"e": 439,
"s": 376,
"text": "df.to_csv(‘existing.csv’, mode=’a’, index=False, header=False)"
},
{
"code": null,
"e": 451,
"s": 439,
"text": "Parameters:"
},
{
"code": null,
"e": 496,
"s": 451,
"text": "existing.csv: Name of the existing CSV file."
},
{
"code": null,
"e": 594,
"s": 496,
"text": "mode: By default mode is ‘w’ which will overwrite the file. Use ‘a’ to append data into the file."
},
{
"code": null,
"e": 737,
"s": 594,
"text": "index: False means do not include an index column when appending the new data. True means include an index column when appending the new data."
},
{
"code": null,
"e": 867,
"s": 737,
"text": "header: False means do not include a header when appending the new data. True means include a header when appending the new data."
},
{
"code": null,
"e": 936,
"s": 867,
"text": "Below are the steps to Append Pandas DataFrame to Existing CSV File."
},
{
"code": null,
"e": 1202,
"s": 936,
"text": "First, find the CSV file in which we want to append the dataframe. We have an existing CSV file with player name and runs, wickets, and catch done by the player. And we want to append some more player data to this CSV file. This is how the existing CSV file looks:"
},
{
"code": null,
"e": 1430,
"s": 1202,
"text": "Now let’s say we want to add more players to this CSV file. First create a dataframe of that player with their corresponding run, wicket, and catch. And make their pandas dataframe. We will append this to the existing CSV file."
},
{
"code": null,
"e": 1509,
"s": 1430,
"text": "Let’s append the dataframe to the existing CSV file. Below is the python code."
},
{
"code": null,
"e": 1517,
"s": 1509,
"text": "Python3"
},
{
"code": "# Append Pandas DataFrame to Existing CSV File# importing pandas moduleimport pandas as pd # data of Player and their performancedata = { 'Name': ['Hardik', 'Pollard', 'Bravo'], 'Run': [50, 63, 15], 'Wicket': [0, 2, 3], 'Catch': [4, 2, 1]} # Make data frame of above datadf = pd.DataFrame(data) # append data frame to CSV filedf.to_csv('GFG.csv', mode='a', index=False, header=False) # print messageprint(\"Data appended successfully.\")",
"e": 1965,
"s": 1517,
"text": null
},
{
"code": null,
"e": 1973,
"s": 1965,
"text": "Output:"
},
{
"code": null,
"e": 1992,
"s": 1973,
"text": "surindertarika1234"
},
{
"code": null,
"e": 1999,
"s": 1992,
"text": "Picked"
},
{
"code": null,
"e": 2016,
"s": 1999,
"text": "Python pandas-io"
},
{
"code": null,
"e": 2030,
"s": 2016,
"text": "Python-pandas"
},
{
"code": null,
"e": 2037,
"s": 2030,
"text": "Python"
},
{
"code": null,
"e": 2135,
"s": 2037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2167,
"s": 2135,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2194,
"s": 2167,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2215,
"s": 2194,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2238,
"s": 2215,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2294,
"s": 2238,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2325,
"s": 2294,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2367,
"s": 2325,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2409,
"s": 2367,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2448,
"s": 2409,
"text": "Python | datetime.timedelta() function"
}
] |
HDFS – Data Read Operation
|
10 Dec, 2020
HDFS is a distributed file system that stores data over a network of commodity machines. HDFS works on the streaming data access pattern means it supports write-ones and read-many features. Read operation on HDFS is very important and also very much necessary for us to know while working on HDFS that how actually reading is done on HDFS(Hadoop Distributed File System). Let’s understand how HDFS data read works.
Reading on HDFS seems to be simple but it is not. Whenever a client sends a request to HDFS to read something from HDFS the access to the data or DataNode where actual data is stored is not directly granted to the client because the client does not have the information about the data i.e. on which DataNode data is stored or where the replica of data is made on DataNodes. Without knowing information about the DataNodes the client can never access or read data from HDFS.
So, that’s why the client first sends the request to NameNode since the NameNode contains all the metadata or information we require to perform read operation on HDFS. Once the request is received by the NameNode it responds and sends all the information like the number of DataNodes, the location where the replica is made, the number of data blocks and their location, etc to the client. Now the client can read data with all this information provided by the NameNode. The client reads the data parallelly since the replica of the same data is available on the cluster. Once the whole data is read it combines all the blocks as the original file.
Let’s understand data read on HDFS with a suitable diagram
Components that we have to know before learning HDFS read operation.
NameNode: The primary purpose of Namenode is to manage all the MetaData. As we know the data is stored in the form of blocks in a Hadoop cluster. So on which DataNode or on which location that block of the file is stored is mentioned in MetaData. Log of the Transaction happening in a Hadoop cluster, when or who read or write the data, all this information will be stored in MetaData.
DataNode: DataNode is a program run on the slave system that serves the read/write request from the client and used to store data in form of blocks.
HDFS Client: HDFS Client is an intermediate component between HDFS and the user. It communicates with the Datanode or Namenode and fetches the essential output that the user requests.
In the above, image we can see that first, we send the request to our HDFS client which is a set of programs. Now, this HDFS client contacts the NameNode because it has all information or metadata about the file we want to read. The NamoNode responds and then sends all the metadata back to the HDFS client. Once the HDFS client knows from which location it has to pick the data block, It asks the FS Data Input Stream to point out those blocks of data on data nodes. The FS Data Input Stream then does some processing and made this data available for the client.
Let’s see the way to read data from HDFS.
With the help of the below command, we can directly read data from HDFS(NOTE: Make sure all of your Hadoop daemons are running).
Commands to start Hadoop Daemons
start-dfs.sh
start-yarn.sh
Syntax For Reading Data From HDFS:
hdfs dfs -get <source-path> <destination-path> # here source path is file path on HDFS that we want to read
# destination path is where we want to store the readed file on local machine
Command
In our case, we have one file with the name dikshant.txt with some data on the HDFS root directory. The below command, we can use to list data on the HDFS root directory.
hdfs dfs -ls /
the below command will read the data from the root directory of HDFS and stores it in the /home/dikshant/Desktop location on my local machine.
hdfs dfs -get /dikshant.txt /home/dikshant/Desktop
In the below image we can observe that the data is successfully read and stored in /home/dikshant/Desktop directory and now we can see the content of it by opening this file.
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Dec, 2020"
},
{
"code": null,
"e": 467,
"s": 52,
"text": "HDFS is a distributed file system that stores data over a network of commodity machines. HDFS works on the streaming data access pattern means it supports write-ones and read-many features. Read operation on HDFS is very important and also very much necessary for us to know while working on HDFS that how actually reading is done on HDFS(Hadoop Distributed File System). Let’s understand how HDFS data read works."
},
{
"code": null,
"e": 941,
"s": 467,
"text": "Reading on HDFS seems to be simple but it is not. Whenever a client sends a request to HDFS to read something from HDFS the access to the data or DataNode where actual data is stored is not directly granted to the client because the client does not have the information about the data i.e. on which DataNode data is stored or where the replica of data is made on DataNodes. Without knowing information about the DataNodes the client can never access or read data from HDFS."
},
{
"code": null,
"e": 1590,
"s": 941,
"text": "So, that’s why the client first sends the request to NameNode since the NameNode contains all the metadata or information we require to perform read operation on HDFS. Once the request is received by the NameNode it responds and sends all the information like the number of DataNodes, the location where the replica is made, the number of data blocks and their location, etc to the client. Now the client can read data with all this information provided by the NameNode. The client reads the data parallelly since the replica of the same data is available on the cluster. Once the whole data is read it combines all the blocks as the original file."
},
{
"code": null,
"e": 1649,
"s": 1590,
"text": "Let’s understand data read on HDFS with a suitable diagram"
},
{
"code": null,
"e": 1718,
"s": 1649,
"text": "Components that we have to know before learning HDFS read operation."
},
{
"code": null,
"e": 2104,
"s": 1718,
"text": "NameNode: The primary purpose of Namenode is to manage all the MetaData. As we know the data is stored in the form of blocks in a Hadoop cluster. So on which DataNode or on which location that block of the file is stored is mentioned in MetaData. Log of the Transaction happening in a Hadoop cluster, when or who read or write the data, all this information will be stored in MetaData."
},
{
"code": null,
"e": 2253,
"s": 2104,
"text": "DataNode: DataNode is a program run on the slave system that serves the read/write request from the client and used to store data in form of blocks."
},
{
"code": null,
"e": 2438,
"s": 2253,
"text": "HDFS Client: HDFS Client is an intermediate component between HDFS and the user. It communicates with the Datanode or Namenode and fetches the essential output that the user requests. "
},
{
"code": null,
"e": 3002,
"s": 2438,
"text": "In the above, image we can see that first, we send the request to our HDFS client which is a set of programs. Now, this HDFS client contacts the NameNode because it has all information or metadata about the file we want to read. The NamoNode responds and then sends all the metadata back to the HDFS client. Once the HDFS client knows from which location it has to pick the data block, It asks the FS Data Input Stream to point out those blocks of data on data nodes. The FS Data Input Stream then does some processing and made this data available for the client."
},
{
"code": null,
"e": 3044,
"s": 3002,
"text": "Let’s see the way to read data from HDFS."
},
{
"code": null,
"e": 3173,
"s": 3044,
"text": "With the help of the below command, we can directly read data from HDFS(NOTE: Make sure all of your Hadoop daemons are running)."
},
{
"code": null,
"e": 3206,
"s": 3173,
"text": "Commands to start Hadoop Daemons"
},
{
"code": null,
"e": 3233,
"s": 3206,
"text": "start-dfs.sh\nstart-yarn.sh"
},
{
"code": null,
"e": 3268,
"s": 3233,
"text": "Syntax For Reading Data From HDFS:"
},
{
"code": null,
"e": 3430,
"s": 3268,
"text": "hdfs dfs -get <source-path> <destination-path> # here source path is file path on HDFS that we want to read "
},
{
"code": null,
"e": 3589,
"s": 3430,
"text": " # destination path is where we want to store the readed file on local machine "
},
{
"code": null,
"e": 3597,
"s": 3589,
"text": "Command"
},
{
"code": null,
"e": 3768,
"s": 3597,
"text": "In our case, we have one file with the name dikshant.txt with some data on the HDFS root directory. The below command, we can use to list data on the HDFS root directory."
},
{
"code": null,
"e": 3783,
"s": 3768,
"text": "hdfs dfs -ls /"
},
{
"code": null,
"e": 3927,
"s": 3783,
"text": "the below command will read the data from the root directory of HDFS and stores it in the /home/dikshant/Desktop location on my local machine. "
},
{
"code": null,
"e": 3978,
"s": 3927,
"text": "hdfs dfs -get /dikshant.txt /home/dikshant/Desktop"
},
{
"code": null,
"e": 4156,
"s": 3978,
"text": "In the below image we can observe that the data is successfully read and stored in /home/dikshant/Desktop directory and now we can see the content of it by opening this file. "
},
{
"code": null,
"e": 4163,
"s": 4156,
"text": "Hadoop"
},
{
"code": null,
"e": 4170,
"s": 4163,
"text": "Hadoop"
}
] |
Python Script to Restart Computer
|
14 Jul, 2019
As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to restart a computer. Let’s start with how to restart the system with Python.
Note: For this to work, you have to import os library in the ide. If you don’t have it, then ‘pip install os‘ through the Command Prompt.
Causion: Please ensure that you save and close all the program before running this code on the IDLE, as the below program will immediately restart your computer.
Below is the Python implementation –
import os restart = input("Do you wish to restart your computer ? (yes / no): ") if restart == 'no': exit()else: os.system("shutdown /r /t 1")
Output:Here is the Python Program which will ask the user to restart the computer providing the option of Yes or No. Also, when you type yes & then press the ENTER key, the system will be restart instantly.
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to restart a computer. Let’s start with how to restart the system with Python."
},
{
"code": null,
"e": 378,
"s": 240,
"text": "Note: For this to work, you have to import os library in the ide. If you don’t have it, then ‘pip install os‘ through the Command Prompt."
},
{
"code": null,
"e": 540,
"s": 378,
"text": "Causion: Please ensure that you save and close all the program before running this code on the IDLE, as the below program will immediately restart your computer."
},
{
"code": null,
"e": 577,
"s": 540,
"text": "Below is the Python implementation –"
},
{
"code": "import os restart = input(\"Do you wish to restart your computer ? (yes / no): \") if restart == 'no': exit()else: os.system(\"shutdown /r /t 1\")",
"e": 728,
"s": 577,
"text": null
},
{
"code": null,
"e": 935,
"s": 728,
"text": "Output:Here is the Python Program which will ask the user to restart the computer providing the option of Yes or No. Also, when you type yes & then press the ENTER key, the system will be restart instantly."
},
{
"code": null,
"e": 950,
"s": 935,
"text": "python-utility"
},
{
"code": null,
"e": 957,
"s": 950,
"text": "Python"
},
{
"code": null,
"e": 973,
"s": 957,
"text": "Python Programs"
},
{
"code": null,
"e": 1071,
"s": 973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1089,
"s": 1071,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1131,
"s": 1089,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1166,
"s": 1131,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1198,
"s": 1166,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1224,
"s": 1198,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1267,
"s": 1224,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1289,
"s": 1267,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1328,
"s": 1289,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1366,
"s": 1328,
"text": "Python | Convert a list to dictionary"
}
] |
Python program to create Bankaccount class with deposit, withdraw function
|
23 Aug, 2021
Prerequisite: Object Oriented Programming in PythonLet’s write a simple Python program using OOP concept to perform some simple bank operations like deposit and withdrawal of money.First of all, define class Bankacccount. This step is followed by defining a function using __init__. It is run as soon as an object of a class is instantiated. This __init__ method is useful to do any initialization you want to do with object, then we have the default argument self.
Python3
# BankAccount classclass Bankaccount: def __init__(self):
This step is followed by declaring that balance is 0 using self argument then we simply print a statement welcoming to Machine. In function deposit and withdraw , amount is taken as input(in float) and is then added/subtracted to the balance. Thus resultant balance is printed in next line.
Python3
# Function to deposite amountdef deposit(self): amount = float(input("Enter amount to be deposited: ")) self.balance += amount print("\n Amount Deposited:", amount)
Use an if condition to check whether there is a sufficient amount of money available in the account to process a fund withdrawal.
Python3
# Function to withdraw the amountdef withdraw(self): amount = float(input("Enter amount to be withdrawn: ")) if self.balance >= amount: self.balance -= amount print("\n You Withdrew:", amount) else: print("\n Insufficient balance ")
Next, we use a display function to display the remaining balance in the account. Then we create a object and call it to get the program executed.
Python3
# Function to display the amountdef display(self): print("\n Net Available Balance =", self.balance)
Below is the implementation:
Python3
# Python program to create Bankaccount class# with both a deposit() and a withdraw() functionclass Bank_Account: def __init__(self): self.balance=0 print("Hello!!! Welcome to the Deposit & Withdrawal Machine") def deposit(self): amount=float(input("Enter amount to be Deposited: ")) self.balance += amount print("\n Amount Deposited:",amount) def withdraw(self): amount = float(input("Enter amount to be Withdrawn: ")) if self.balance>=amount: self.balance-=amount print("\n You Withdrew:", amount) else: print("\n Insufficient balance ") def display(self): print("\n Net Available Balance=",self.balance) # Driver code # creating an object of classs = Bank_Account() # Calling functions with that class objects.deposit()s.withdraw()s.display()
Output:
Hello !!! Welcome to Deposit&Withdrawal Machine
Enter amount to be deposited:
Amount Deposited: 1000.0
Enter amount to be withdrawn:
You Withdrew: 500.0
Net Available Balance = 500.0
lennyatomz
Akanksha_Rai
rajeev0719singh
gulshankumarar231
Python-OOP
python-oop-concepts
Technical Scripter 2018
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to check Armstrong Number
Python program to interchange first and last elements in a list
Differences and Applications of List, Tuple, Set and Dictionary in Python
Appending to list in Python dictionary
Python Program for simple interest
Python Program for Merge Sort
Python Program for n-th Fibonacci number
Python | Find most frequent element in a list
Python | Remove spaces from a string
Python Program to find largest element in an array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 521,
"s": 54,
"text": "Prerequisite: Object Oriented Programming in PythonLet’s write a simple Python program using OOP concept to perform some simple bank operations like deposit and withdrawal of money.First of all, define class Bankacccount. This step is followed by defining a function using __init__. It is run as soon as an object of a class is instantiated. This __init__ method is useful to do any initialization you want to do with object, then we have the default argument self. "
},
{
"code": null,
"e": 529,
"s": 521,
"text": "Python3"
},
{
"code": "# BankAccount classclass Bankaccount: def __init__(self):",
"e": 590,
"s": 529,
"text": null
},
{
"code": null,
"e": 882,
"s": 590,
"text": "This step is followed by declaring that balance is 0 using self argument then we simply print a statement welcoming to Machine. In function deposit and withdraw , amount is taken as input(in float) and is then added/subtracted to the balance. Thus resultant balance is printed in next line. "
},
{
"code": null,
"e": 890,
"s": 882,
"text": "Python3"
},
{
"code": "# Function to deposite amountdef deposit(self): amount = float(input(\"Enter amount to be deposited: \")) self.balance += amount print(\"\\n Amount Deposited:\", amount)",
"e": 1076,
"s": 890,
"text": null
},
{
"code": null,
"e": 1207,
"s": 1076,
"text": "Use an if condition to check whether there is a sufficient amount of money available in the account to process a fund withdrawal. "
},
{
"code": null,
"e": 1215,
"s": 1207,
"text": "Python3"
},
{
"code": "# Function to withdraw the amountdef withdraw(self): amount = float(input(\"Enter amount to be withdrawn: \")) if self.balance >= amount: self.balance -= amount print(\"\\n You Withdrew:\", amount) else: print(\"\\n Insufficient balance \")",
"e": 1503,
"s": 1215,
"text": null
},
{
"code": null,
"e": 1651,
"s": 1503,
"text": "Next, we use a display function to display the remaining balance in the account. Then we create a object and call it to get the program executed. "
},
{
"code": null,
"e": 1659,
"s": 1651,
"text": "Python3"
},
{
"code": "# Function to display the amountdef display(self): print(\"\\n Net Available Balance =\", self.balance)",
"e": 1767,
"s": 1659,
"text": null
},
{
"code": null,
"e": 1798,
"s": 1767,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 1806,
"s": 1798,
"text": "Python3"
},
{
"code": "# Python program to create Bankaccount class# with both a deposit() and a withdraw() functionclass Bank_Account: def __init__(self): self.balance=0 print(\"Hello!!! Welcome to the Deposit & Withdrawal Machine\") def deposit(self): amount=float(input(\"Enter amount to be Deposited: \")) self.balance += amount print(\"\\n Amount Deposited:\",amount) def withdraw(self): amount = float(input(\"Enter amount to be Withdrawn: \")) if self.balance>=amount: self.balance-=amount print(\"\\n You Withdrew:\", amount) else: print(\"\\n Insufficient balance \") def display(self): print(\"\\n Net Available Balance=\",self.balance) # Driver code # creating an object of classs = Bank_Account() # Calling functions with that class objects.deposit()s.withdraw()s.display()",
"e": 2665,
"s": 1806,
"text": null
},
{
"code": null,
"e": 2675,
"s": 2665,
"text": "Output: "
},
{
"code": null,
"e": 2864,
"s": 2675,
"text": "Hello !!! Welcome to Deposit&Withdrawal Machine\nEnter amount to be deposited: \n Amount Deposited: 1000.0\nEnter amount to be withdrawn: \n You Withdrew: 500.0\n\n Net Available Balance = 500.0"
},
{
"code": null,
"e": 2877,
"s": 2866,
"text": "lennyatomz"
},
{
"code": null,
"e": 2890,
"s": 2877,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2906,
"s": 2890,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2924,
"s": 2906,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 2935,
"s": 2924,
"text": "Python-OOP"
},
{
"code": null,
"e": 2955,
"s": 2935,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 2979,
"s": 2955,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2995,
"s": 2979,
"text": "Python Programs"
},
{
"code": null,
"e": 3014,
"s": 2995,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3112,
"s": 3014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3153,
"s": 3112,
"text": "Python Program to check Armstrong Number"
},
{
"code": null,
"e": 3217,
"s": 3153,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 3291,
"s": 3217,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 3330,
"s": 3291,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 3365,
"s": 3330,
"text": "Python Program for simple interest"
},
{
"code": null,
"e": 3395,
"s": 3365,
"text": "Python Program for Merge Sort"
},
{
"code": null,
"e": 3436,
"s": 3395,
"text": "Python Program for n-th Fibonacci number"
},
{
"code": null,
"e": 3482,
"s": 3436,
"text": "Python | Find most frequent element in a list"
},
{
"code": null,
"e": 3519,
"s": 3482,
"text": "Python | Remove spaces from a string"
}
] |
Random Access Iterators in C++ - GeeksforGeeks
|
07 Jan, 2022
After going through the template definition of various STL algorithms like std::nth_element, std::sort, you must have found their template definition consisting of objects of type Random-access Iterator. So what are they and why are they used?
Random-access iterators are one of the five main types of iterators present in C++ Standard Library, others being:
Input iterators
Output iterator
Forward iterator
Bidirectional iterator
Random-access iterators are iterators that can be used to access elements at an arbitrary offset position relative to the element they point to, offering the same functionality as pointers. Random-access iterators are the most complete iterators in terms of functionality. All pointer types are also valid random-access iterators.
It is to be noted that containers like vector, deque support random-access iterators. This means that if we declare normal iterators for them, and then those will be random-access iterators, just like in the case of list, map, multimap, set and multiset they are bidirectional iterators.
Also, note that Iterator algorithms do not depend on the container type. As the iterators provide common usage for all of them, the internal structure of a container does not matter.
So, from the above hierarchy, it can be said that random-access iterators are the strongest of all iterator types.
1) Usability: Random-access iterators can be used in multi-pass algorithms, i.e., an algorithm which involves processing the container several times in various passes.
2) Equality/Inequality Comparison: A Random-access iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.
So, the following two expressions are valid if A and B are Random-access iterators:
A == B // Checking for equality
A != B // Checking for inequality
3) Dereferencing: A random-access iterator can be dereferenced both as an rvalue as well as an lvalue.
CPP
// C++ program to demonstrate Random-Access iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 10, 20, 30, 40, 50 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 7; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;}
7 7 7 7 7
So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a random Access iterator.
4) Incrementable: A Random-access iterator can be incremented, so that it refers to the next element in the sequence, using operator ++(), as seen in the previous code, where i1 was incremented in the for loop.
So, the following two expressions are valid if A is a random-access iterator:
A++ // Using post increment operator
++A // Using pre increment operator
5) Decrementable: Just like we can use operator ++() with Random-access iterators for incrementing them, we can also decrement them.
CPP
// C++ program to demonstrate Random Access iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1 = v1.end() - 1; i1 != v1.begin() - 1; --i1) { cout << (*i1) << " "; } return 0;}
5 4 3 2 1
Since, we are starting from the end of the vector and then moving towards the beginning by decrementing the pointer, which shows that the decrement operator can be used with such iterators.
6) Relational Operators: Although, Bidirectional iterators cannot be used with relational operators like =, random-access iterators being higher in hierarchy support all these relational operators.
If A and B are Random-access iterators, then
A == B // Allowed
A <= B // Allowed
7) Arithmetic Operators: Similar to relational operators, they also can be used with arithmetic operators like +, – and so on. This means that Random-access iterators can move in both the direction and that too randomly.
If A and B are Random-access iterators, then
A + 1 // Allowed
B - 2 // Allowed
CPP
// C++ program to demonstrate Random Access Iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring first iterator vector<int>::iterator i1; // Declaring second iterator vector<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if (i1 < i2) { cout << "Yes"; } // Applying arithmetic operator to them int count = i2 - i1; cout << "\ncount = " << count; return 0;}
Yes
count = 5
Here, since i1 is pointing to beginning and i2 is pointing to end, so i2 will be greater than i1 and also a difference between them will be the total distance between them.
8) Use of offset dereference operator ([ ]): Random-access iterators support offset dereference operator ([ ]), which is used for random-access.
If A is a Random-access iterator, then
A[3] // Allowed
CPP
// C++ program to demonstrate Random Access iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; int i; // Accessing elements using offset dereference // operator [ ] for (i = 0; i < 5; ++i) { cout << v1[i] << " "; } return 0;}
1 2 3 4 5
9) Swappable: The value pointed to by these iterators can be exchanged or swapped.
Practical implementation: After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, Random-access iterators can be used for all purposes and in every scenario. The following STL algorithm shows one of its practical implementations:
std::random_shuffle: As we know this algorithm is used to randomly shuffle all the elements present in a container. So, let us look at its internal working (Do not go into detail just look where random-access iterators can be used):
// Definition of std::random_shuffle()
template void random_shuffle(RandomAccessIterator first,
RandomAccessIterator last,
RandomNumberGenerator& gen)
{
iterator_traits::difference_type i, n;
n = (last - first);
for (i = n - 1; i > 0; --i) {
swap(first[i], first[gen(i + 1)]);
}
}
Here, we can see that we have made use of Random-access iterators, as there is no other type of iterator that supports arithmetic operators, that is why we have used it.
In fact, if you are thinking of uses of random-access iterators, then you can use random-access iterator in place of any other type of iterator since it is the strongest and the best type of iterator available in the C++ Standard library.
This article is contributed by Mrigendra Singh. 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.
anshikajain26
cpp-iterator
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Constructors in C++
Operator Overloading in C++
Templates in C++ with Examples
Socket Programming in C/C++
Polymorphism in C++
Object Oriented Programming in C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 25999,
"s": 25755,
"text": "After going through the template definition of various STL algorithms like std::nth_element, std::sort, you must have found their template definition consisting of objects of type Random-access Iterator. So what are they and why are they used?"
},
{
"code": null,
"e": 26114,
"s": 25999,
"text": "Random-access iterators are one of the five main types of iterators present in C++ Standard Library, others being:"
},
{
"code": null,
"e": 26130,
"s": 26114,
"text": "Input iterators"
},
{
"code": null,
"e": 26146,
"s": 26130,
"text": "Output iterator"
},
{
"code": null,
"e": 26164,
"s": 26146,
"text": "Forward iterator "
},
{
"code": null,
"e": 26187,
"s": 26164,
"text": "Bidirectional iterator"
},
{
"code": null,
"e": 26518,
"s": 26187,
"text": "Random-access iterators are iterators that can be used to access elements at an arbitrary offset position relative to the element they point to, offering the same functionality as pointers. Random-access iterators are the most complete iterators in terms of functionality. All pointer types are also valid random-access iterators."
},
{
"code": null,
"e": 26807,
"s": 26518,
"text": "It is to be noted that containers like vector, deque support random-access iterators. This means that if we declare normal iterators for them, and then those will be random-access iterators, just like in the case of list, map, multimap, set and multiset they are bidirectional iterators. "
},
{
"code": null,
"e": 26990,
"s": 26807,
"text": "Also, note that Iterator algorithms do not depend on the container type. As the iterators provide common usage for all of them, the internal structure of a container does not matter."
},
{
"code": null,
"e": 27107,
"s": 26992,
"text": "So, from the above hierarchy, it can be said that random-access iterators are the strongest of all iterator types."
},
{
"code": null,
"e": 27275,
"s": 27107,
"text": "1) Usability: Random-access iterators can be used in multi-pass algorithms, i.e., an algorithm which involves processing the container several times in various passes."
},
{
"code": null,
"e": 27521,
"s": 27275,
"text": "2) Equality/Inequality Comparison: A Random-access iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not."
},
{
"code": null,
"e": 27605,
"s": 27521,
"text": "So, the following two expressions are valid if A and B are Random-access iterators:"
},
{
"code": null,
"e": 27673,
"s": 27605,
"text": "A == B // Checking for equality\nA != B // Checking for inequality"
},
{
"code": null,
"e": 27776,
"s": 27673,
"text": "3) Dereferencing: A random-access iterator can be dereferenced both as an rvalue as well as an lvalue."
},
{
"code": null,
"e": 27780,
"s": 27776,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate Random-Access iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 10, 20, 30, 40, 50 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 7; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}",
"e": 28292,
"s": 27780,
"text": null
},
{
"code": null,
"e": 28303,
"s": 28292,
"text": "7 7 7 7 7 "
},
{
"code": null,
"e": 28439,
"s": 28303,
"text": "So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a random Access iterator. "
},
{
"code": null,
"e": 28650,
"s": 28439,
"text": "4) Incrementable: A Random-access iterator can be incremented, so that it refers to the next element in the sequence, using operator ++(), as seen in the previous code, where i1 was incremented in the for loop."
},
{
"code": null,
"e": 28728,
"s": 28650,
"text": "So, the following two expressions are valid if A is a random-access iterator:"
},
{
"code": null,
"e": 28805,
"s": 28728,
"text": "A++ // Using post increment operator\n++A // Using pre increment operator"
},
{
"code": null,
"e": 28938,
"s": 28805,
"text": "5) Decrementable: Just like we can use operator ++() with Random-access iterators for incrementing them, we can also decrement them."
},
{
"code": null,
"e": 28942,
"s": 28938,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate Random Access iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1 = v1.end() - 1; i1 != v1.begin() - 1; --i1) { cout << (*i1) << \" \"; } return 0;}",
"e": 29335,
"s": 28942,
"text": null
},
{
"code": null,
"e": 29346,
"s": 29335,
"text": "5 4 3 2 1 "
},
{
"code": null,
"e": 29537,
"s": 29346,
"text": "Since, we are starting from the end of the vector and then moving towards the beginning by decrementing the pointer, which shows that the decrement operator can be used with such iterators. "
},
{
"code": null,
"e": 29735,
"s": 29537,
"text": "6) Relational Operators: Although, Bidirectional iterators cannot be used with relational operators like =, random-access iterators being higher in hierarchy support all these relational operators."
},
{
"code": null,
"e": 29825,
"s": 29735,
"text": "If A and B are Random-access iterators, then\n\nA == B // Allowed\nA <= B // Allowed"
},
{
"code": null,
"e": 30046,
"s": 29825,
"text": "7) Arithmetic Operators: Similar to relational operators, they also can be used with arithmetic operators like +, – and so on. This means that Random-access iterators can move in both the direction and that too randomly."
},
{
"code": null,
"e": 30134,
"s": 30046,
"text": "If A and B are Random-access iterators, then\n\nA + 1 // Allowed\nB - 2 // Allowed"
},
{
"code": null,
"e": 30138,
"s": 30134,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate Random Access Iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring first iterator vector<int>::iterator i1; // Declaring second iterator vector<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if (i1 < i2) { cout << \"Yes\"; } // Applying arithmetic operator to them int count = i2 - i1; cout << \"\\ncount = \" << count; return 0;}",
"e": 30750,
"s": 30138,
"text": null
},
{
"code": null,
"e": 30764,
"s": 30750,
"text": "Yes\ncount = 5"
},
{
"code": null,
"e": 30938,
"s": 30764,
"text": "Here, since i1 is pointing to beginning and i2 is pointing to end, so i2 will be greater than i1 and also a difference between them will be the total distance between them. "
},
{
"code": null,
"e": 31083,
"s": 30938,
"text": "8) Use of offset dereference operator ([ ]): Random-access iterators support offset dereference operator ([ ]), which is used for random-access."
},
{
"code": null,
"e": 31142,
"s": 31083,
"text": "If A is a Random-access iterator, then\nA[3] // Allowed "
},
{
"code": null,
"e": 31146,
"s": 31142,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate Random Access iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; int i; // Accessing elements using offset dereference // operator [ ] for (i = 0; i < 5; ++i) { cout << v1[i] << \" \"; } return 0;}",
"e": 31462,
"s": 31146,
"text": null
},
{
"code": null,
"e": 31473,
"s": 31462,
"text": "1 2 3 4 5 "
},
{
"code": null,
"e": 31556,
"s": 31473,
"text": "9) Swappable: The value pointed to by these iterators can be exchanged or swapped."
},
{
"code": null,
"e": 31856,
"s": 31556,
"text": "Practical implementation: After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, Random-access iterators can be used for all purposes and in every scenario. The following STL algorithm shows one of its practical implementations: "
},
{
"code": null,
"e": 32089,
"s": 31856,
"text": "std::random_shuffle: As we know this algorithm is used to randomly shuffle all the elements present in a container. So, let us look at its internal working (Do not go into detail just look where random-access iterators can be used):"
},
{
"code": null,
"e": 32445,
"s": 32089,
"text": "// Definition of std::random_shuffle()\ntemplate void random_shuffle(RandomAccessIterator first,\n RandomAccessIterator last,\n RandomNumberGenerator& gen)\n{\n iterator_traits::difference_type i, n;\n n = (last - first);\n for (i = n - 1; i > 0; --i) {\n swap(first[i], first[gen(i + 1)]);\n }\n}"
},
{
"code": null,
"e": 32615,
"s": 32445,
"text": "Here, we can see that we have made use of Random-access iterators, as there is no other type of iterator that supports arithmetic operators, that is why we have used it."
},
{
"code": null,
"e": 32854,
"s": 32615,
"text": "In fact, if you are thinking of uses of random-access iterators, then you can use random-access iterator in place of any other type of iterator since it is the strongest and the best type of iterator available in the C++ Standard library."
},
{
"code": null,
"e": 33278,
"s": 32854,
"text": "This article is contributed by Mrigendra Singh. 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": 33292,
"s": 33278,
"text": "anshikajain26"
},
{
"code": null,
"e": 33305,
"s": 33292,
"text": "cpp-iterator"
},
{
"code": null,
"e": 33309,
"s": 33305,
"text": "STL"
},
{
"code": null,
"e": 33313,
"s": 33309,
"text": "C++"
},
{
"code": null,
"e": 33317,
"s": 33313,
"text": "STL"
},
{
"code": null,
"e": 33321,
"s": 33317,
"text": "CPP"
},
{
"code": null,
"e": 33419,
"s": 33321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33438,
"s": 33419,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 33462,
"s": 33438,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 33486,
"s": 33462,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 33506,
"s": 33486,
"text": "Constructors in C++"
},
{
"code": null,
"e": 33534,
"s": 33506,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 33565,
"s": 33534,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 33593,
"s": 33565,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 33613,
"s": 33593,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 33648,
"s": 33613,
"text": "Object Oriented Programming in C++"
}
] |
Web scraping with Scrapy : Practical Understanding | by Karthikeyan P | Jul, 2020 | Towards Data Science | Towards Data Science
|
With all the theoretical aspects of using Scrapy being dealt with in part-1, it’s now time for some practical examples. I shall put these theoretical aspects into examples of increasing complexity. There are 3 examples,
An example demonstrating single request & response by extracting a city’s weather from a weather site
An example demonstrating multiple requests & responses by extracting book details from a dummy online book store
An example demonstrating image scraping
You can download these examples from my GitHub page. This is the second part of a 4 part tutorial series on web scraping using Scrapy and Selenium. The other parts can be found at
Part 1: Web scraping with Scrapy: Theoretical Understanding
Part 3: Web scraping with Selenium
Part 4: Web scraping with Selenium & Scrapy
Important note:Before you try to scrape any website, please go through its robots.txt file. It can be accessed like www.google.com/robots.txt. There, you will see a list of pages allowed and disallowed for scraping google’s website. You can access only those pages that fall under User-agent: * and those that follow Allow:.
Our goal for this example is to extract today’s ‘Chennai’ city weather report from weather.com. The extracted data must contain temperature, air quality and condition/description. You are free to choose your city. Just provide the URL to your city in the spider’s code. As pointed out earlier, the site allows data to be scraped provided there is a crawl delay of no less than 10 seconds i.e. you have to wait at least 10 seconds before requesting another URL from weather.com. This can be found in the site’s robots.txt.
User-agent: *# Crawl-delay: 10
I have created a new Scrapy project using scrapy startproject command and created a basic spider using
scrapy genspider -t basic weather_spider weather.com
The first task while starting to code is to adhere to the site’s policy. To adhere to weather.com’s crawl delay policy, we need to add the following line to our scrapy project’s settings.py file.
DOWNLOAD_DELAY = 10
This line makes the spiders in our project to wait 10 seconds before making a new URL request. We can now start to code our spider.
As shown earlier, the template code is generated. I have made some modifications to the code.
import scrapyimport refrom ..items import WeatherItemclass WeatherSpiderSpider(scrapy.Spider): name = "weather_spider" allowed_domains = ["weather.com"]def start_requests(self): # Weather.com URL for Chennai's weather urls = [ "https://weather.com/en-IN/weather/today/l/bf01d09009561812f3f95abece23d16e123d8c08fd0b8ec7ffc9215c0154913c" ] for url in urls: yield scrapy.Request(url=url, callback=self.parse_url)def parse_url(self, response):# Extracting city, temperature, air quality and condition from the response using XPath city = response.xpath('//h1[contains(@class,"location")]/text()').get() temp = response.xpath('//span[@data-testid="TemperatureValue"]/text()').get() air_quality = response.xpath('//span[@data-testid="AirQualityCategory"]/text()').get() cond = response.xpath('//div[@data-testid="wxPhrase"]/text()').get()temp = re.match(r"(\d+)", temp).group(1) + " C" # Removing the degree symbol and adding C city = re.match(r"^(.*)(?: Weather)", city).group(1) # Removing 'Weather' from location# Yielding the extracted data as Item object. You may also extract as Dictionary item = WeatherItem() item["city"] = city item["temp"] = temp item["air_quality"] = air_quality item["cond"] = cond yield item
I think the code for this example is self-explanatory. I will, however, explain the flow. I hope you can remember the overall flow diagram of Scrapy from the last part. I wish to be in control of making requests, so I use start_requests() instead of start_urls. Inside the start_requests() the URL for Chennai's weather page is specified. If you wish to change it to your preferred city or add more cities feel free to do it. For every URL in the list of URLs, generate a request and yield it. All of these requests will reach the Scheduler, which will then dispatch the requests whenever Engine asks for a request. After the webpage corresponding to the request is downloaded by the Downloader, the response is sent back to the engine which directs it to the respective spider. In this case, WeatherSpider receives the response and calls the callback function parse_url(). Inside this function, I have used XPath to extract the required data from the response.
You may understand till this part, the next part of the code would be new to you since it has not yet been explained. I have made use of Scrapy Items. These are Python objects that define key-value pairs. You can refer to this link to explore more about Items. If you do not wish to make use of Items, you can create a dictionary and yield it instead. A question may arise, where to define these so-called items. Allow me to refresh your memory. While creating a new project, we saw some files being created by Scrapy. Remember?
weather/├── scrapy.cfg└── weather ├── __init__.py ├── items.py ├── middlewares.py ├── pipelines.py ├── __pycache__ ├── settings.py └── spiders ├── WeatherSpider.py ├── __init__.py └── __pycache__
If you look patiently along this tree, you may notice a file named items.py. It is into this file, you need to define the Item objects.
# -*- coding: utf-8 -*-# Define here the models for your scraped items## See documentation in:# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass WeatherItem(scrapy.Item): city = scrapy.Field() temp = scrapy.Field() air_quality = scrapy.Field() cond = scrapy.Field()
Scrapy would have created the class, all you need to do is define the key-value pairs. In this example, since we need city name, temperature, air quality and condition, I have created 4 items. You can create any number of items as required by your project.
When you run the project using the following command, a JSON file containing the scraped items would be created.
scrapy crawl weather_spider -o output.json
The contents would look like,
output.json------------[{"city": "Chennai, Tamil Nadu", "temp": "31 C", "air_quality": "Good", "cond": "Cloudy"}]
Hurray!!. You have successfully executed a simple Scrapy project handling a single request and response.
Our goal for this example is to scrape the details of all the books (1000 to be exact) from the website books.toscrape.com. Do not worry about robots.txt. This site is specifically designed and hosted for the purpose of practising web scraping. So, you are in the clear. This website is designed in such a way that it has 50 pages with each page listing 20 books. You cannot extract book details from the listing page. You have to navigate to individual book’s webpage to extract the required details. This is a scenario which requires crawling multiple webpages, so I will be using Crawl Spider.Like the previous example, I have created a new project and a crawling spider using scrapy startproject and
scrapy genspider -t crawl crawl_spider books.toscrape.com
For this example, I will be extracting title of the book, its price, rating and availability. The items.py file would look like this.
class BookstoscrapeItem(scrapy.Item): title = scrapy.Field() price = scrapy.Field() rating = scrapy.Field() availability = scrapy.Field()
Now that everything needed for the project is ready, let us look into crawl_spider.py.
class CrawlSpiderSpider(CrawlSpider): name = "crawl_spider" allowed_domains = ["books.toscrape.com"] # start_urls = ["http://books.toscrape.com/"] # when trying to use this, comment start_requests()rules = (Rule(LinkExtractor(allow=r"catalogue/"), callback="parse_books", follow=True),)def start_requests(self): url = "http://books.toscrape.com/" yield scrapy.Request(url)def parse_books(self, response): """ Filtering out pages other than books' pages to avoid getting "NotFound" error. Because, other pages would not have any 'div' tag with attribute 'class="col-sm-6 product_main"' """ if response.xpath('//div[@class="col-sm-6 product_main"]').get() is not None: title = response.xpath('//div[@class="col-sm-6 product_main"]/h1/text()').get() price = response.xpath('//div[@class="col-sm-6 product_main"]/p[@class="price_color"]/text()').get() stock = ( response.xpath('//div[@class="col-sm-6 product_main"]/p[@class="instock availability"]/text()') .getall()[-1] .strip() ) rating = response.xpath('//div[@class="col-sm-6 product_main"]/p[3]/@class').get()# Yielding the extracted data as Item object. item = BookstoscrapeItem() item["title"] = title item["price"] = price item["rating"] = rating item["availability"] = stock yield item
Have you noticed a change in start_requests()? Why am I generating a request without a callback? Was I the one who said every request must have a corresponding callback in last part? If you had these questions, I applaud your attention to detail and critical reasoning. Kudos to you!! Enough of beating around the bush and let me get back to answering your questions. I have not included a callback in the initial request because rules have the callback specified in it along with the URL using which subsequent requests are to be made.
The flow would start with me explicitly generating a request with http://books.toscrape.com. Immediately it is followed by the LinkExtractor extracting links with the pattern http://books.toscrape.com/catalogue/. The crawling spider starts generating requests with all the URLs that the LinkExtractor has created with parse_books as the callback function. These requests are sent to the Scheduler, which in turn dispatches requests when the Engine asks. The usual flow, like before, continues until no more requests are left at the Scheduler. When you run this spider using a JSON output, you would get 1000 books' details.
scrapy crawl crawl_spider -o crawl_spider_output.json
Sample output is shown below.
[ { "title": "A Light in the Attic", "price": "\u00a351.77", "rating": "star-rating Three", "availability": "In stock (22 available)" }, { "title": "Libertarianism for Beginners", "price": "\u00a351.33", "rating": "star-rating Two", "availability": "In stock (19 available)" }, ...]#Note: /u00a3 is the unicode representation of £
As mentioned before, this is not the only way of extracting the details of all 1000 books. A basic spider can also be used to extract the exact details. I have included the code using a basic spider that does the same. Create a basic spider using the following command.
scrapy genspider -t basic book_spider books.toscrape.com
The basic spider contains the following code.
class BookSpiderSpider(scrapy.Spider): name = "book_spider" allowed_domains = ["books.toscrape.com"]def start_requests(self): urls = ["http://books.toscrape.com/"] for url in urls: yield scrapy.Request(url=url, callback=self.parse_pages)def parse_pages(self, response): """ The purpose of this method is to look for books listing and the link for next page. - When it sees books listing, it generates requests with individual book's URL with parse_books() as its callback function. - When it sees a next page URL, it generates a request for the next page by calling itself as the callback function. """books = response.xpath("//h3")""" Using response.urljoin() to get individual book page """ """ for book in books: book_url = response.urljoin(book.xpath(".//a/@href").get()) yield scrapy.Request(url=book_url, callback=self.parse_books) """""" Using response.follow() to get individual book page """ for book in books: yield response.follow(url=book.xpath(".//a/@href").get(), callback=self.parse_books)""" Using response. urljoin() to get next page """ """ next_page_url = response.xpath('//li[@class="next"]/a/@href').get() if next_page_url is not None: next_page = response.urljoin(next_page_url) yield scrapy.Request(url=next_page, callback=self.parse_pages) """""" Using response.follow() to get next page """ next_page_url = response.xpath('//li[@class="next"]/a/@href').get() if next_page_url is not None: yield response.follow(url=next_page_url, callback=self.parse_pages)def parse_books(self, response): """ Method to extract book details and yield it as Item object """title = response.xpath('//div[@class="col-sm-6 product_main"]/h1/text()').get() price = response.xpath('//div[@class="col-sm-6 product_main"]/p[@class="price_color"]/text()').get() stock = ( response.xpath('//div[@class="col-sm-6 product_main"]/p[@class="instock availability"]/text()') .getall()[-1] .strip() ) rating = response.xpath('//div[@class="col-sm-6 product_main"]/p[3]/@class').get()item = BookstoscrapeItem() item["title"] = title item["price"] = price item["rating"] = rating item["availability"] = stock yield item
Have you noticed the same parse_books() method in both the spiders? Method of extracting book details is the same. The only difference is that I have replaced rules in crawling spider with a dedicated and long function parse_pages() in the basic spider. I hope this shows you the distinction between crawling spider and basic spider.
Before starting with this example, let us look at a brief overview of how Scrapy scrapes and processes files and images. To scrape files or images from webpages, you need to use in-built pipelines, specifically, FilesPipeline or ImagesPipeline, for the respective purpose. I will explain the typical workflow when using FilesPipeline.
You have to use a Spider to scrape an item and put the URLs of the desired file into a file_urls field.You then return the item, which then goes into the item pipeline.When the item reaches the FilesPipeline, the URLs in the file_urls are sent to the Scheduler to be downloaded by the Downloader. The only difference is that these file_urls are given higher priority and downloaded before processing any other requests.When the files are downloaded, another field files will be populated with the results. It will comprise of the actual download URL, a relative path where it is stored, its checksum and the status.
You have to use a Spider to scrape an item and put the URLs of the desired file into a file_urls field.
You then return the item, which then goes into the item pipeline.
When the item reaches the FilesPipeline, the URLs in the file_urls are sent to the Scheduler to be downloaded by the Downloader. The only difference is that these file_urls are given higher priority and downloaded before processing any other requests.
When the files are downloaded, another field files will be populated with the results. It will comprise of the actual download URL, a relative path where it is stored, its checksum and the status.
FilesPipeline can be used to scrape different types of files (images, pdfs, texts, etc.). ImagesPipeline is specialized for scraping and processing images. Apart from the functionalities of FilesPipeline, it does the following:
Convert all downloaded images to JPG format and RGB mode
Generates thumbnails
Check image width/height to make sure they meet a minimum constraint
Also, file names are different. Please use image_urls and images in place of file_urls and files while working with ImagesPipeline. If you wish to know more about files and images processing, you can always follow this link.
Our goal for this example is to scrape the cover images of all the books from the website books.toscrape.com. I will be repurposing the Crawl Spider from the previous example to achieve our goal. There is one important step to be done before starting with code. You need to set up the ImagesPipeline. To do this, add the following two lines to settings.py file in the project folder.
ITEM_PIPELINES = {"scrapy.pipelines.images.ImagesPipeline": 1}IMAGES_STORE = "path/to/store/images"
Now you are ready to code. Since I am reusing the crawling spider, there would be no significant difference to the crawling spider’s code. The only difference is that you need to create Item objects containing images, image_urls and yield it from the spider.
# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom ..items import ImagescraperItemimport reclass ImageCrawlSpiderSpider(CrawlSpider): name = "image_crawl_spider" allowed_domains = ["books.toscrape.com"] # start_urls = ["http://books.toscrape.com/"]def start_requests(self): url = "http://books.toscrape.com/" yield scrapy.Request(url=url)rules = (Rule(LinkExtractor(allow=r"catalogue/"), callback="parse_image", follow=True),)def parse_image(self, response): if response.xpath('//div[@class="item active"]/img').get() is not None: img = response.xpath('//div[@class="item active"]/img/@src').get()""" Computing the Absolute path of the image file. "image_urls" require absolute path, not relative path """ m = re.match(r"^(?:../../)(.*)$", img).group(1) url = "http://books.toscrape.com/" img_url = "".join([url, m])image = ImagescraperItem() image["image_urls"] = [img_url] # "image_urls" must be a listyield image
The items.py file would look like.
import scrapyclass ImagescraperItem(scrapy.Item): images = scrapy.Field() image_urls = scrapy.Field()
When you run the spider with an output file, the spider would crawl all the webpages of the http://books.toscrape.com, scrape URLs of the books’ covers and yield it as image_urls, which would then be sent to the Scheduler and the workflow continues as detailed at the beginning of this example.
scrapy crawl image_crawl_spider -o output.json
The downloaded images would be stored at the location specified by IMAGES_STORE and the output.json will look like this.
[ { "image_urls": [ "http://books.toscrape.com/media/cache/ee/cf/eecfe998905e455df12064dba399c075.jpg" ], "images": [ { "url": "http://books.toscrape.com/media/cache/ee/cf/eecfe998905e455df12064dba399c075.jpg", "path": "full/59d0249d6ae2eeb367e72b04740583bc70f81558.jpg", "checksum": "693caff3d97645e73bd28da8e5974946", "status": "downloaded" } ] }, { "image_urls": [ "http://books.toscrape.com/media/cache/08/e9/08e94f3731d7d6b760dfbfbc02ca5c62.jpg" ], "images": [ { "url": "http://books.toscrape.com/media/cache/08/e9/08e94f3731d7d6b760dfbfbc02ca5c62.jpg", "path": "full/1c1a130c161d186db9973e70558b6ec221ce7c4e.jpg", "checksum": "e3953238c2ff7ac507a4bed4485c8622", "status": "downloaded" } ] }, ...]
If you wish to scrape other files of different format, you can use FilesPipeline instead. I will leave this to your curiosity. You can download these 3 examples from this link.
Beginners, who are enthusiastic about web scraping, might go overboard and scrape websites at an increased rate which might result is their IP getting banned/blacklisted from the website. Some websites implement certain measures to prevent bots from crawling them, with varying degrees of sophistication.
The following are some tips to keep in mind when dealing with these kinds of sites and it is taken from Scrapy Common Practices:
Rotate your user agent from a pool of well-known ones from browsers (google around to get a list of them).
Disable cookies (see COOKIES_ENABLED) as some sites may use cookies to spot bot behaviour.
Use download delays (2 or higher). See DOWNLOAD_DELAY setting.
If possible, use Google cache to fetch pages, instead of hitting the sites directly
Use a pool of rotating IPs. For example, the free Tor project or paid services like ProxyMesh. An open-source alternative is scrapoxy, a super proxy that you can attach your own proxies to.
Use a highly distributed downloader that circumvents bans internally, so you can just focus on parsing clean pages. One example of such downloaders is Crawlera
As my goal is to make you work confidently with Scrapy after reading this tutorial, I have restrained myself from diving into various intricate aspects of Scrapy. But, I hope that I have introduced you to the concept and practice of working with Scrapy with a clear distinction between basic and crawling spiders. If you are interested in swimming to the deeper end of this pool, feel free to take the guidance of Scrapy official documentation that can be reached by clicking here.
In the next part of this web scraping series, we shall be looking at Selenium.
Till then, Good luck. Stay safe and happy learning.!
|
[
{
"code": null,
"e": 392,
"s": 172,
"text": "With all the theoretical aspects of using Scrapy being dealt with in part-1, it’s now time for some practical examples. I shall put these theoretical aspects into examples of increasing complexity. There are 3 examples,"
},
{
"code": null,
"e": 494,
"s": 392,
"text": "An example demonstrating single request & response by extracting a city’s weather from a weather site"
},
{
"code": null,
"e": 607,
"s": 494,
"text": "An example demonstrating multiple requests & responses by extracting book details from a dummy online book store"
},
{
"code": null,
"e": 647,
"s": 607,
"text": "An example demonstrating image scraping"
},
{
"code": null,
"e": 827,
"s": 647,
"text": "You can download these examples from my GitHub page. This is the second part of a 4 part tutorial series on web scraping using Scrapy and Selenium. The other parts can be found at"
},
{
"code": null,
"e": 887,
"s": 827,
"text": "Part 1: Web scraping with Scrapy: Theoretical Understanding"
},
{
"code": null,
"e": 922,
"s": 887,
"text": "Part 3: Web scraping with Selenium"
},
{
"code": null,
"e": 966,
"s": 922,
"text": "Part 4: Web scraping with Selenium & Scrapy"
},
{
"code": null,
"e": 1291,
"s": 966,
"text": "Important note:Before you try to scrape any website, please go through its robots.txt file. It can be accessed like www.google.com/robots.txt. There, you will see a list of pages allowed and disallowed for scraping google’s website. You can access only those pages that fall under User-agent: * and those that follow Allow:."
},
{
"code": null,
"e": 1813,
"s": 1291,
"text": "Our goal for this example is to extract today’s ‘Chennai’ city weather report from weather.com. The extracted data must contain temperature, air quality and condition/description. You are free to choose your city. Just provide the URL to your city in the spider’s code. As pointed out earlier, the site allows data to be scraped provided there is a crawl delay of no less than 10 seconds i.e. you have to wait at least 10 seconds before requesting another URL from weather.com. This can be found in the site’s robots.txt."
},
{
"code": null,
"e": 1844,
"s": 1813,
"text": "User-agent: *# Crawl-delay: 10"
},
{
"code": null,
"e": 1947,
"s": 1844,
"text": "I have created a new Scrapy project using scrapy startproject command and created a basic spider using"
},
{
"code": null,
"e": 2000,
"s": 1947,
"text": "scrapy genspider -t basic weather_spider weather.com"
},
{
"code": null,
"e": 2196,
"s": 2000,
"text": "The first task while starting to code is to adhere to the site’s policy. To adhere to weather.com’s crawl delay policy, we need to add the following line to our scrapy project’s settings.py file."
},
{
"code": null,
"e": 2216,
"s": 2196,
"text": "DOWNLOAD_DELAY = 10"
},
{
"code": null,
"e": 2348,
"s": 2216,
"text": "This line makes the spiders in our project to wait 10 seconds before making a new URL request. We can now start to code our spider."
},
{
"code": null,
"e": 2442,
"s": 2348,
"text": "As shown earlier, the template code is generated. I have made some modifications to the code."
},
{
"code": null,
"e": 3793,
"s": 2442,
"text": "import scrapyimport refrom ..items import WeatherItemclass WeatherSpiderSpider(scrapy.Spider): name = \"weather_spider\" allowed_domains = [\"weather.com\"]def start_requests(self): # Weather.com URL for Chennai's weather urls = [ \"https://weather.com/en-IN/weather/today/l/bf01d09009561812f3f95abece23d16e123d8c08fd0b8ec7ffc9215c0154913c\" ] for url in urls: yield scrapy.Request(url=url, callback=self.parse_url)def parse_url(self, response):# Extracting city, temperature, air quality and condition from the response using XPath city = response.xpath('//h1[contains(@class,\"location\")]/text()').get() temp = response.xpath('//span[@data-testid=\"TemperatureValue\"]/text()').get() air_quality = response.xpath('//span[@data-testid=\"AirQualityCategory\"]/text()').get() cond = response.xpath('//div[@data-testid=\"wxPhrase\"]/text()').get()temp = re.match(r\"(\\d+)\", temp).group(1) + \" C\" # Removing the degree symbol and adding C city = re.match(r\"^(.*)(?: Weather)\", city).group(1) # Removing 'Weather' from location# Yielding the extracted data as Item object. You may also extract as Dictionary item = WeatherItem() item[\"city\"] = city item[\"temp\"] = temp item[\"air_quality\"] = air_quality item[\"cond\"] = cond yield item"
},
{
"code": null,
"e": 4755,
"s": 3793,
"text": "I think the code for this example is self-explanatory. I will, however, explain the flow. I hope you can remember the overall flow diagram of Scrapy from the last part. I wish to be in control of making requests, so I use start_requests() instead of start_urls. Inside the start_requests() the URL for Chennai's weather page is specified. If you wish to change it to your preferred city or add more cities feel free to do it. For every URL in the list of URLs, generate a request and yield it. All of these requests will reach the Scheduler, which will then dispatch the requests whenever Engine asks for a request. After the webpage corresponding to the request is downloaded by the Downloader, the response is sent back to the engine which directs it to the respective spider. In this case, WeatherSpider receives the response and calls the callback function parse_url(). Inside this function, I have used XPath to extract the required data from the response."
},
{
"code": null,
"e": 5284,
"s": 4755,
"text": "You may understand till this part, the next part of the code would be new to you since it has not yet been explained. I have made use of Scrapy Items. These are Python objects that define key-value pairs. You can refer to this link to explore more about Items. If you do not wish to make use of Items, you can create a dictionary and yield it instead. A question may arise, where to define these so-called items. Allow me to refresh your memory. While creating a new project, we saw some files being created by Scrapy. Remember?"
},
{
"code": null,
"e": 5522,
"s": 5284,
"text": "weather/├── scrapy.cfg└── weather ├── __init__.py ├── items.py ├── middlewares.py ├── pipelines.py ├── __pycache__ ├── settings.py └── spiders ├── WeatherSpider.py ├── __init__.py └── __pycache__"
},
{
"code": null,
"e": 5658,
"s": 5522,
"text": "If you look patiently along this tree, you may notice a file named items.py. It is into this file, you need to define the Item objects."
},
{
"code": null,
"e": 5957,
"s": 5658,
"text": "# -*- coding: utf-8 -*-# Define here the models for your scraped items## See documentation in:# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass WeatherItem(scrapy.Item): city = scrapy.Field() temp = scrapy.Field() air_quality = scrapy.Field() cond = scrapy.Field()"
},
{
"code": null,
"e": 6214,
"s": 5957,
"text": "Scrapy would have created the class, all you need to do is define the key-value pairs. In this example, since we need city name, temperature, air quality and condition, I have created 4 items. You can create any number of items as required by your project."
},
{
"code": null,
"e": 6327,
"s": 6214,
"text": "When you run the project using the following command, a JSON file containing the scraped items would be created."
},
{
"code": null,
"e": 6370,
"s": 6327,
"text": "scrapy crawl weather_spider -o output.json"
},
{
"code": null,
"e": 6400,
"s": 6370,
"text": "The contents would look like,"
},
{
"code": null,
"e": 6514,
"s": 6400,
"text": "output.json------------[{\"city\": \"Chennai, Tamil Nadu\", \"temp\": \"31 C\", \"air_quality\": \"Good\", \"cond\": \"Cloudy\"}]"
},
{
"code": null,
"e": 6619,
"s": 6514,
"text": "Hurray!!. You have successfully executed a simple Scrapy project handling a single request and response."
},
{
"code": null,
"e": 7323,
"s": 6619,
"text": "Our goal for this example is to scrape the details of all the books (1000 to be exact) from the website books.toscrape.com. Do not worry about robots.txt. This site is specifically designed and hosted for the purpose of practising web scraping. So, you are in the clear. This website is designed in such a way that it has 50 pages with each page listing 20 books. You cannot extract book details from the listing page. You have to navigate to individual book’s webpage to extract the required details. This is a scenario which requires crawling multiple webpages, so I will be using Crawl Spider.Like the previous example, I have created a new project and a crawling spider using scrapy startproject and"
},
{
"code": null,
"e": 7381,
"s": 7323,
"text": "scrapy genspider -t crawl crawl_spider books.toscrape.com"
},
{
"code": null,
"e": 7515,
"s": 7381,
"text": "For this example, I will be extracting title of the book, its price, rating and availability. The items.py file would look like this."
},
{
"code": null,
"e": 7665,
"s": 7515,
"text": "class BookstoscrapeItem(scrapy.Item): title = scrapy.Field() price = scrapy.Field() rating = scrapy.Field() availability = scrapy.Field()"
},
{
"code": null,
"e": 7752,
"s": 7665,
"text": "Now that everything needed for the project is ready, let us look into crawl_spider.py."
},
{
"code": null,
"e": 9211,
"s": 7752,
"text": "class CrawlSpiderSpider(CrawlSpider): name = \"crawl_spider\" allowed_domains = [\"books.toscrape.com\"] # start_urls = [\"http://books.toscrape.com/\"] # when trying to use this, comment start_requests()rules = (Rule(LinkExtractor(allow=r\"catalogue/\"), callback=\"parse_books\", follow=True),)def start_requests(self): url = \"http://books.toscrape.com/\" yield scrapy.Request(url)def parse_books(self, response): \"\"\" Filtering out pages other than books' pages to avoid getting \"NotFound\" error. Because, other pages would not have any 'div' tag with attribute 'class=\"col-sm-6 product_main\"' \"\"\" if response.xpath('//div[@class=\"col-sm-6 product_main\"]').get() is not None: title = response.xpath('//div[@class=\"col-sm-6 product_main\"]/h1/text()').get() price = response.xpath('//div[@class=\"col-sm-6 product_main\"]/p[@class=\"price_color\"]/text()').get() stock = ( response.xpath('//div[@class=\"col-sm-6 product_main\"]/p[@class=\"instock availability\"]/text()') .getall()[-1] .strip() ) rating = response.xpath('//div[@class=\"col-sm-6 product_main\"]/p[3]/@class').get()# Yielding the extracted data as Item object. item = BookstoscrapeItem() item[\"title\"] = title item[\"price\"] = price item[\"rating\"] = rating item[\"availability\"] = stock yield item"
},
{
"code": null,
"e": 9748,
"s": 9211,
"text": "Have you noticed a change in start_requests()? Why am I generating a request without a callback? Was I the one who said every request must have a corresponding callback in last part? If you had these questions, I applaud your attention to detail and critical reasoning. Kudos to you!! Enough of beating around the bush and let me get back to answering your questions. I have not included a callback in the initial request because rules have the callback specified in it along with the URL using which subsequent requests are to be made."
},
{
"code": null,
"e": 10372,
"s": 9748,
"text": "The flow would start with me explicitly generating a request with http://books.toscrape.com. Immediately it is followed by the LinkExtractor extracting links with the pattern http://books.toscrape.com/catalogue/. The crawling spider starts generating requests with all the URLs that the LinkExtractor has created with parse_books as the callback function. These requests are sent to the Scheduler, which in turn dispatches requests when the Engine asks. The usual flow, like before, continues until no more requests are left at the Scheduler. When you run this spider using a JSON output, you would get 1000 books' details."
},
{
"code": null,
"e": 10426,
"s": 10372,
"text": "scrapy crawl crawl_spider -o crawl_spider_output.json"
},
{
"code": null,
"e": 10456,
"s": 10426,
"text": "Sample output is shown below."
},
{
"code": null,
"e": 10816,
"s": 10456,
"text": "[ { \"title\": \"A Light in the Attic\", \"price\": \"\\u00a351.77\", \"rating\": \"star-rating Three\", \"availability\": \"In stock (22 available)\" }, { \"title\": \"Libertarianism for Beginners\", \"price\": \"\\u00a351.33\", \"rating\": \"star-rating Two\", \"availability\": \"In stock (19 available)\" }, ...]#Note: /u00a3 is the unicode representation of £"
},
{
"code": null,
"e": 11086,
"s": 10816,
"text": "As mentioned before, this is not the only way of extracting the details of all 1000 books. A basic spider can also be used to extract the exact details. I have included the code using a basic spider that does the same. Create a basic spider using the following command."
},
{
"code": null,
"e": 11143,
"s": 11086,
"text": "scrapy genspider -t basic book_spider books.toscrape.com"
},
{
"code": null,
"e": 11189,
"s": 11143,
"text": "The basic spider contains the following code."
},
{
"code": null,
"e": 13617,
"s": 11189,
"text": "class BookSpiderSpider(scrapy.Spider): name = \"book_spider\" allowed_domains = [\"books.toscrape.com\"]def start_requests(self): urls = [\"http://books.toscrape.com/\"] for url in urls: yield scrapy.Request(url=url, callback=self.parse_pages)def parse_pages(self, response): \"\"\" The purpose of this method is to look for books listing and the link for next page. - When it sees books listing, it generates requests with individual book's URL with parse_books() as its callback function. - When it sees a next page URL, it generates a request for the next page by calling itself as the callback function. \"\"\"books = response.xpath(\"//h3\")\"\"\" Using response.urljoin() to get individual book page \"\"\" \"\"\" for book in books: book_url = response.urljoin(book.xpath(\".//a/@href\").get()) yield scrapy.Request(url=book_url, callback=self.parse_books) \"\"\"\"\"\" Using response.follow() to get individual book page \"\"\" for book in books: yield response.follow(url=book.xpath(\".//a/@href\").get(), callback=self.parse_books)\"\"\" Using response. urljoin() to get next page \"\"\" \"\"\" next_page_url = response.xpath('//li[@class=\"next\"]/a/@href').get() if next_page_url is not None: next_page = response.urljoin(next_page_url) yield scrapy.Request(url=next_page, callback=self.parse_pages) \"\"\"\"\"\" Using response.follow() to get next page \"\"\" next_page_url = response.xpath('//li[@class=\"next\"]/a/@href').get() if next_page_url is not None: yield response.follow(url=next_page_url, callback=self.parse_pages)def parse_books(self, response): \"\"\" Method to extract book details and yield it as Item object \"\"\"title = response.xpath('//div[@class=\"col-sm-6 product_main\"]/h1/text()').get() price = response.xpath('//div[@class=\"col-sm-6 product_main\"]/p[@class=\"price_color\"]/text()').get() stock = ( response.xpath('//div[@class=\"col-sm-6 product_main\"]/p[@class=\"instock availability\"]/text()') .getall()[-1] .strip() ) rating = response.xpath('//div[@class=\"col-sm-6 product_main\"]/p[3]/@class').get()item = BookstoscrapeItem() item[\"title\"] = title item[\"price\"] = price item[\"rating\"] = rating item[\"availability\"] = stock yield item"
},
{
"code": null,
"e": 13951,
"s": 13617,
"text": "Have you noticed the same parse_books() method in both the spiders? Method of extracting book details is the same. The only difference is that I have replaced rules in crawling spider with a dedicated and long function parse_pages() in the basic spider. I hope this shows you the distinction between crawling spider and basic spider."
},
{
"code": null,
"e": 14286,
"s": 13951,
"text": "Before starting with this example, let us look at a brief overview of how Scrapy scrapes and processes files and images. To scrape files or images from webpages, you need to use in-built pipelines, specifically, FilesPipeline or ImagesPipeline, for the respective purpose. I will explain the typical workflow when using FilesPipeline."
},
{
"code": null,
"e": 14902,
"s": 14286,
"text": "You have to use a Spider to scrape an item and put the URLs of the desired file into a file_urls field.You then return the item, which then goes into the item pipeline.When the item reaches the FilesPipeline, the URLs in the file_urls are sent to the Scheduler to be downloaded by the Downloader. The only difference is that these file_urls are given higher priority and downloaded before processing any other requests.When the files are downloaded, another field files will be populated with the results. It will comprise of the actual download URL, a relative path where it is stored, its checksum and the status."
},
{
"code": null,
"e": 15006,
"s": 14902,
"text": "You have to use a Spider to scrape an item and put the URLs of the desired file into a file_urls field."
},
{
"code": null,
"e": 15072,
"s": 15006,
"text": "You then return the item, which then goes into the item pipeline."
},
{
"code": null,
"e": 15324,
"s": 15072,
"text": "When the item reaches the FilesPipeline, the URLs in the file_urls are sent to the Scheduler to be downloaded by the Downloader. The only difference is that these file_urls are given higher priority and downloaded before processing any other requests."
},
{
"code": null,
"e": 15521,
"s": 15324,
"text": "When the files are downloaded, another field files will be populated with the results. It will comprise of the actual download URL, a relative path where it is stored, its checksum and the status."
},
{
"code": null,
"e": 15749,
"s": 15521,
"text": "FilesPipeline can be used to scrape different types of files (images, pdfs, texts, etc.). ImagesPipeline is specialized for scraping and processing images. Apart from the functionalities of FilesPipeline, it does the following:"
},
{
"code": null,
"e": 15806,
"s": 15749,
"text": "Convert all downloaded images to JPG format and RGB mode"
},
{
"code": null,
"e": 15827,
"s": 15806,
"text": "Generates thumbnails"
},
{
"code": null,
"e": 15896,
"s": 15827,
"text": "Check image width/height to make sure they meet a minimum constraint"
},
{
"code": null,
"e": 16121,
"s": 15896,
"text": "Also, file names are different. Please use image_urls and images in place of file_urls and files while working with ImagesPipeline. If you wish to know more about files and images processing, you can always follow this link."
},
{
"code": null,
"e": 16505,
"s": 16121,
"text": "Our goal for this example is to scrape the cover images of all the books from the website books.toscrape.com. I will be repurposing the Crawl Spider from the previous example to achieve our goal. There is one important step to be done before starting with code. You need to set up the ImagesPipeline. To do this, add the following two lines to settings.py file in the project folder."
},
{
"code": null,
"e": 16605,
"s": 16505,
"text": "ITEM_PIPELINES = {\"scrapy.pipelines.images.ImagesPipeline\": 1}IMAGES_STORE = \"path/to/store/images\""
},
{
"code": null,
"e": 16864,
"s": 16605,
"text": "Now you are ready to code. Since I am reusing the crawling spider, there would be no significant difference to the crawling spider’s code. The only difference is that you need to create Item objects containing images, image_urls and yield it from the spider."
},
{
"code": null,
"e": 17980,
"s": 16864,
"text": "# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom ..items import ImagescraperItemimport reclass ImageCrawlSpiderSpider(CrawlSpider): name = \"image_crawl_spider\" allowed_domains = [\"books.toscrape.com\"] # start_urls = [\"http://books.toscrape.com/\"]def start_requests(self): url = \"http://books.toscrape.com/\" yield scrapy.Request(url=url)rules = (Rule(LinkExtractor(allow=r\"catalogue/\"), callback=\"parse_image\", follow=True),)def parse_image(self, response): if response.xpath('//div[@class=\"item active\"]/img').get() is not None: img = response.xpath('//div[@class=\"item active\"]/img/@src').get()\"\"\" Computing the Absolute path of the image file. \"image_urls\" require absolute path, not relative path \"\"\" m = re.match(r\"^(?:../../)(.*)$\", img).group(1) url = \"http://books.toscrape.com/\" img_url = \"\".join([url, m])image = ImagescraperItem() image[\"image_urls\"] = [img_url] # \"image_urls\" must be a listyield image"
},
{
"code": null,
"e": 18015,
"s": 17980,
"text": "The items.py file would look like."
},
{
"code": null,
"e": 18123,
"s": 18015,
"text": "import scrapyclass ImagescraperItem(scrapy.Item): images = scrapy.Field() image_urls = scrapy.Field()"
},
{
"code": null,
"e": 18418,
"s": 18123,
"text": "When you run the spider with an output file, the spider would crawl all the webpages of the http://books.toscrape.com, scrape URLs of the books’ covers and yield it as image_urls, which would then be sent to the Scheduler and the workflow continues as detailed at the beginning of this example."
},
{
"code": null,
"e": 18465,
"s": 18418,
"text": "scrapy crawl image_crawl_spider -o output.json"
},
{
"code": null,
"e": 18586,
"s": 18465,
"text": "The downloaded images would be stored at the location specified by IMAGES_STORE and the output.json will look like this."
},
{
"code": null,
"e": 19404,
"s": 18586,
"text": "[ { \"image_urls\": [ \"http://books.toscrape.com/media/cache/ee/cf/eecfe998905e455df12064dba399c075.jpg\" ], \"images\": [ { \"url\": \"http://books.toscrape.com/media/cache/ee/cf/eecfe998905e455df12064dba399c075.jpg\", \"path\": \"full/59d0249d6ae2eeb367e72b04740583bc70f81558.jpg\", \"checksum\": \"693caff3d97645e73bd28da8e5974946\", \"status\": \"downloaded\" } ] }, { \"image_urls\": [ \"http://books.toscrape.com/media/cache/08/e9/08e94f3731d7d6b760dfbfbc02ca5c62.jpg\" ], \"images\": [ { \"url\": \"http://books.toscrape.com/media/cache/08/e9/08e94f3731d7d6b760dfbfbc02ca5c62.jpg\", \"path\": \"full/1c1a130c161d186db9973e70558b6ec221ce7c4e.jpg\", \"checksum\": \"e3953238c2ff7ac507a4bed4485c8622\", \"status\": \"downloaded\" } ] }, ...]"
},
{
"code": null,
"e": 19581,
"s": 19404,
"text": "If you wish to scrape other files of different format, you can use FilesPipeline instead. I will leave this to your curiosity. You can download these 3 examples from this link."
},
{
"code": null,
"e": 19886,
"s": 19581,
"text": "Beginners, who are enthusiastic about web scraping, might go overboard and scrape websites at an increased rate which might result is their IP getting banned/blacklisted from the website. Some websites implement certain measures to prevent bots from crawling them, with varying degrees of sophistication."
},
{
"code": null,
"e": 20015,
"s": 19886,
"text": "The following are some tips to keep in mind when dealing with these kinds of sites and it is taken from Scrapy Common Practices:"
},
{
"code": null,
"e": 20122,
"s": 20015,
"text": "Rotate your user agent from a pool of well-known ones from browsers (google around to get a list of them)."
},
{
"code": null,
"e": 20213,
"s": 20122,
"text": "Disable cookies (see COOKIES_ENABLED) as some sites may use cookies to spot bot behaviour."
},
{
"code": null,
"e": 20276,
"s": 20213,
"text": "Use download delays (2 or higher). See DOWNLOAD_DELAY setting."
},
{
"code": null,
"e": 20360,
"s": 20276,
"text": "If possible, use Google cache to fetch pages, instead of hitting the sites directly"
},
{
"code": null,
"e": 20550,
"s": 20360,
"text": "Use a pool of rotating IPs. For example, the free Tor project or paid services like ProxyMesh. An open-source alternative is scrapoxy, a super proxy that you can attach your own proxies to."
},
{
"code": null,
"e": 20710,
"s": 20550,
"text": "Use a highly distributed downloader that circumvents bans internally, so you can just focus on parsing clean pages. One example of such downloaders is Crawlera"
},
{
"code": null,
"e": 21192,
"s": 20710,
"text": "As my goal is to make you work confidently with Scrapy after reading this tutorial, I have restrained myself from diving into various intricate aspects of Scrapy. But, I hope that I have introduced you to the concept and practice of working with Scrapy with a clear distinction between basic and crawling spiders. If you are interested in swimming to the deeper end of this pool, feel free to take the guidance of Scrapy official documentation that can be reached by clicking here."
},
{
"code": null,
"e": 21271,
"s": 21192,
"text": "In the next part of this web scraping series, we shall be looking at Selenium."
}
] |
SQL - Syntax
|
SQL is followed by a unique set of rules and guidelines called Syntax. This tutorial gives you a quick start with SQL by listing all the basic SQL Syntax.
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;).
The most important point to be noted here is that SQL is case insensitive, which means SELECT and select have same meaning in SQL statements. Whereas, MySQL makes difference in table names. So, if you are working with MySQL, then you need to give table names as they exist in the database.
SELECT column1, column2....columnN
FROM table_name;
SELECT DISTINCT column1, column2....columnN
FROM table_name;
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
DROP TABLE table_name;
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
ALTER TABLE table_name
DROP INDEX index_name;
DESC table_name;
TRUNCATE TABLE table_name;
ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};
ALTER TABLE table_name RENAME TO new_table_name;
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
DELETE FROM table_name
WHERE {CONDITION};
CREATE DATABASE database_name;
DROP DATABASE database_name;
USE database_name;
COMMIT;
ROLLBACK;
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2608,
"s": 2453,
"text": "SQL is followed by a unique set of rules and guidelines called Syntax. This tutorial gives you a quick start with SQL by listing all the basic SQL Syntax."
},
{
"code": null,
"e": 2779,
"s": 2608,
"text": "All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;)."
},
{
"code": null,
"e": 3069,
"s": 2779,
"text": "The most important point to be noted here is that SQL is case insensitive, which means SELECT and select have same meaning in SQL statements. Whereas, MySQL makes difference in table names. So, if you are working with MySQL, then you need to give table names as they exist in the database."
},
{
"code": null,
"e": 3124,
"s": 3069,
"text": "SELECT column1, column2....columnN\nFROM table_name;\n"
},
{
"code": null,
"e": 3188,
"s": 3124,
"text": "SELECT DISTINCT column1, column2....columnN\nFROM table_name;\n"
},
{
"code": null,
"e": 3260,
"s": 3188,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION;\n"
},
{
"code": null,
"e": 3355,
"s": 3260,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION-1 {AND|OR} CONDITION-2;\n"
},
{
"code": null,
"e": 3456,
"s": 3355,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name IN (val-1, val-2,...val-N);\n"
},
{
"code": null,
"e": 3554,
"s": 3456,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name BETWEEN val-1 AND val-2;\n"
},
{
"code": null,
"e": 3645,
"s": 3554,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name LIKE { PATTERN };\n"
},
{
"code": null,
"e": 3749,
"s": 3645,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION\nORDER BY column_name {ASC|DESC};\n"
},
{
"code": null,
"e": 3831,
"s": 3749,
"text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name;\n"
},
{
"code": null,
"e": 3894,
"s": 3831,
"text": "SELECT COUNT(column_name)\nFROM table_name\nWHERE CONDITION;\n"
},
{
"code": null,
"e": 4016,
"s": 3894,
"text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name\nHAVING (arithematic function condition);\n"
},
{
"code": null,
"e": 4158,
"s": 4016,
"text": "CREATE TABLE table_name(\ncolumn1 datatype,\ncolumn2 datatype,\ncolumn3 datatype,\n.....\ncolumnN datatype,\nPRIMARY KEY( one or more columns )\n);\n"
},
{
"code": null,
"e": 4182,
"s": 4158,
"text": "DROP TABLE table_name;\n"
},
{
"code": null,
"e": 4260,
"s": 4182,
"text": "CREATE UNIQUE INDEX index_name\nON table_name ( column1, column2,...columnN);\n"
},
{
"code": null,
"e": 4307,
"s": 4260,
"text": "ALTER TABLE table_name\nDROP INDEX index_name;\n"
},
{
"code": null,
"e": 4325,
"s": 4307,
"text": "DESC table_name;\n"
},
{
"code": null,
"e": 4353,
"s": 4325,
"text": "TRUNCATE TABLE table_name;\n"
},
{
"code": null,
"e": 4419,
"s": 4353,
"text": "ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};\n"
},
{
"code": null,
"e": 4469,
"s": 4419,
"text": "ALTER TABLE table_name RENAME TO new_table_name;\n"
},
{
"code": null,
"e": 4559,
"s": 4469,
"text": "INSERT INTO table_name( column1, column2....columnN)\nVALUES ( value1, value2....valueN);\n"
},
{
"code": null,
"e": 4657,
"s": 4559,
"text": "UPDATE table_name\nSET column1 = value1, column2 = value2....columnN=valueN\n[ WHERE CONDITION ];\n"
},
{
"code": null,
"e": 4701,
"s": 4657,
"text": "DELETE FROM table_name\nWHERE {CONDITION};\n"
},
{
"code": null,
"e": 4733,
"s": 4701,
"text": "CREATE DATABASE database_name;\n"
},
{
"code": null,
"e": 4763,
"s": 4733,
"text": "DROP DATABASE database_name;\n"
},
{
"code": null,
"e": 4783,
"s": 4763,
"text": "USE database_name;\n"
},
{
"code": null,
"e": 4792,
"s": 4783,
"text": "COMMIT;\n"
},
{
"code": null,
"e": 4803,
"s": 4792,
"text": "ROLLBACK;\n"
},
{
"code": null,
"e": 4836,
"s": 4803,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4850,
"s": 4836,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4883,
"s": 4850,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4897,
"s": 4883,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4932,
"s": 4897,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4946,
"s": 4932,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4979,
"s": 4946,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5001,
"s": 4979,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5036,
"s": 5001,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5090,
"s": 5036,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 5123,
"s": 5090,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5151,
"s": 5123,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5158,
"s": 5151,
"text": " Print"
},
{
"code": null,
"e": 5169,
"s": 5158,
"text": " Add Notes"
}
] |
3 Python Projects That Will Help Automate Your Life | by Frank Andrade | Towards Data Science
|
Most jobs have some tasks that add little value to our profession. Doing such tasks once isn’t a big deal, but when they become repetitive and time-consuming, they have to be automated.
By automating tasks you will stop wasting time doing mundane tasks and focus on what matters most for you. On top of that, you will put into practice all your knowledge in Python and even learn new things.
In this guide, I will show you 3 Python projects that helped me automate some of my everyday tasks at work and hopefully will help you too.
Think of all the things you have to do to make an Excel reporting — you use Excel formulas, create a pivot table, make a chart, and format the worksheet.
Doing it once is easy, but things get complicated when you have to do it lots of times. Fortunately, Python can help you automate these tasks, so you’ll only need a couple of clicks the next time you have to make an Excel reporting.
In Python, we can use openpyxl and Pandas to automate your Excel reporting. Here’s a guide I made to automate your Excel reporting with Python. Both are great Python libraries, but the downside is that it might take some time for beginners to learn openpyxl and it doesn’t have applications beyond Excel.
There’s an easier approach to automate your Excel reporting though. You only need to install a Python library named mitosheet (aka Mito). This library allows us to group data and calculate summary stats using an intuitive Excel-like interface. The best part is that Mito generates the code for each edit, so we’ll be able to see the Python code that corresponds to each edit.
In the example below, you can see how I used mitosheet’s interface to create a pivot table. After making the pivot table, the code is automatically created, isn’t that great?
To automate pivot tables and more Excel tasks you need to install the mitosheet library. To install it, first, open a new terminal or command prompt and then download the Mito installer with the following command:
python -m pip install mitoinstaller
Then, run the installer (this command may take a few moments to run)
python -m mitoinstaller install
That’s it! Check this link to learn how to create your first pivot table with mitosheet.
Most data analysis projects end with a presentation that contains lots of graphs. In my previous jobs, I’d update my Excel reporting and then manually make visualizations such as bar plots, piecharts, boxplots, and more.
This was time-consuming tough, so I looked for an alternative in Python. I found a couple of libraries that could help me automate plotting visualizations. I only had to read my updated Excel reporting with Python and by running a script all the visualizations would be created.
To automate data visualization, first, we need to write code that creates the graph we want (preferably in a Jupiter Notebook file). Then write down how the input data (Excel file) should look like, so you make sure the column names, the shape of the data, data type, and other important features remain the same in the next update.
Now you might be wondering “how can I make visualizations with Python?” Well, Python offers different options to make standard as well as interactive visualizations. Here’s a guide to making visualizations with Matplotlib/Seaborn and here’s another guide to making interactive visualizations with Pandas/Plotly.
That said, learning such libraries might take you a good number of hours. Here Mito can help too. You can use Mito to make data visualization with a couple of clicks while generating the corresponding Python code. This code can be used to automate the creation of data visualization for future data.
Let’s have a look at how it works.
In the gif above, I’m using the mitosheet library to create a barplot of a Netflix dataset with a couple of clicks. I only need to select a column, click on the graph button, and voilà! The graph is created and the code is automatically generated.
One of the boring tasks I had to do as a junior data analyst was to upload files to a client’s website on a daily basis. The steps were quite simple: Go to website “X,” click on this button, select an option from a dropdown and click on upload.
Doing this could take 2 minutes or so, but I had to repeat these steps hundreds of times during the week. This is why I decided to automate this task with Selenium. This is a tool for controlling web browsers like Chrome through Python.
To automate any website with Python, first think of all the steps you would normally follow to do a task on a website. Your task might involve clicking on buttons, selecting elements within dropdowns, introducing text, scrolling up/down, logging in to pages, etc.
Once all the tasks are enumerated, replicate all the steps in Python using Selenium. Below is my Python Selenium tutorial for beginners on YouTube and here’s a Selenium guide in Python. Both will help you create a bot in Selenium that will perform almost any task on a website as if you were controlling it yourself.
Bonus: If you reach this point, it means that you’re into automation, here are 4 more automation projects you can with Python, and here are other 4 projects you can do even without writing a single line of code.
medium.datadriveninvestor.com
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to thousands of Python guides and Data science articles. If you sign up using my link, I’ll earn a small commission with no extra cost to you.
|
[
{
"code": null,
"e": 357,
"s": 171,
"text": "Most jobs have some tasks that add little value to our profession. Doing such tasks once isn’t a big deal, but when they become repetitive and time-consuming, they have to be automated."
},
{
"code": null,
"e": 563,
"s": 357,
"text": "By automating tasks you will stop wasting time doing mundane tasks and focus on what matters most for you. On top of that, you will put into practice all your knowledge in Python and even learn new things."
},
{
"code": null,
"e": 703,
"s": 563,
"text": "In this guide, I will show you 3 Python projects that helped me automate some of my everyday tasks at work and hopefully will help you too."
},
{
"code": null,
"e": 857,
"s": 703,
"text": "Think of all the things you have to do to make an Excel reporting — you use Excel formulas, create a pivot table, make a chart, and format the worksheet."
},
{
"code": null,
"e": 1090,
"s": 857,
"text": "Doing it once is easy, but things get complicated when you have to do it lots of times. Fortunately, Python can help you automate these tasks, so you’ll only need a couple of clicks the next time you have to make an Excel reporting."
},
{
"code": null,
"e": 1395,
"s": 1090,
"text": "In Python, we can use openpyxl and Pandas to automate your Excel reporting. Here’s a guide I made to automate your Excel reporting with Python. Both are great Python libraries, but the downside is that it might take some time for beginners to learn openpyxl and it doesn’t have applications beyond Excel."
},
{
"code": null,
"e": 1771,
"s": 1395,
"text": "There’s an easier approach to automate your Excel reporting though. You only need to install a Python library named mitosheet (aka Mito). This library allows us to group data and calculate summary stats using an intuitive Excel-like interface. The best part is that Mito generates the code for each edit, so we’ll be able to see the Python code that corresponds to each edit."
},
{
"code": null,
"e": 1946,
"s": 1771,
"text": "In the example below, you can see how I used mitosheet’s interface to create a pivot table. After making the pivot table, the code is automatically created, isn’t that great?"
},
{
"code": null,
"e": 2160,
"s": 1946,
"text": "To automate pivot tables and more Excel tasks you need to install the mitosheet library. To install it, first, open a new terminal or command prompt and then download the Mito installer with the following command:"
},
{
"code": null,
"e": 2196,
"s": 2160,
"text": "python -m pip install mitoinstaller"
},
{
"code": null,
"e": 2265,
"s": 2196,
"text": "Then, run the installer (this command may take a few moments to run)"
},
{
"code": null,
"e": 2297,
"s": 2265,
"text": "python -m mitoinstaller install"
},
{
"code": null,
"e": 2386,
"s": 2297,
"text": "That’s it! Check this link to learn how to create your first pivot table with mitosheet."
},
{
"code": null,
"e": 2607,
"s": 2386,
"text": "Most data analysis projects end with a presentation that contains lots of graphs. In my previous jobs, I’d update my Excel reporting and then manually make visualizations such as bar plots, piecharts, boxplots, and more."
},
{
"code": null,
"e": 2886,
"s": 2607,
"text": "This was time-consuming tough, so I looked for an alternative in Python. I found a couple of libraries that could help me automate plotting visualizations. I only had to read my updated Excel reporting with Python and by running a script all the visualizations would be created."
},
{
"code": null,
"e": 3219,
"s": 2886,
"text": "To automate data visualization, first, we need to write code that creates the graph we want (preferably in a Jupiter Notebook file). Then write down how the input data (Excel file) should look like, so you make sure the column names, the shape of the data, data type, and other important features remain the same in the next update."
},
{
"code": null,
"e": 3531,
"s": 3219,
"text": "Now you might be wondering “how can I make visualizations with Python?” Well, Python offers different options to make standard as well as interactive visualizations. Here’s a guide to making visualizations with Matplotlib/Seaborn and here’s another guide to making interactive visualizations with Pandas/Plotly."
},
{
"code": null,
"e": 3831,
"s": 3531,
"text": "That said, learning such libraries might take you a good number of hours. Here Mito can help too. You can use Mito to make data visualization with a couple of clicks while generating the corresponding Python code. This code can be used to automate the creation of data visualization for future data."
},
{
"code": null,
"e": 3866,
"s": 3831,
"text": "Let’s have a look at how it works."
},
{
"code": null,
"e": 4115,
"s": 3866,
"text": "In the gif above, I’m using the mitosheet library to create a barplot of a Netflix dataset with a couple of clicks. I only need to select a column, click on the graph button, and voilà! The graph is created and the code is automatically generated."
},
{
"code": null,
"e": 4360,
"s": 4115,
"text": "One of the boring tasks I had to do as a junior data analyst was to upload files to a client’s website on a daily basis. The steps were quite simple: Go to website “X,” click on this button, select an option from a dropdown and click on upload."
},
{
"code": null,
"e": 4597,
"s": 4360,
"text": "Doing this could take 2 minutes or so, but I had to repeat these steps hundreds of times during the week. This is why I decided to automate this task with Selenium. This is a tool for controlling web browsers like Chrome through Python."
},
{
"code": null,
"e": 4861,
"s": 4597,
"text": "To automate any website with Python, first think of all the steps you would normally follow to do a task on a website. Your task might involve clicking on buttons, selecting elements within dropdowns, introducing text, scrolling up/down, logging in to pages, etc."
},
{
"code": null,
"e": 5178,
"s": 4861,
"text": "Once all the tasks are enumerated, replicate all the steps in Python using Selenium. Below is my Python Selenium tutorial for beginners on YouTube and here’s a Selenium guide in Python. Both will help you create a bot in Selenium that will perform almost any task on a website as if you were controlling it yourself."
},
{
"code": null,
"e": 5390,
"s": 5178,
"text": "Bonus: If you reach this point, it means that you’re into automation, here are 4 more automation projects you can with Python, and here are other 4 projects you can do even without writing a single line of code."
},
{
"code": null,
"e": 5420,
"s": 5390,
"text": "medium.datadriveninvestor.com"
},
{
"code": null,
"e": 5538,
"s": 5420,
"text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)"
}
] |
Machine Learning Basics: Random Forest Regression | by Gurucharan M K | Towards Data Science
|
Previously, I had explained the various Regression models such as Linear, Polynomial, Support Vector and Decision Tree Regression. In this article, we will go through the code for the application of Random Forest Regression which is an extension to the Decision Tree Regression implemented previously.
The Decision Tree is an easily understood and interpreted algorithm and hence a single tree may not be enough for the model to learn the features from it. On the other hand, Random Forest is also a “Tree”-based algorithm that uses the qualities features of multiple Decision Trees for making decisions.
Therefore, it can be referred to as a ‘Forest’ of trees and hence the name “Random Forest”. The term ‘Random’ is due to the fact that this algorithm is a forest of ‘Randomly created Decision Trees’.
The Decision Tree algorithm has a major disadvantage in that it causes over-fitting. This problem can be limited by implementing the Random Forest Regression in place of the Decision Tree Regression. Additionally, the Random Forest algorithm is also very fast and robust than other regression models.
To summarize in short, The Random Forest Algorithm merges the output of multiple Decision Trees to generate the final output.
The same data set that was used for the Decision Tree Regression is utilized in this where we have one independent variable Temperature and one independent variable Revenue which we have to predict. In this problem, we have to build a Random Forest Regression Model which will study the correlation between the Temperature and Revenue of the Ice Cream Shop and predict the revenue for the ice cream shop based on the temperature on a particular day.
As usual, the NumPy, matplotlib and the Pandas libraries are imported.
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd
The data set is imported using the function ‘pd.read_csv’ from my github repository. In this, we assign the independent variable (X) to the ‘Temperature’ column and the dependent variable (y) to the ‘Revenue’ column.
dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/IceCreamData.csv')X = dataset['Temperature'].valuesy = dataset['Revenue'].valuesdataset.head(5)>>Temperature Revenue24.566884 534.79902826.005191 625.19012227.790554 660.63228920.595335 487.70696011.503498 316.240194
Similar to the Decision Tree Regression Model, we will split the data set, we use test_size=0.05 which means that 5% of 500 data rows (25 rows) will only be used as test set and the remaining 475 rows will be used as training set for building the Random Forest Regression Model.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.05)
In this step, to train the model, we import the RandomForestRegressor class and assign it to the variable regressor. We then use the .fit() function to fit the X_train and y_train values to the regressor by reshaping it accordingly.
# Fitting Random Forest Regression to the datasetfrom sklearn.ensemble import RandomForestRegressorregressor = RandomForestRegressor(n_estimators = 10, random_state = 0)regressor.fit(X_train.reshape(-1,1), y_train.reshape(-1,1))
In this step, we predict the results of the test set with the model trained on the training set values using the regressor.predict function and assign it to ‘y_pred’.
y_pred = regressor.predict(X_test.reshape(-1,1))
In this step, we shall compare and display the values of y_test as ‘Real Values’ and y_pred as ‘Predicted Values’ in a Pandas dataframe.
df = pd.DataFrame({'Real Values':y_test.reshape(-1), 'Predicted Values':y_pred.reshape(-1)})df>>Real Values Predicted Values534.622865 510.602018542.608070 558.764770618.457277 653.356430460.402500 449.302331759.377432 728.037404631.318237 649.712332572.672047 583.685756494.627437 503.075097250.131728 239.372956594.651009 635.653662383.956240 384.531416491.230603 503.075097875.019348 933.984685273.073342 224.659296500.925064 498.355934191.623312 193.223331691.516541 726.817925421.621505 420.997198636.298374 653.945550321.848273 276.772845283.679657 275.805778608.936345 589.542982212.591740 239.372956594.804871 541.164031500.065779 524.649546
From the above values, we infer that the model is able to predict the values of the y_test with a good accuracy though it can be improved by tuning the hyper-parameters such as n_estimators and max_depth. I leave it to you all to play with those parameters and improve the accuracy of the Random Forest Regression Model.
In this graph, the Real values are plotted with “Red” color and the Predicted values are plotted with “Green” color. The plot of the Decision Tree Regression model is also drawn in “Black” color.
I am attaching a link of my github repository where you can find the Google Colab notebook and the data files for your reference.
github.com
I do hope that I have been able to explain the ML code for building a Decision Tree Regression model with an example.
You can also find the explanation of the program for other Regression models below:
Simple Linear Regression
Multiple Linear Regression
Polynomial Regression
Support Vector Regression
Decision Tree Regression
Random Forest Regression
We will come across the more complex models of Regression, Classification and Clustering in the upcoming articles. Till then, Happy Machine Learning!
|
[
{
"code": null,
"e": 474,
"s": 172,
"text": "Previously, I had explained the various Regression models such as Linear, Polynomial, Support Vector and Decision Tree Regression. In this article, we will go through the code for the application of Random Forest Regression which is an extension to the Decision Tree Regression implemented previously."
},
{
"code": null,
"e": 777,
"s": 474,
"text": "The Decision Tree is an easily understood and interpreted algorithm and hence a single tree may not be enough for the model to learn the features from it. On the other hand, Random Forest is also a “Tree”-based algorithm that uses the qualities features of multiple Decision Trees for making decisions."
},
{
"code": null,
"e": 976,
"s": 777,
"text": "Therefore, it can be referred to as a ‘Forest’ of trees and hence the name “Random Forest”. The term ‘Random’ is due to the fact that this algorithm is a forest of ‘Randomly created Decision Trees’."
},
{
"code": null,
"e": 1277,
"s": 976,
"text": "The Decision Tree algorithm has a major disadvantage in that it causes over-fitting. This problem can be limited by implementing the Random Forest Regression in place of the Decision Tree Regression. Additionally, the Random Forest algorithm is also very fast and robust than other regression models."
},
{
"code": null,
"e": 1403,
"s": 1277,
"text": "To summarize in short, The Random Forest Algorithm merges the output of multiple Decision Trees to generate the final output."
},
{
"code": null,
"e": 1853,
"s": 1403,
"text": "The same data set that was used for the Decision Tree Regression is utilized in this where we have one independent variable Temperature and one independent variable Revenue which we have to predict. In this problem, we have to build a Random Forest Regression Model which will study the correlation between the Temperature and Revenue of the Ice Cream Shop and predict the revenue for the ice cream shop based on the temperature on a particular day."
},
{
"code": null,
"e": 1924,
"s": 1853,
"text": "As usual, the NumPy, matplotlib and the Pandas libraries are imported."
},
{
"code": null,
"e": 1993,
"s": 1924,
"text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd"
},
{
"code": null,
"e": 2210,
"s": 1993,
"text": "The data set is imported using the function ‘pd.read_csv’ from my github repository. In this, we assign the independent variable (X) to the ‘Temperature’ column and the dependent variable (y) to the ‘Revenue’ column."
},
{
"code": null,
"e": 2538,
"s": 2210,
"text": "dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/IceCreamData.csv')X = dataset['Temperature'].valuesy = dataset['Revenue'].valuesdataset.head(5)>>Temperature Revenue24.566884 534.79902826.005191 625.19012227.790554 660.63228920.595335 487.70696011.503498 316.240194"
},
{
"code": null,
"e": 2817,
"s": 2538,
"text": "Similar to the Decision Tree Regression Model, we will split the data set, we use test_size=0.05 which means that 5% of 500 data rows (25 rows) will only be used as test set and the remaining 475 rows will be used as training set for building the Random Forest Regression Model."
},
{
"code": null,
"e": 2945,
"s": 2817,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.05)"
},
{
"code": null,
"e": 3178,
"s": 2945,
"text": "In this step, to train the model, we import the RandomForestRegressor class and assign it to the variable regressor. We then use the .fit() function to fit the X_train and y_train values to the regressor by reshaping it accordingly."
},
{
"code": null,
"e": 3407,
"s": 3178,
"text": "# Fitting Random Forest Regression to the datasetfrom sklearn.ensemble import RandomForestRegressorregressor = RandomForestRegressor(n_estimators = 10, random_state = 0)regressor.fit(X_train.reshape(-1,1), y_train.reshape(-1,1))"
},
{
"code": null,
"e": 3574,
"s": 3407,
"text": "In this step, we predict the results of the test set with the model trained on the training set values using the regressor.predict function and assign it to ‘y_pred’."
},
{
"code": null,
"e": 3623,
"s": 3574,
"text": "y_pred = regressor.predict(X_test.reshape(-1,1))"
},
{
"code": null,
"e": 3760,
"s": 3623,
"text": "In this step, we shall compare and display the values of y_test as ‘Real Values’ and y_pred as ‘Predicted Values’ in a Pandas dataframe."
},
{
"code": null,
"e": 4513,
"s": 3760,
"text": "df = pd.DataFrame({'Real Values':y_test.reshape(-1), 'Predicted Values':y_pred.reshape(-1)})df>>Real Values Predicted Values534.622865 510.602018542.608070 558.764770618.457277 653.356430460.402500 449.302331759.377432 728.037404631.318237 649.712332572.672047 583.685756494.627437 503.075097250.131728 239.372956594.651009 635.653662383.956240 384.531416491.230603 503.075097875.019348 933.984685273.073342 224.659296500.925064 498.355934191.623312 193.223331691.516541 726.817925421.621505 420.997198636.298374 653.945550321.848273 276.772845283.679657 275.805778608.936345 589.542982212.591740 239.372956594.804871 541.164031500.065779 524.649546"
},
{
"code": null,
"e": 4834,
"s": 4513,
"text": "From the above values, we infer that the model is able to predict the values of the y_test with a good accuracy though it can be improved by tuning the hyper-parameters such as n_estimators and max_depth. I leave it to you all to play with those parameters and improve the accuracy of the Random Forest Regression Model."
},
{
"code": null,
"e": 5030,
"s": 4834,
"text": "In this graph, the Real values are plotted with “Red” color and the Predicted values are plotted with “Green” color. The plot of the Decision Tree Regression model is also drawn in “Black” color."
},
{
"code": null,
"e": 5160,
"s": 5030,
"text": "I am attaching a link of my github repository where you can find the Google Colab notebook and the data files for your reference."
},
{
"code": null,
"e": 5171,
"s": 5160,
"text": "github.com"
},
{
"code": null,
"e": 5289,
"s": 5171,
"text": "I do hope that I have been able to explain the ML code for building a Decision Tree Regression model with an example."
},
{
"code": null,
"e": 5373,
"s": 5289,
"text": "You can also find the explanation of the program for other Regression models below:"
},
{
"code": null,
"e": 5398,
"s": 5373,
"text": "Simple Linear Regression"
},
{
"code": null,
"e": 5425,
"s": 5398,
"text": "Multiple Linear Regression"
},
{
"code": null,
"e": 5447,
"s": 5425,
"text": "Polynomial Regression"
},
{
"code": null,
"e": 5473,
"s": 5447,
"text": "Support Vector Regression"
},
{
"code": null,
"e": 5498,
"s": 5473,
"text": "Decision Tree Regression"
},
{
"code": null,
"e": 5523,
"s": 5498,
"text": "Random Forest Regression"
}
] |
Dealing with List Values in Pandas Dataframes | by Max Hilsdorf | Towards Data Science
|
Have you ever dealt with a dataset that required you to work with list values? If so, you will understand how painful this can be. If you have not, you better prepare for it.
If you look closely, you will find that lists are everywhere! Here are some practical problems, where you will probably encounter list values.
Audio- or video tags
Open-ended questions in survey data
Lists of all authors, artists, producers, etc. involved in a creative product
I have recently worked on multiple projects that required me to analyze this kind of data. After many painful hours of figuring out how to perform even the simplest operations, I realized had to share my knowledge here to save you some time.
I will show you the kinds of problems you might encounter and offer practical solutions for them.
To follow this tutorial, feel free to download the fictional dataset used for all the examples. All materials including the code can be found in this repo.
Also, please import all the necessary libraries and load the dataframe.
import pandas as pdimport numpy as npimport matplotlib as pltfruits = pd.read_csv("fruits.csv", delimiter = ";")
Allow me to get right to the point: List values mess up everything you know about data analysis. The simplest operations can not be performed without endless looping. Let me show you a quick example:
For the “age” column in the example dataset, we can easily use the value_counts() function to count how many times which age was observed.
fruits["age"].value_counts()## OUTPUT ##8 310 26 29 17 15 1
What if we want to find out which fruits were named the most? In principle, we have all the data we need for this in the “favorite_fruits” column. However, if we apply the same function, the results are less than unhelpful.
fruits["favorite_fruits"].value_counts()## OUTPUT ##["strawberry", "raspberry", "blueberry"] 1["mango", "pineapple", "orange"] 1["blueberry", "watermelon", "apple", "raspberry"] 1["apple", "pear", "peach"] 1["pear", "strawberry", "raspberry"] 1["banana", "maracuja", "watermelon", "apple", "pineapple"] 1["peach", "strawberry", "apple", "blueberry"] 1[] 1["banana", "mango", "orange", "watermelon"] 1["watermelon", "apple", "blueberry", "pear", "strawberry"] 1
The reason this does not work is that Pandas does not have direct access to every individual element of the lists. Thus, Pandas is unable to apply functions like value_counts() properly. So, what do we do instead? I will show you in the following!
One problem you will always encounter is that Pandas will read your lists as strings, not as lists.
for i, l in enumerate(fruits["favorite_fruits"]): print("list",i,"is",type(l))## OUTPUT ##list 0 is <class 'str'>list 1 is <class 'str'>list 2 is <class 'str'>list 3 is <class 'str'>list 4 is <class 'str'>list 5 is <class 'str'>list 6 is <class 'str'>list 7 is <class 'str'>list 8 is <class 'str'>list 9 is <class 'str'>
This means that you can not even loop through the lists to count unique values or frequencies. Depending on how your lists are formatted in the dataframe, there is an easy or a more complex solution. In any case, you will simply be able to use the code I provide.
In that case, there is a quick method using the apply() and eval() functions.
fruits["favorite_fruits"] = fruits["favorite_fruits"].apply(eval)
This one is tougher, because the eval() function will not work, as the list is lacking the inner quotation marks in order for it to be recognized as a list object. The quick and dirty solution is to simply add the quotation marks to the string and apply eval() afterwards. Use this function:
def clean_alt_list(list_): list_ = list_.replace(', ', '","') list_ = list_.replace('[', '["') list_ = list_.replace(']', '"]') return list_
To apply this to your dataframe, use this pseudo code:
df[col] = df[col].apply(clean_alt_list)
Note that in both cases, Pandas will still assign the series an “O” datatype, which is typically used for strings. But do not let this confuse you. You can check the actual datatype using:
for i, l in enumerate(fruits[“favorite_fruits”]): print(“list”,i,”is”,type(l))## OUTPUT ##list 0 is <class 'list'>list 1 is <class 'list'>list 2 is <class 'list'>list 3 is <class 'list'>list 4 is <class 'list'>list 5 is <class 'list'>list 6 is <class 'list'>list 7 is <class 'list'>list 8 is <class 'list'>list 9 is <class 'list'>
After this first step, our lists are finally recognized as such by Pandas. Still, we can not use the standard functions, because they are not made for list applications.
At least we could use loops for everything now. This method works with small datasets, but can get awfully slow with large ones. For example, I had to analyze taglists of up to 999 tags for around 500k music tracks. This means, that the inner loop would have had hundreds of millions of iterations, which would have taken many hours and probably crashed my computer. I will show you a cleaner and quicker way to do this in a minute. However, if you really want to use loops, here is the code:
fruit_dict = {}for i in fruits["favorite_fruits"]: for j in j: if j not in fruit_dict: fruit_dict[j] = 1 else: fruit_dict[j] += 1
Here is the clean way that took me a while to figure out. If we conceptualize the favorite_fruits column as a 2D array, reducing its dimensions from 2 to 1 would allow us to apply the typical pandas functions again. For that, you can use this function:
def to_1D(series): return pd.Series([x for _list in series for x in _list])
If we use value_counts() now, we get the results we want.
to_1D(fruits[“favorite_fruits”]).value_counts()## OUTPUT ##apple 5blueberry 4watermelon 4strawberry 4raspberry 3pear 3banana 2pineapple 2mango 2peach 2orange 2maracuja 1
To get unique values, just extract them from the results above chaining .index() onto it.
At this point, we can produce our first meaningful visualization.
fig, ax = plt.subplots(figsize = (14,4))ax.bar(to_1D(fruits["favorite_fruits"]).value_counts().index, to_1D(fruits["favorite_fruits"]).value_counts().values)ax.set_ylabel("Frequency", size = 12)ax.set_title("Children's Favorite Fruits", size = 14)
At this point, things are getting advanced. If you are happy with the results we got before, you can stop here. However, a deeper level of analysis might be required for your research goal. Maybe you want to correlate all list elements with each other to compute similarity scores. E.g. do kids who eat bananas typically also like mangos? Or maybe you want to find out which fruit has been ranked as the top favorite fruit by the most kids. These questions can only be answered at a deeper level of analysis.
For this, I will introduce two useful methods. They differ in complexity, but also in what you can do with their results.
This is a shockingly easy and fast method I stumbled upon. And it is so useful! All you need is one line of code.
fruits_expanded_v1 = fruits["favorite_fruits"].apply(pd.Series)
As you can see, this one-liner produced a dataframe where every list is split into its single elements. The columns indicate the order, in which the fruit was placed in the list. With this method, you will always get a dataframe with a shape of (n, len(longest_list)). In this case, two of the 10 children named five favorite fruits, which results a 10x5 dataframe.
Using this, we can find out which fruit was named most often as the number one favorite fruit.
fruits_expanded_v1.iloc[:,0].value_counts(normalize = True)## OUTPUT ##banana 0.222222 pear 0.111111 watermelon 0.111111 blueberry 0.111111 strawberry 0.111111 apple 0.111111 peach 0.111111 mango 0.111111
We can see that bananas are most often kids’ absolute favorite fruit.
Alternatively, we could target single fruits and find out how many times they were named at each position of the lists. This is the function I wrote for that:
def get_rankings(item, df): # Empty dict for results item_count_dict = {} # For every tag in df for i in range(df.shape[1]): # Calculate % of cases that tagged the item val_counts = df.iloc[:,i].value_counts(normalize = True) if item in val_counts.index: item_counts = val_counts[item] else: item_counts = 0 # Add score to dict item_count_dict["tag_{}".format(i)] = item_counts return item_count_dict
If we apply it, we get:
get_rankings(item = "apple", df = fruits_expanded_v1)## OUTPUT ##{'tag_0': 0.1111111111111111, 'tag_1': 0.1111111111111111, 'tag_2': 0.2222222222222222, 'tag_3': 0.2, 'tag_4': 0}
As you can see, we can perform rank-based analyses very well with this approach. However, this method is near useless for other approaches. Because the columns do not represent a single tag, but a rank, most tag-based operations can not be done properly. For example, calculating the correlation between bananas and peaches is not possible with the dataframe we got from method 1. If that is your research goal, use the next method.
This method is more complex and requires more resources. The idea is that we create a dataframe where rows stay the same as before, but where every fruit is assigned its own column. If only kid #2 named bananas, the banana column would have a “True” value at row 2 and “False” values everywhere else (see Figure 6). I wrote a function that will perform this operation. It relies on looping, which means that it will take lots of time with large datasets. However, out of all the methods I tried, this was the most efficient way to do it.
def boolean_df(item_lists, unique_items):# Create empty dict bool_dict = {} # Loop through all the tags for i, item in enumerate(unique_items): # Apply boolean mask bool_dict[item] = item_lists.apply(lambda x: item in x) # Return the results as a dataframe return pd.DataFrame(bool_dict)
If we now apply the function
fruits_bool = boolean_df(fruits[“favorite_fruits”], unique_items.keys())
we get this dataframe:
From here, we can easily calculate correlations. Note that “correlation” is not really the correct term, because we are not using metric or ordinal, but binary data. If you want to be correct, use “association”. I will not.
Again, there are multiple ways to correlate the fruits. One straight forward way is the Pearson correlation coefficient, which can also be used for binary data. Pandas has a built-int function for this.
fruits_corr = fruits_bool.corr(method = "pearson")
Another way is to simply count how many times a fruit was named alongside all other fruits. This can be solved using matrix multiplication. For this, we will need to convert the boolean dataframe to an integer based on first.
fruits_int = fruits_bool.astype(int)
Then, we can calculate the frequencies.
fruits_freq_mat = np.dot(fruits_int.T, fruits_int)## OUTPUT ##array([[5, 3, 3, 2, 2, 1, 1, 1, 0, 2, 0, 1], [3, 4, 2, 1, 1, 1, 1, 2, 1, 0, 1, 1], [3, 2, 4, 3, 1, 2, 0, 0, 0, 1, 0, 0], [2, 1, 3, 4, 2, 2, 0, 0, 0, 1, 0, 0], [2, 1, 1, 2, 3, 1, 0, 0, 0, 1, 0, 0], [1, 1, 2, 2, 1, 3, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 2, 1, 1, 0, 1, 1], [1, 2, 0, 0, 0, 0, 1, 2, 1, 0, 1, 1], [0, 1, 0, 0, 0, 0, 1, 1, 2, 0, 2, 0], [2, 0, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0], [0, 1, 0, 0, 0, 0, 1, 1, 2, 0, 2, 0], [1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1]])
All we need to do now is add labels and transform it back to a dataframe.
fruits_freq = pd.DataFrame(fruits_freq_mat, columns = unique_items.keys(), index = unique_items.keys())
If you are looking for a nice visualization, you can create a heatmap with the seaborn library.
import seaborn as snfig, ax = plt.subplots(figsize = (9,5))sn.heatmap(fruits_freq, cmap = "Blues")plt.xticks(rotation=50)plt.savefig("heatmap.png", dpi = 300)
With the Pearson matrix, we can easily build a fruit recommender system. For example, if you input that you like bananas, it will recommend you a maracuja, because those two have the highest correlation (0.67). You will be surprised by how powerful this simple approach is. I have used it successfully multiple times. If you want to do something like this with the frequency dataframe, you need to normalize the data first. However, that is a topic for another post.
I hope this guide was useful to you and saved you some time or inspired you. Thank you all for reading!
|
[
{
"code": null,
"e": 346,
"s": 171,
"text": "Have you ever dealt with a dataset that required you to work with list values? If so, you will understand how painful this can be. If you have not, you better prepare for it."
},
{
"code": null,
"e": 489,
"s": 346,
"text": "If you look closely, you will find that lists are everywhere! Here are some practical problems, where you will probably encounter list values."
},
{
"code": null,
"e": 510,
"s": 489,
"text": "Audio- or video tags"
},
{
"code": null,
"e": 546,
"s": 510,
"text": "Open-ended questions in survey data"
},
{
"code": null,
"e": 624,
"s": 546,
"text": "Lists of all authors, artists, producers, etc. involved in a creative product"
},
{
"code": null,
"e": 866,
"s": 624,
"text": "I have recently worked on multiple projects that required me to analyze this kind of data. After many painful hours of figuring out how to perform even the simplest operations, I realized had to share my knowledge here to save you some time."
},
{
"code": null,
"e": 964,
"s": 866,
"text": "I will show you the kinds of problems you might encounter and offer practical solutions for them."
},
{
"code": null,
"e": 1120,
"s": 964,
"text": "To follow this tutorial, feel free to download the fictional dataset used for all the examples. All materials including the code can be found in this repo."
},
{
"code": null,
"e": 1192,
"s": 1120,
"text": "Also, please import all the necessary libraries and load the dataframe."
},
{
"code": null,
"e": 1305,
"s": 1192,
"text": "import pandas as pdimport numpy as npimport matplotlib as pltfruits = pd.read_csv(\"fruits.csv\", delimiter = \";\")"
},
{
"code": null,
"e": 1505,
"s": 1305,
"text": "Allow me to get right to the point: List values mess up everything you know about data analysis. The simplest operations can not be performed without endless looping. Let me show you a quick example:"
},
{
"code": null,
"e": 1644,
"s": 1505,
"text": "For the “age” column in the example dataset, we can easily use the value_counts() function to count how many times which age was observed."
},
{
"code": null,
"e": 1727,
"s": 1644,
"text": "fruits[\"age\"].value_counts()## OUTPUT ##8 310 26 29 17 15 1"
},
{
"code": null,
"e": 1951,
"s": 1727,
"text": "What if we want to find out which fruits were named the most? In principle, we have all the data we need for this in the “favorite_fruits” column. However, if we apply the same function, the results are less than unhelpful."
},
{
"code": null,
"e": 2634,
"s": 1951,
"text": "fruits[\"favorite_fruits\"].value_counts()## OUTPUT ##[\"strawberry\", \"raspberry\", \"blueberry\"] 1[\"mango\", \"pineapple\", \"orange\"] 1[\"blueberry\", \"watermelon\", \"apple\", \"raspberry\"] 1[\"apple\", \"pear\", \"peach\"] 1[\"pear\", \"strawberry\", \"raspberry\"] 1[\"banana\", \"maracuja\", \"watermelon\", \"apple\", \"pineapple\"] 1[\"peach\", \"strawberry\", \"apple\", \"blueberry\"] 1[] 1[\"banana\", \"mango\", \"orange\", \"watermelon\"] 1[\"watermelon\", \"apple\", \"blueberry\", \"pear\", \"strawberry\"] 1"
},
{
"code": null,
"e": 2882,
"s": 2634,
"text": "The reason this does not work is that Pandas does not have direct access to every individual element of the lists. Thus, Pandas is unable to apply functions like value_counts() properly. So, what do we do instead? I will show you in the following!"
},
{
"code": null,
"e": 2982,
"s": 2882,
"text": "One problem you will always encounter is that Pandas will read your lists as strings, not as lists."
},
{
"code": null,
"e": 3306,
"s": 2982,
"text": "for i, l in enumerate(fruits[\"favorite_fruits\"]): print(\"list\",i,\"is\",type(l))## OUTPUT ##list 0 is <class 'str'>list 1 is <class 'str'>list 2 is <class 'str'>list 3 is <class 'str'>list 4 is <class 'str'>list 5 is <class 'str'>list 6 is <class 'str'>list 7 is <class 'str'>list 8 is <class 'str'>list 9 is <class 'str'>"
},
{
"code": null,
"e": 3570,
"s": 3306,
"text": "This means that you can not even loop through the lists to count unique values or frequencies. Depending on how your lists are formatted in the dataframe, there is an easy or a more complex solution. In any case, you will simply be able to use the code I provide."
},
{
"code": null,
"e": 3648,
"s": 3570,
"text": "In that case, there is a quick method using the apply() and eval() functions."
},
{
"code": null,
"e": 3714,
"s": 3648,
"text": "fruits[\"favorite_fruits\"] = fruits[\"favorite_fruits\"].apply(eval)"
},
{
"code": null,
"e": 4006,
"s": 3714,
"text": "This one is tougher, because the eval() function will not work, as the list is lacking the inner quotation marks in order for it to be recognized as a list object. The quick and dirty solution is to simply add the quotation marks to the string and apply eval() afterwards. Use this function:"
},
{
"code": null,
"e": 4159,
"s": 4006,
"text": "def clean_alt_list(list_): list_ = list_.replace(', ', '\",\"') list_ = list_.replace('[', '[\"') list_ = list_.replace(']', '\"]') return list_"
},
{
"code": null,
"e": 4214,
"s": 4159,
"text": "To apply this to your dataframe, use this pseudo code:"
},
{
"code": null,
"e": 4254,
"s": 4214,
"text": "df[col] = df[col].apply(clean_alt_list)"
},
{
"code": null,
"e": 4443,
"s": 4254,
"text": "Note that in both cases, Pandas will still assign the series an “O” datatype, which is typically used for strings. But do not let this confuse you. You can check the actual datatype using:"
},
{
"code": null,
"e": 4774,
"s": 4443,
"text": "for i, l in enumerate(fruits[“favorite_fruits”]): print(“list”,i,”is”,type(l))## OUTPUT ##list 0 is <class 'list'>list 1 is <class 'list'>list 2 is <class 'list'>list 3 is <class 'list'>list 4 is <class 'list'>list 5 is <class 'list'>list 6 is <class 'list'>list 7 is <class 'list'>list 8 is <class 'list'>list 9 is <class 'list'>"
},
{
"code": null,
"e": 4944,
"s": 4774,
"text": "After this first step, our lists are finally recognized as such by Pandas. Still, we can not use the standard functions, because they are not made for list applications."
},
{
"code": null,
"e": 5437,
"s": 4944,
"text": "At least we could use loops for everything now. This method works with small datasets, but can get awfully slow with large ones. For example, I had to analyze taglists of up to 999 tags for around 500k music tracks. This means, that the inner loop would have had hundreds of millions of iterations, which would have taken many hours and probably crashed my computer. I will show you a cleaner and quicker way to do this in a minute. However, if you really want to use loops, here is the code:"
},
{
"code": null,
"e": 5606,
"s": 5437,
"text": "fruit_dict = {}for i in fruits[\"favorite_fruits\"]: for j in j: if j not in fruit_dict: fruit_dict[j] = 1 else: fruit_dict[j] += 1"
},
{
"code": null,
"e": 5859,
"s": 5606,
"text": "Here is the clean way that took me a while to figure out. If we conceptualize the favorite_fruits column as a 2D array, reducing its dimensions from 2 to 1 would allow us to apply the typical pandas functions again. For that, you can use this function:"
},
{
"code": null,
"e": 5935,
"s": 5859,
"text": "def to_1D(series): return pd.Series([x for _list in series for x in _list])"
},
{
"code": null,
"e": 5993,
"s": 5935,
"text": "If we use value_counts() now, we get the results we want."
},
{
"code": null,
"e": 6233,
"s": 5993,
"text": "to_1D(fruits[“favorite_fruits”]).value_counts()## OUTPUT ##apple 5blueberry 4watermelon 4strawberry 4raspberry 3pear 3banana 2pineapple 2mango 2peach 2orange 2maracuja 1"
},
{
"code": null,
"e": 6323,
"s": 6233,
"text": "To get unique values, just extract them from the results above chaining .index() onto it."
},
{
"code": null,
"e": 6389,
"s": 6323,
"text": "At this point, we can produce our first meaningful visualization."
},
{
"code": null,
"e": 6644,
"s": 6389,
"text": "fig, ax = plt.subplots(figsize = (14,4))ax.bar(to_1D(fruits[\"favorite_fruits\"]).value_counts().index, to_1D(fruits[\"favorite_fruits\"]).value_counts().values)ax.set_ylabel(\"Frequency\", size = 12)ax.set_title(\"Children's Favorite Fruits\", size = 14)"
},
{
"code": null,
"e": 7153,
"s": 6644,
"text": "At this point, things are getting advanced. If you are happy with the results we got before, you can stop here. However, a deeper level of analysis might be required for your research goal. Maybe you want to correlate all list elements with each other to compute similarity scores. E.g. do kids who eat bananas typically also like mangos? Or maybe you want to find out which fruit has been ranked as the top favorite fruit by the most kids. These questions can only be answered at a deeper level of analysis."
},
{
"code": null,
"e": 7275,
"s": 7153,
"text": "For this, I will introduce two useful methods. They differ in complexity, but also in what you can do with their results."
},
{
"code": null,
"e": 7389,
"s": 7275,
"text": "This is a shockingly easy and fast method I stumbled upon. And it is so useful! All you need is one line of code."
},
{
"code": null,
"e": 7453,
"s": 7389,
"text": "fruits_expanded_v1 = fruits[\"favorite_fruits\"].apply(pd.Series)"
},
{
"code": null,
"e": 7819,
"s": 7453,
"text": "As you can see, this one-liner produced a dataframe where every list is split into its single elements. The columns indicate the order, in which the fruit was placed in the list. With this method, you will always get a dataframe with a shape of (n, len(longest_list)). In this case, two of the 10 children named five favorite fruits, which results a 10x5 dataframe."
},
{
"code": null,
"e": 7914,
"s": 7819,
"text": "Using this, we can find out which fruit was named most often as the number one favorite fruit."
},
{
"code": null,
"e": 8169,
"s": 7914,
"text": "fruits_expanded_v1.iloc[:,0].value_counts(normalize = True)## OUTPUT ##banana 0.222222 pear 0.111111 watermelon 0.111111 blueberry 0.111111 strawberry 0.111111 apple 0.111111 peach 0.111111 mango 0.111111"
},
{
"code": null,
"e": 8239,
"s": 8169,
"text": "We can see that bananas are most often kids’ absolute favorite fruit."
},
{
"code": null,
"e": 8398,
"s": 8239,
"text": "Alternatively, we could target single fruits and find out how many times they were named at each position of the lists. This is the function I wrote for that:"
},
{
"code": null,
"e": 8906,
"s": 8398,
"text": "def get_rankings(item, df): # Empty dict for results item_count_dict = {} # For every tag in df for i in range(df.shape[1]): # Calculate % of cases that tagged the item val_counts = df.iloc[:,i].value_counts(normalize = True) if item in val_counts.index: item_counts = val_counts[item] else: item_counts = 0 # Add score to dict item_count_dict[\"tag_{}\".format(i)] = item_counts return item_count_dict"
},
{
"code": null,
"e": 8930,
"s": 8906,
"text": "If we apply it, we get:"
},
{
"code": null,
"e": 9113,
"s": 8930,
"text": "get_rankings(item = \"apple\", df = fruits_expanded_v1)## OUTPUT ##{'tag_0': 0.1111111111111111, 'tag_1': 0.1111111111111111, 'tag_2': 0.2222222222222222, 'tag_3': 0.2, 'tag_4': 0}"
},
{
"code": null,
"e": 9546,
"s": 9113,
"text": "As you can see, we can perform rank-based analyses very well with this approach. However, this method is near useless for other approaches. Because the columns do not represent a single tag, but a rank, most tag-based operations can not be done properly. For example, calculating the correlation between bananas and peaches is not possible with the dataframe we got from method 1. If that is your research goal, use the next method."
},
{
"code": null,
"e": 10084,
"s": 9546,
"text": "This method is more complex and requires more resources. The idea is that we create a dataframe where rows stay the same as before, but where every fruit is assigned its own column. If only kid #2 named bananas, the banana column would have a “True” value at row 2 and “False” values everywhere else (see Figure 6). I wrote a function that will perform this operation. It relies on looping, which means that it will take lots of time with large datasets. However, out of all the methods I tried, this was the most efficient way to do it."
},
{
"code": null,
"e": 10425,
"s": 10084,
"text": "def boolean_df(item_lists, unique_items):# Create empty dict bool_dict = {} # Loop through all the tags for i, item in enumerate(unique_items): # Apply boolean mask bool_dict[item] = item_lists.apply(lambda x: item in x) # Return the results as a dataframe return pd.DataFrame(bool_dict)"
},
{
"code": null,
"e": 10454,
"s": 10425,
"text": "If we now apply the function"
},
{
"code": null,
"e": 10527,
"s": 10454,
"text": "fruits_bool = boolean_df(fruits[“favorite_fruits”], unique_items.keys())"
},
{
"code": null,
"e": 10550,
"s": 10527,
"text": "we get this dataframe:"
},
{
"code": null,
"e": 10774,
"s": 10550,
"text": "From here, we can easily calculate correlations. Note that “correlation” is not really the correct term, because we are not using metric or ordinal, but binary data. If you want to be correct, use “association”. I will not."
},
{
"code": null,
"e": 10977,
"s": 10774,
"text": "Again, there are multiple ways to correlate the fruits. One straight forward way is the Pearson correlation coefficient, which can also be used for binary data. Pandas has a built-int function for this."
},
{
"code": null,
"e": 11028,
"s": 10977,
"text": "fruits_corr = fruits_bool.corr(method = \"pearson\")"
},
{
"code": null,
"e": 11254,
"s": 11028,
"text": "Another way is to simply count how many times a fruit was named alongside all other fruits. This can be solved using matrix multiplication. For this, we will need to convert the boolean dataframe to an integer based on first."
},
{
"code": null,
"e": 11291,
"s": 11254,
"text": "fruits_int = fruits_bool.astype(int)"
},
{
"code": null,
"e": 11331,
"s": 11291,
"text": "Then, we can calculate the frequencies."
},
{
"code": null,
"e": 11923,
"s": 11331,
"text": "fruits_freq_mat = np.dot(fruits_int.T, fruits_int)## OUTPUT ##array([[5, 3, 3, 2, 2, 1, 1, 1, 0, 2, 0, 1], [3, 4, 2, 1, 1, 1, 1, 2, 1, 0, 1, 1], [3, 2, 4, 3, 1, 2, 0, 0, 0, 1, 0, 0], [2, 1, 3, 4, 2, 2, 0, 0, 0, 1, 0, 0], [2, 1, 1, 2, 3, 1, 0, 0, 0, 1, 0, 0], [1, 1, 2, 2, 1, 3, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 2, 1, 1, 0, 1, 1], [1, 2, 0, 0, 0, 0, 1, 2, 1, 0, 1, 1], [0, 1, 0, 0, 0, 0, 1, 1, 2, 0, 2, 0], [2, 0, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0], [0, 1, 0, 0, 0, 0, 1, 1, 2, 0, 2, 0], [1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1]])"
},
{
"code": null,
"e": 11997,
"s": 11923,
"text": "All we need to do now is add labels and transform it back to a dataframe."
},
{
"code": null,
"e": 12101,
"s": 11997,
"text": "fruits_freq = pd.DataFrame(fruits_freq_mat, columns = unique_items.keys(), index = unique_items.keys())"
},
{
"code": null,
"e": 12197,
"s": 12101,
"text": "If you are looking for a nice visualization, you can create a heatmap with the seaborn library."
},
{
"code": null,
"e": 12356,
"s": 12197,
"text": "import seaborn as snfig, ax = plt.subplots(figsize = (9,5))sn.heatmap(fruits_freq, cmap = \"Blues\")plt.xticks(rotation=50)plt.savefig(\"heatmap.png\", dpi = 300)"
},
{
"code": null,
"e": 12823,
"s": 12356,
"text": "With the Pearson matrix, we can easily build a fruit recommender system. For example, if you input that you like bananas, it will recommend you a maracuja, because those two have the highest correlation (0.67). You will be surprised by how powerful this simple approach is. I have used it successfully multiple times. If you want to do something like this with the frequency dataframe, you need to normalize the data first. However, that is a topic for another post."
}
] |
Creating a 3D plot in Matplotlib from a 3D numpy array
|
To create a 3D plot from a 3D numpy array, we can create a 3D array using numpy and extract the x, y,
and z points.
Create a new figure or activate an existing figure using figure() method.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
Create a random data of size=(3, 3, 3).
Extract x, y, and z data from the 3D array.
Plot 3D scattered points on the created axis
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
data = np.random.random(size=(3, 3, 3))
z, x, y = data.nonzero()
ax.scatter(x, y, z, c=z, alpha=1)
plt.show()
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "To create a 3D plot from a 3D numpy array, we can create a 3D array using numpy and extract the x, y,\nand z points."
},
{
"code": null,
"e": 1252,
"s": 1178,
"text": "Create a new figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1348,
"s": 1252,
"text": "Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method."
},
{
"code": null,
"e": 1388,
"s": 1348,
"text": "Create a random data of size=(3, 3, 3)."
},
{
"code": null,
"e": 1432,
"s": 1388,
"text": "Extract x, y, and z data from the 3D array."
},
{
"code": null,
"e": 1477,
"s": 1432,
"text": "Plot 3D scattered points on the created axis"
},
{
"code": null,
"e": 1519,
"s": 1477,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1834,
"s": 1519,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\ndata = np.random.random(size=(3, 3, 3))\nz, x, y = data.nonzero()\nax.scatter(x, y, z, c=z, alpha=1)\nplt.show()"
}
] |
Medical Image Pre-Processing with Python | by Esma Sert | Towards Data Science
|
In this post, I will explain how beautifully medical images can be preprocessed with simple examples to train any artificial intelligence model and how data is prepared for model to give the highest result by going through the all preprocessing stages.
The data I am going to use is bunch of 2D Brain CT images. They are in DICOM format. You can simply apply these operations to your own data to get more efficient results from your model.
Before we start coding, let’s talk about the medical data. First of all, I will explain what is CT.
Computer Tomography is a scanning that takes images of X-rays which are sent to the body from different angles and combined using a computer processor to access cross-sectional images (slices) of bones, blood vessels, and soft tissues in various parts of the body. These images provide more detailed information than regular x-ray images. In this way, anomalies in the bones, veins or tissues of the patient are detected. That’s why, a more precise diagnosis can be maden for patient and the treatment would continue accordingly.
Now let’s talk about, what the DICOM format is.
DICOM is an acronym for Digital Imaging and Communication in Medicine. Files in this format are most likely saved with a ‘dcm’ file extension. DICOM is both a communication protocol and a file format; This means that a patient can store medical information such as ultrasound and MRI images along with their information in a single file. While png or jpg files contain only the name, date, and number of pixels of the picture; dicom format includes the patient’s information, windowing intervals of the picture, which we call meta data. Briefly it includes more detailed information of patients. This format not only keeps all the data together, but also ensures that the information is transferred between devices that support the DICOM format. I took the few dcm images from Kaggle.
import pydicomfile_path = "/Users/esmasert/Desktop/basicsDcm/10095.dcm"medical_image = pydicom.read_file(file_path)print(medical_image)
After the basic summary of CT and dicom, let’s move on with the preprocessing. I used 5 steps during the preprocessing stages of images.
These steps are: Transforming to HU, Removing Noises, Tilt Correction, Crop Images and Padding.
After applying these preprocessing steps to data, we see that model accuracy got increased significantly. I am about the explain the preprocessing methods. To see the code in a clearer format, you can visit this link.
After loading our image data in DICOM format, we will transform it to Hounsfield Unit form.
The Hounsfield Unit (HU) is a relative quantitative measurement of the intensity of radio waves used by radiologists for better explanation and understanding of computed tomography (CT) images. The absorption/attenuation coefficient of radiation within a tissue is used during CT reconstruction to produce a grayscale image. The linear transformation produces a Hounsfield scale that displays as gray tones. More dense tissue, with greater X-ray beam absorption, has positive values and appears bright; less dense tissue, with less X-ray beam absorption, has negative values and appears dark.[1] The Hounsfield unit is named after the famous Sir Godfrey Hounsfield, who has part of the invention of Computer Tomography and was awarded the Nobel Prize for it.
We can obtain the HU by using Rescale Intercept and Rescale Slope headers:
def transform_to_hu(medical_image, image): intercept = medical_image.RescaleIntercept slope = medical_image.RescaleSlope hu_image = image * slope + intercept return hu_imagedef window_image(image, window_center, window_width): img_min = window_center - window_width // 2 img_max = window_center + window_width // 2 window_image = image.copy() window_image[window_image < img_min] = img_min window_image[window_image > img_max] = img_max return window_image
If you want a specific zone of the image you can adjust the windowing of image.
During preprocess, removing noises is a very important stage since, the data is improved after the implementation we can see it more clearly. So, model can be trained better. [2]
def remove_noise(file_path, display=False): medical_image = pydicom.read_file(file_path) image = medical_image.pixel_array hu_image = transform_to_hu(medical_image, image) brain_image = window_image(hu_image, 40, 80) #bone windowing segmentation = morphology.dilation(brain_image, np.ones((1, 1))) labels, label_nb = ndimage.label(segmentation) label_count = np.bincount(labels.ravel().astype(np.int)) label_count[0] = 0 mask = labels == label_count.argmax() mask = morphology.dilation(mask, np.ones((1, 1))) mask = ndimage.morphology.binary_fill_holes(mask) mask = morphology.dilation(mask, np.ones((3, 3))) masked_image = mask * brain_image return masked_image
Tilt correction is the alignment of brain image in a proposed way. When tilt experienced by brain CT images, it may result in misalignment for medical applications. It is important because when we train the model, it can see the whole data through the same alignment. Manually correcting the tilt on a large scale data is time-consuming and expensive. Thus, there is a need for an automatic way of performing tilt correction in preprocessing before the training.
img=numpy.uint8 (iskemiMaskedImg)contours, hier =cv2.findContours (img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)mask=numpy.zeros (img.shape, numpy.uint8)# find the biggest contour (c) by the areac = max(contours, key = cv2.contourArea)(x,y),(MA,ma),angle = cv2.fitEllipse(c)cv2.ellipse(img, ((x,y), (MA,ma), angle), color=(0, 255, 0), thickness=2)rmajor = max(MA,ma)/2if angle > 90: angle -= 90else: angle += 96xtop = x + math.cos(math.radians(angle))*rmajorytop = y + math.sin(math.radians(angle))*rmajorxbot = x + math.cos(math.radians(angle+180))*rmajorybot = y + math.sin(math.radians(angle+180))*rmajorcv2.line(img, (int(xtop),int(ytop)), (int(xbot),int(ybot)), (0, 255, 0), 3)pylab.imshow(img)pylab.show()M = cv2.getRotationMatrix2D((x, y), angle-90, 1) #transformation matriximg = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]), cv2.INTER_CUBIC)pylab.imshow(img)pylab.show()
Cropping image is needed to place the brain image at the center and get rid of unnecessary parts of image. Also, some brain images might be placed in different location within general image. By cropping image and adding pads, we will make sure almost all the images are in same location within general image itself.
def add_pad(image, new_height=512, new_width=512): height, width = image.shape final_image = np.zeros((new_height, new_width)) pad_left = int((new_width - width) // 2) pad_top = int((new_height - height) // 2) # Replace the pixels with the image's pixels final_image[pad_top:pad_top + height, pad_left:pad_left + width] = image return final_image
Here is the result! A clean, corrected and centered brain image. Ready to go inside training.
I included the references below. Many thanks to https://vincentblog.xyz/ ! It really helped me to understand the image processing deeper.
If you have any suggestion or question please comment below. Thank you very much!
|
[
{
"code": null,
"e": 425,
"s": 172,
"text": "In this post, I will explain how beautifully medical images can be preprocessed with simple examples to train any artificial intelligence model and how data is prepared for model to give the highest result by going through the all preprocessing stages."
},
{
"code": null,
"e": 612,
"s": 425,
"text": "The data I am going to use is bunch of 2D Brain CT images. They are in DICOM format. You can simply apply these operations to your own data to get more efficient results from your model."
},
{
"code": null,
"e": 712,
"s": 612,
"text": "Before we start coding, let’s talk about the medical data. First of all, I will explain what is CT."
},
{
"code": null,
"e": 1242,
"s": 712,
"text": "Computer Tomography is a scanning that takes images of X-rays which are sent to the body from different angles and combined using a computer processor to access cross-sectional images (slices) of bones, blood vessels, and soft tissues in various parts of the body. These images provide more detailed information than regular x-ray images. In this way, anomalies in the bones, veins or tissues of the patient are detected. That’s why, a more precise diagnosis can be maden for patient and the treatment would continue accordingly."
},
{
"code": null,
"e": 1290,
"s": 1242,
"text": "Now let’s talk about, what the DICOM format is."
},
{
"code": null,
"e": 2075,
"s": 1290,
"text": "DICOM is an acronym for Digital Imaging and Communication in Medicine. Files in this format are most likely saved with a ‘dcm’ file extension. DICOM is both a communication protocol and a file format; This means that a patient can store medical information such as ultrasound and MRI images along with their information in a single file. While png or jpg files contain only the name, date, and number of pixels of the picture; dicom format includes the patient’s information, windowing intervals of the picture, which we call meta data. Briefly it includes more detailed information of patients. This format not only keeps all the data together, but also ensures that the information is transferred between devices that support the DICOM format. I took the few dcm images from Kaggle."
},
{
"code": null,
"e": 2211,
"s": 2075,
"text": "import pydicomfile_path = \"/Users/esmasert/Desktop/basicsDcm/10095.dcm\"medical_image = pydicom.read_file(file_path)print(medical_image)"
},
{
"code": null,
"e": 2348,
"s": 2211,
"text": "After the basic summary of CT and dicom, let’s move on with the preprocessing. I used 5 steps during the preprocessing stages of images."
},
{
"code": null,
"e": 2444,
"s": 2348,
"text": "These steps are: Transforming to HU, Removing Noises, Tilt Correction, Crop Images and Padding."
},
{
"code": null,
"e": 2662,
"s": 2444,
"text": "After applying these preprocessing steps to data, we see that model accuracy got increased significantly. I am about the explain the preprocessing methods. To see the code in a clearer format, you can visit this link."
},
{
"code": null,
"e": 2754,
"s": 2662,
"text": "After loading our image data in DICOM format, we will transform it to Hounsfield Unit form."
},
{
"code": null,
"e": 3513,
"s": 2754,
"text": "The Hounsfield Unit (HU) is a relative quantitative measurement of the intensity of radio waves used by radiologists for better explanation and understanding of computed tomography (CT) images. The absorption/attenuation coefficient of radiation within a tissue is used during CT reconstruction to produce a grayscale image. The linear transformation produces a Hounsfield scale that displays as gray tones. More dense tissue, with greater X-ray beam absorption, has positive values and appears bright; less dense tissue, with less X-ray beam absorption, has negative values and appears dark.[1] The Hounsfield unit is named after the famous Sir Godfrey Hounsfield, who has part of the invention of Computer Tomography and was awarded the Nobel Prize for it."
},
{
"code": null,
"e": 3588,
"s": 3513,
"text": "We can obtain the HU by using Rescale Intercept and Rescale Slope headers:"
},
{
"code": null,
"e": 4079,
"s": 3588,
"text": "def transform_to_hu(medical_image, image): intercept = medical_image.RescaleIntercept slope = medical_image.RescaleSlope hu_image = image * slope + intercept return hu_imagedef window_image(image, window_center, window_width): img_min = window_center - window_width // 2 img_max = window_center + window_width // 2 window_image = image.copy() window_image[window_image < img_min] = img_min window_image[window_image > img_max] = img_max return window_image"
},
{
"code": null,
"e": 4159,
"s": 4079,
"text": "If you want a specific zone of the image you can adjust the windowing of image."
},
{
"code": null,
"e": 4338,
"s": 4159,
"text": "During preprocess, removing noises is a very important stage since, the data is improved after the implementation we can see it more clearly. So, model can be trained better. [2]"
},
{
"code": null,
"e": 5056,
"s": 4338,
"text": "def remove_noise(file_path, display=False): medical_image = pydicom.read_file(file_path) image = medical_image.pixel_array hu_image = transform_to_hu(medical_image, image) brain_image = window_image(hu_image, 40, 80) #bone windowing segmentation = morphology.dilation(brain_image, np.ones((1, 1))) labels, label_nb = ndimage.label(segmentation) label_count = np.bincount(labels.ravel().astype(np.int)) label_count[0] = 0 mask = labels == label_count.argmax() mask = morphology.dilation(mask, np.ones((1, 1))) mask = ndimage.morphology.binary_fill_holes(mask) mask = morphology.dilation(mask, np.ones((3, 3))) masked_image = mask * brain_image return masked_image"
},
{
"code": null,
"e": 5519,
"s": 5056,
"text": "Tilt correction is the alignment of brain image in a proposed way. When tilt experienced by brain CT images, it may result in misalignment for medical applications. It is important because when we train the model, it can see the whole data through the same alignment. Manually correcting the tilt on a large scale data is time-consuming and expensive. Thus, there is a need for an automatic way of performing tilt correction in preprocessing before the training."
},
{
"code": null,
"e": 6416,
"s": 5519,
"text": "img=numpy.uint8 (iskemiMaskedImg)contours, hier =cv2.findContours (img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)mask=numpy.zeros (img.shape, numpy.uint8)# find the biggest contour (c) by the areac = max(contours, key = cv2.contourArea)(x,y),(MA,ma),angle = cv2.fitEllipse(c)cv2.ellipse(img, ((x,y), (MA,ma), angle), color=(0, 255, 0), thickness=2)rmajor = max(MA,ma)/2if angle > 90: angle -= 90else: angle += 96xtop = x + math.cos(math.radians(angle))*rmajorytop = y + math.sin(math.radians(angle))*rmajorxbot = x + math.cos(math.radians(angle+180))*rmajorybot = y + math.sin(math.radians(angle+180))*rmajorcv2.line(img, (int(xtop),int(ytop)), (int(xbot),int(ybot)), (0, 255, 0), 3)pylab.imshow(img)pylab.show()M = cv2.getRotationMatrix2D((x, y), angle-90, 1) #transformation matriximg = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]), cv2.INTER_CUBIC)pylab.imshow(img)pylab.show()"
},
{
"code": null,
"e": 6732,
"s": 6416,
"text": "Cropping image is needed to place the brain image at the center and get rid of unnecessary parts of image. Also, some brain images might be placed in different location within general image. By cropping image and adding pads, we will make sure almost all the images are in same location within general image itself."
},
{
"code": null,
"e": 7112,
"s": 6732,
"text": "def add_pad(image, new_height=512, new_width=512): height, width = image.shape final_image = np.zeros((new_height, new_width)) pad_left = int((new_width - width) // 2) pad_top = int((new_height - height) // 2) # Replace the pixels with the image's pixels final_image[pad_top:pad_top + height, pad_left:pad_left + width] = image return final_image"
},
{
"code": null,
"e": 7206,
"s": 7112,
"text": "Here is the result! A clean, corrected and centered brain image. Ready to go inside training."
},
{
"code": null,
"e": 7344,
"s": 7206,
"text": "I included the references below. Many thanks to https://vincentblog.xyz/ ! It really helped me to understand the image processing deeper."
}
] |
JSF - h:selectBooleanCheckbox
|
The h:selectBooleanCheckbox tag renders an HTML input element of the type "checkbox".
<h:selectBooleanCheckbox value = "Remember Me" id = "chkRememberMe" />
<input id = "jsfForm1:chkRememberMe" type = "checkbox"
name = "jsfForm1:chkRememberMe" checked = "checked" />
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
value
A component’s value, typically a value binding
valueChangeListener
A method binding to a method that responds to value changes
converter
Converter class name
validator
Class name of a validator that’s created and attached to a component
required
A boolean; if true, requires a value to be entered in the associated field
accesskey
A key, typically combined with a system-defined metakey, that gives focus to an element
accept
Comma-separated list of content types for a form
accept-charset
Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset.
alt
Alternative text for nontextual elements such as images or applets
charset
Character encoding for a linked resource
coords
Coordinates for an element whose shape is a rectangle, circle, or polygon
dir
Direction for text. Valid values are ltr (left to right) and rtl (right to left).
disabled
Disabled state of an input element or button
hreflang
Base language of a resource specified with the href attribute; hreflang may only be used with href..
lang
Base language of an element’s attributes and text
maxlength
Maximum number of characters for text fields
readonly
Read-only state of an input field; text can be selected in a readonly field but not edited
rel
Relationship between the current document and a link specified with the href attribute
rev
Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types.
rows
Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute.
shape
Shape of a region. Valid values: default, rect,circle, poly. (default signifies the entire region)
style
Inline style information
tabindex
Numerical value specifying a tab index
target
The name of a frame in which a document is opened
title
A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value
type
Type of a link; for example, stylesheet
width
Width of an element
onblur
Element loses focus
onchange
Element’s value changes
onclick
Mouse button is clicked over the element
ondblclick
Mouse button is double-clicked over the element
onfocus
Element receives focus
onkeydown
Key is pressed
onkeypress
Key is pressed and subsequently released
onkeyup
Key is released
onmousedown
Mouse button is pressed over the element
onmousemove
Mouse moves over the element
onmouseout
Mouse leaves the element’s area
onmouseover
Mouse moves onto an element
onmouseup
Mouse button is released
onreset
Form is reset
onselect
Text is selected in an input field
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>
<h:head>
<script type = "text/javascript">
function showCheckedValue() {
alert(document.getElementById('jsfForm1:chkRememberMe').checked);
}
</script>
</h:head>
</head>
<body>
<h2>h:selectBooleanCheckbox example</h2>
<hr />
<h:form id = "jsfForm1">
<h3>Get value from selectBooleanCheckbox field</h3>
<h:selectBooleanCheckbox value = "Remember Me" id = "chkRememberMe" />
<h:commandButton value = "Show Checked" onclick = "showCheckedValue()" />
</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 the following result.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2038,
"s": 1952,
"text": "The h:selectBooleanCheckbox tag renders an HTML input element of the type \"checkbox\"."
},
{
"code": null,
"e": 2110,
"s": 2038,
"text": "<h:selectBooleanCheckbox value = \"Remember Me\" id = \"chkRememberMe\" /> "
},
{
"code": null,
"e": 2226,
"s": 2110,
"text": "<input id = \"jsfForm1:chkRememberMe\" type = \"checkbox\" \n name = \"jsfForm1:chkRememberMe\" checked = \"checked\" />\n"
},
{
"code": null,
"e": 2229,
"s": 2226,
"text": "id"
},
{
"code": null,
"e": 2256,
"s": 2229,
"text": "Identifier for a component"
},
{
"code": null,
"e": 2264,
"s": 2256,
"text": "binding"
},
{
"code": null,
"e": 2326,
"s": 2264,
"text": "Reference to the component that can be used in a backing bean"
},
{
"code": null,
"e": 2335,
"s": 2326,
"text": "rendered"
},
{
"code": null,
"e": 2373,
"s": 2335,
"text": "A boolean; false suppresses rendering"
},
{
"code": null,
"e": 2384,
"s": 2373,
"text": "styleClass"
},
{
"code": null,
"e": 2422,
"s": 2384,
"text": "Cascading stylesheet (CSS) class name"
},
{
"code": null,
"e": 2428,
"s": 2422,
"text": "value"
},
{
"code": null,
"e": 2475,
"s": 2428,
"text": "A component’s value, typically a value binding"
},
{
"code": null,
"e": 2495,
"s": 2475,
"text": "valueChangeListener"
},
{
"code": null,
"e": 2555,
"s": 2495,
"text": "A method binding to a method that responds to value changes"
},
{
"code": null,
"e": 2565,
"s": 2555,
"text": "converter"
},
{
"code": null,
"e": 2586,
"s": 2565,
"text": "Converter class name"
},
{
"code": null,
"e": 2596,
"s": 2586,
"text": "validator"
},
{
"code": null,
"e": 2665,
"s": 2596,
"text": "Class name of a validator that’s created and attached to a component"
},
{
"code": null,
"e": 2674,
"s": 2665,
"text": "required"
},
{
"code": null,
"e": 2749,
"s": 2674,
"text": "A boolean; if true, requires a value to be entered in the associated field"
},
{
"code": null,
"e": 2759,
"s": 2749,
"text": "accesskey"
},
{
"code": null,
"e": 2847,
"s": 2759,
"text": "A key, typically combined with a system-defined metakey, that gives focus to an element"
},
{
"code": null,
"e": 2854,
"s": 2847,
"text": "accept"
},
{
"code": null,
"e": 2903,
"s": 2854,
"text": "Comma-separated list of content types for a form"
},
{
"code": null,
"e": 2918,
"s": 2903,
"text": "accept-charset"
},
{
"code": null,
"e": 3075,
"s": 2918,
"text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset."
},
{
"code": null,
"e": 3079,
"s": 3075,
"text": "alt"
},
{
"code": null,
"e": 3146,
"s": 3079,
"text": "Alternative text for nontextual elements such as images or applets"
},
{
"code": null,
"e": 3154,
"s": 3146,
"text": "charset"
},
{
"code": null,
"e": 3195,
"s": 3154,
"text": "Character encoding for a linked resource"
},
{
"code": null,
"e": 3202,
"s": 3195,
"text": "coords"
},
{
"code": null,
"e": 3276,
"s": 3202,
"text": "Coordinates for an element whose shape is a rectangle, circle, or polygon"
},
{
"code": null,
"e": 3280,
"s": 3276,
"text": "dir"
},
{
"code": null,
"e": 3362,
"s": 3280,
"text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)."
},
{
"code": null,
"e": 3371,
"s": 3362,
"text": "disabled"
},
{
"code": null,
"e": 3416,
"s": 3371,
"text": "Disabled state of an input element or button"
},
{
"code": null,
"e": 3425,
"s": 3416,
"text": "hreflang"
},
{
"code": null,
"e": 3526,
"s": 3425,
"text": "Base language of a resource specified with the href attribute; hreflang may only be used with href.."
},
{
"code": null,
"e": 3531,
"s": 3526,
"text": "lang"
},
{
"code": null,
"e": 3581,
"s": 3531,
"text": "Base language of an element’s attributes and text"
},
{
"code": null,
"e": 3591,
"s": 3581,
"text": "maxlength"
},
{
"code": null,
"e": 3636,
"s": 3591,
"text": "Maximum number of characters for text fields"
},
{
"code": null,
"e": 3645,
"s": 3636,
"text": "readonly"
},
{
"code": null,
"e": 3736,
"s": 3645,
"text": "Read-only state of an input field; text can be selected in a readonly field but not edited"
},
{
"code": null,
"e": 3740,
"s": 3736,
"text": "rel"
},
{
"code": null,
"e": 3827,
"s": 3740,
"text": "Relationship between the current document and a link specified with the href attribute"
},
{
"code": null,
"e": 3831,
"s": 3827,
"text": "rev"
},
{
"code": null,
"e": 3973,
"s": 3831,
"text": "Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types."
},
{
"code": null,
"e": 3978,
"s": 3973,
"text": "rows"
},
{
"code": null,
"e": 4096,
"s": 3978,
"text": "Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute."
},
{
"code": null,
"e": 4102,
"s": 4096,
"text": "shape"
},
{
"code": null,
"e": 4201,
"s": 4102,
"text": "Shape of a region. Valid values: default, rect,circle, poly. (default signifies the entire region)"
},
{
"code": null,
"e": 4207,
"s": 4201,
"text": "style"
},
{
"code": null,
"e": 4232,
"s": 4207,
"text": "Inline style information"
},
{
"code": null,
"e": 4241,
"s": 4232,
"text": "tabindex"
},
{
"code": null,
"e": 4280,
"s": 4241,
"text": "Numerical value specifying a tab index"
},
{
"code": null,
"e": 4287,
"s": 4280,
"text": "target"
},
{
"code": null,
"e": 4337,
"s": 4287,
"text": "The name of a frame in which a document is opened"
},
{
"code": null,
"e": 4343,
"s": 4337,
"text": "title"
},
{
"code": null,
"e": 4467,
"s": 4343,
"text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value"
},
{
"code": null,
"e": 4472,
"s": 4467,
"text": "type"
},
{
"code": null,
"e": 4512,
"s": 4472,
"text": "Type of a link; for example, stylesheet"
},
{
"code": null,
"e": 4518,
"s": 4512,
"text": "width"
},
{
"code": null,
"e": 4538,
"s": 4518,
"text": "Width of an element"
},
{
"code": null,
"e": 4545,
"s": 4538,
"text": "onblur"
},
{
"code": null,
"e": 4565,
"s": 4545,
"text": "Element loses focus"
},
{
"code": null,
"e": 4574,
"s": 4565,
"text": "onchange"
},
{
"code": null,
"e": 4598,
"s": 4574,
"text": "Element’s value changes"
},
{
"code": null,
"e": 4606,
"s": 4598,
"text": "onclick"
},
{
"code": null,
"e": 4647,
"s": 4606,
"text": "Mouse button is clicked over the element"
},
{
"code": null,
"e": 4658,
"s": 4647,
"text": "ondblclick"
},
{
"code": null,
"e": 4706,
"s": 4658,
"text": "Mouse button is double-clicked over the element"
},
{
"code": null,
"e": 4714,
"s": 4706,
"text": "onfocus"
},
{
"code": null,
"e": 4737,
"s": 4714,
"text": "Element receives focus"
},
{
"code": null,
"e": 4747,
"s": 4737,
"text": "onkeydown"
},
{
"code": null,
"e": 4762,
"s": 4747,
"text": "Key is pressed"
},
{
"code": null,
"e": 4773,
"s": 4762,
"text": "onkeypress"
},
{
"code": null,
"e": 4814,
"s": 4773,
"text": "Key is pressed and subsequently released"
},
{
"code": null,
"e": 4822,
"s": 4814,
"text": "onkeyup"
},
{
"code": null,
"e": 4838,
"s": 4822,
"text": "Key is released"
},
{
"code": null,
"e": 4850,
"s": 4838,
"text": "onmousedown"
},
{
"code": null,
"e": 4891,
"s": 4850,
"text": "Mouse button is pressed over the element"
},
{
"code": null,
"e": 4903,
"s": 4891,
"text": "onmousemove"
},
{
"code": null,
"e": 4932,
"s": 4903,
"text": "Mouse moves over the element"
},
{
"code": null,
"e": 4943,
"s": 4932,
"text": "onmouseout"
},
{
"code": null,
"e": 4975,
"s": 4943,
"text": "Mouse leaves the element’s area"
},
{
"code": null,
"e": 4987,
"s": 4975,
"text": "onmouseover"
},
{
"code": null,
"e": 5015,
"s": 4987,
"text": "Mouse moves onto an element"
},
{
"code": null,
"e": 5025,
"s": 5015,
"text": "onmouseup"
},
{
"code": null,
"e": 5050,
"s": 5025,
"text": "Mouse button is released"
},
{
"code": null,
"e": 5058,
"s": 5050,
"text": "onreset"
},
{
"code": null,
"e": 5072,
"s": 5058,
"text": "Form is reset"
},
{
"code": null,
"e": 5081,
"s": 5072,
"text": "onselect"
},
{
"code": null,
"e": 5116,
"s": 5081,
"text": "Text is selected in an input field"
},
{
"code": null,
"e": 5176,
"s": 5116,
"text": "Let us create a test JSF application to test the above tag."
},
{
"code": null,
"e": 6024,
"s": 5176,
"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\n <head>\n <title>JSF Tutorial!</title>\n <h:head>\n \n <script type = \"text/javascript\">\n function showCheckedValue() { \n alert(document.getElementById('jsfForm1:chkRememberMe').checked);\t \n }\n </script>\n </h:head>\n </head>\n \n <body>\n <h2>h:selectBooleanCheckbox example</h2>\n <hr />\n \n <h:form id = \"jsfForm1\">\n <h3>Get value from selectBooleanCheckbox field</h3>\n <h:selectBooleanCheckbox value = \"Remember Me\" id = \"chkRememberMe\" />\n <h:commandButton value = \"Show Checked\" onclick = \"showCheckedValue()\" />\n </h:form> \n \n </body>\n</html>"
},
{
"code": null,
"e": 6240,
"s": 6024,
"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 the following result."
},
{
"code": null,
"e": 6275,
"s": 6240,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6290,
"s": 6275,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 6297,
"s": 6290,
"text": " Print"
},
{
"code": null,
"e": 6308,
"s": 6297,
"text": " Add Notes"
}
] |
Building a Content Based Recommender System for Hotels in Seattle | by Susan Li | Towards Data Science
|
The cold start problem is a well known and well researched problem for recommender systems, where system is not able to recommend items to users. due to three different situation i.e. for new users, for new products and for new websites.
Content-based filtering is the method that solve this problem. Our system first uses the metadata of new products when creating recommendations, while visitor action is secondary for a certain period of time. And our systems recommend a product to a user based upon the category and description of the product.
Content-based recommendation systems may be used in a variety of domains ranging from recommending web pages, news articles, restaurants, television programs, and hotels. The advantage of content-based filtering is that it doesn’t have a cold-start problem. If you just start out a new website, or any new products can be recommended right away.
Let’s assume we are starting a new online travel agency (OTA), and we have signed up thousands of hotels that are willing to sell on our platform, and we start seeing traffic coming from our website users, but we don’t have any users history, therefore, we are going to build a content-based recommendation systems to analyze hotel descriptions to identify hotels that are of particular interest to the user.
We would like to recommend hotels based on the hotels that a user has already booked or viewed using the cosine similarity. We would recommend hotels with the largest similarity to the ones previously booked or viewed or showed interest by the user. Our recommender system is highly dependent on defining an appropriate similarity measure. Eventually, we select a subset of hotels to display to the user or to determine an order in which to display the hotels.
It’s very hard to find public available hotel description data, therefore, I collected them by myself from each hotel’s homepage for over 150 hotels in Seattle area, that includes downtown business hotels, boutique hotels and bed and breakfast, airport business hotels, inns near the universities, motels in the middle of nowhere, and so on. The data can be found here.
import pandas as pdimport numpy as npfrom nltk.corpus import stopwordsfrom sklearn.metrics.pairwise import linear_kernelfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.decomposition import LatentDirichletAllocationimport reimport randomimport plotly.graph_objs as goimport plotly.plotly as pyimport cufflinkspd.options.display.max_columns = 30from IPython.core.interactiveshell import InteractiveShellimport plotly.figure_factory as ffInteractiveShell.ast_node_interactivity = 'all'from plotly.offline import iplotcufflinks.go_offline()cufflinks.set_config_file(world_readable=True, theme='solar')df = pd.read_csv('Seattle_Hotels.csv', encoding="latin-1")df.head()print('We have ', len(df), 'hotels in the data')
Have a look few hotel name and description pairs.
print_description(10)
print_description(100)
Everyone knows Seattle’s Pike Place Market, it is way more than a public farmers market. It is a historical vibrant tourism attraction comprised of hundreds of farmers, craftspeople, small businesses. The hotel industry thrives on location, tourists look for a hotel that is possibly nearest to downtown and / or must-visit attractions of the city. Therefore, every hotel would brag about it if it is not too far from the hotel.
df['word_count'] = df['desc'].apply(lambda x: len(str(x).split()))desc_lengths = list(df['word_count'])print("Number of descriptions:",len(desc_lengths), "\nAverage word count", np.average(desc_lengths), "\nMinimum word count", min(desc_lengths), "\nMaximum word count", max(desc_lengths))
Many hotels use description to their full potential, know how to utilize captivating descriptions to appeal to travelers’ emotions to drive direct bookings. Their descriptions may be longer than others.
The test is pretty clean, we don’t have a lot to do, but just in case.
Create a TF-IDF matrix of unigrams, bigrams, and trigrams for each hotel.
Compute similarity between all hotels using sklearn’s linear_kernel (equivalent to cosine similarity in our case).
Define a function that takes in hotel name as input and returns the top 10 recommended hotels.
Let’s make some recommendations!
recommendations('Hilton Seattle Airport & Conference Center')
A good test on whether our similarity works is that the content based recommender returns all airport hotels when an airport hotel is a seed.
We can also ask Google. The following are recommended by Google for “Hilton Seattle Airport & Conference Center”:
Three out of four recommended by Google were also recommended by us.
The following are recommended by tripadvisor for “Hilton Seattle Airport & Conference Center”:
Not bad either.
Try a bed & breakfast.
recommendations("The Bacon Mansion Bed and Breakfast")
The following are recommended by Google for “The Bacon Mansion Bed and Breakfast”:
Cool!
The following are recommended by tripadvisor for “The Bacon Mansion Bed and Breakfast”, which I was not impressed.
Jupyter notebook can be found on Github, if you prefer, this is a nbviewer version.
Have a productive week!
|
[
{
"code": null,
"e": 410,
"s": 172,
"text": "The cold start problem is a well known and well researched problem for recommender systems, where system is not able to recommend items to users. due to three different situation i.e. for new users, for new products and for new websites."
},
{
"code": null,
"e": 721,
"s": 410,
"text": "Content-based filtering is the method that solve this problem. Our system first uses the metadata of new products when creating recommendations, while visitor action is secondary for a certain period of time. And our systems recommend a product to a user based upon the category and description of the product."
},
{
"code": null,
"e": 1067,
"s": 721,
"text": "Content-based recommendation systems may be used in a variety of domains ranging from recommending web pages, news articles, restaurants, television programs, and hotels. The advantage of content-based filtering is that it doesn’t have a cold-start problem. If you just start out a new website, or any new products can be recommended right away."
},
{
"code": null,
"e": 1476,
"s": 1067,
"text": "Let’s assume we are starting a new online travel agency (OTA), and we have signed up thousands of hotels that are willing to sell on our platform, and we start seeing traffic coming from our website users, but we don’t have any users history, therefore, we are going to build a content-based recommendation systems to analyze hotel descriptions to identify hotels that are of particular interest to the user."
},
{
"code": null,
"e": 1937,
"s": 1476,
"text": "We would like to recommend hotels based on the hotels that a user has already booked or viewed using the cosine similarity. We would recommend hotels with the largest similarity to the ones previously booked or viewed or showed interest by the user. Our recommender system is highly dependent on defining an appropriate similarity measure. Eventually, we select a subset of hotels to display to the user or to determine an order in which to display the hotels."
},
{
"code": null,
"e": 2307,
"s": 1937,
"text": "It’s very hard to find public available hotel description data, therefore, I collected them by myself from each hotel’s homepage for over 150 hotels in Seattle area, that includes downtown business hotels, boutique hotels and bed and breakfast, airport business hotels, inns near the universities, motels in the middle of nowhere, and so on. The data can be found here."
},
{
"code": null,
"e": 3103,
"s": 2307,
"text": "import pandas as pdimport numpy as npfrom nltk.corpus import stopwordsfrom sklearn.metrics.pairwise import linear_kernelfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.decomposition import LatentDirichletAllocationimport reimport randomimport plotly.graph_objs as goimport plotly.plotly as pyimport cufflinkspd.options.display.max_columns = 30from IPython.core.interactiveshell import InteractiveShellimport plotly.figure_factory as ffInteractiveShell.ast_node_interactivity = 'all'from plotly.offline import iplotcufflinks.go_offline()cufflinks.set_config_file(world_readable=True, theme='solar')df = pd.read_csv('Seattle_Hotels.csv', encoding=\"latin-1\")df.head()print('We have ', len(df), 'hotels in the data')"
},
{
"code": null,
"e": 3153,
"s": 3103,
"text": "Have a look few hotel name and description pairs."
},
{
"code": null,
"e": 3175,
"s": 3153,
"text": "print_description(10)"
},
{
"code": null,
"e": 3198,
"s": 3175,
"text": "print_description(100)"
},
{
"code": null,
"e": 3627,
"s": 3198,
"text": "Everyone knows Seattle’s Pike Place Market, it is way more than a public farmers market. It is a historical vibrant tourism attraction comprised of hundreds of farmers, craftspeople, small businesses. The hotel industry thrives on location, tourists look for a hotel that is possibly nearest to downtown and / or must-visit attractions of the city. Therefore, every hotel would brag about it if it is not too far from the hotel."
},
{
"code": null,
"e": 3932,
"s": 3627,
"text": "df['word_count'] = df['desc'].apply(lambda x: len(str(x).split()))desc_lengths = list(df['word_count'])print(\"Number of descriptions:\",len(desc_lengths), \"\\nAverage word count\", np.average(desc_lengths), \"\\nMinimum word count\", min(desc_lengths), \"\\nMaximum word count\", max(desc_lengths))"
},
{
"code": null,
"e": 4135,
"s": 3932,
"text": "Many hotels use description to their full potential, know how to utilize captivating descriptions to appeal to travelers’ emotions to drive direct bookings. Their descriptions may be longer than others."
},
{
"code": null,
"e": 4206,
"s": 4135,
"text": "The test is pretty clean, we don’t have a lot to do, but just in case."
},
{
"code": null,
"e": 4280,
"s": 4206,
"text": "Create a TF-IDF matrix of unigrams, bigrams, and trigrams for each hotel."
},
{
"code": null,
"e": 4395,
"s": 4280,
"text": "Compute similarity between all hotels using sklearn’s linear_kernel (equivalent to cosine similarity in our case)."
},
{
"code": null,
"e": 4490,
"s": 4395,
"text": "Define a function that takes in hotel name as input and returns the top 10 recommended hotels."
},
{
"code": null,
"e": 4523,
"s": 4490,
"text": "Let’s make some recommendations!"
},
{
"code": null,
"e": 4585,
"s": 4523,
"text": "recommendations('Hilton Seattle Airport & Conference Center')"
},
{
"code": null,
"e": 4727,
"s": 4585,
"text": "A good test on whether our similarity works is that the content based recommender returns all airport hotels when an airport hotel is a seed."
},
{
"code": null,
"e": 4841,
"s": 4727,
"text": "We can also ask Google. The following are recommended by Google for “Hilton Seattle Airport & Conference Center”:"
},
{
"code": null,
"e": 4910,
"s": 4841,
"text": "Three out of four recommended by Google were also recommended by us."
},
{
"code": null,
"e": 5005,
"s": 4910,
"text": "The following are recommended by tripadvisor for “Hilton Seattle Airport & Conference Center”:"
},
{
"code": null,
"e": 5021,
"s": 5005,
"text": "Not bad either."
},
{
"code": null,
"e": 5044,
"s": 5021,
"text": "Try a bed & breakfast."
},
{
"code": null,
"e": 5099,
"s": 5044,
"text": "recommendations(\"The Bacon Mansion Bed and Breakfast\")"
},
{
"code": null,
"e": 5182,
"s": 5099,
"text": "The following are recommended by Google for “The Bacon Mansion Bed and Breakfast”:"
},
{
"code": null,
"e": 5188,
"s": 5182,
"text": "Cool!"
},
{
"code": null,
"e": 5303,
"s": 5188,
"text": "The following are recommended by tripadvisor for “The Bacon Mansion Bed and Breakfast”, which I was not impressed."
},
{
"code": null,
"e": 5387,
"s": 5303,
"text": "Jupyter notebook can be found on Github, if you prefer, this is a nbviewer version."
}
] |
How to Check Timezone in Linux - GeeksforGeeks
|
17 Jun, 2021
There are a number of time management utilities available on Linux such as timedatectl, date, etc by which you can view the current timezone in your Linux system. In this article, we will be discussing some ways by which you can check the system timezone in Linux.
We can use the timedatectl command to display the timezone along with other information. We can check for the timezone-related info from the output.
Syntax :
timedatectl
Example :
Using the command timedatectl to display timezone
As we can see in the above example, we can easily find the timezone-related info which is “Asia/Kolkata ( IST, +0530)” in the above output screenshot.
We can use the pipeline feature of Linux ( output from one command becomes the input of another command ) to find out the timezone. In this case, the output generated from the timedatectl command is searched for a keyword, which in our case is “Time Zone” and we only get the relevant output finally.
Syntax :
timedatectl | grep "Time zone"
Example :
Using pipeline feature of Linux on timedatectl and grep to display timezone
In the above example, we have only got the required output “Time zone: Asia/Kolkata ( IST, +0530)” as compared to the previous method in which the only timedatectl was used. This can be a better method if you do not want to search for the required line in the output by yourself as in the previous method.
We can use the cat command and the required file to display the timezone. the cat command displays the contents of a file and for our case, in order to find the timezone, we will search for a file named timezone in /etc Linux directory. etc is a Linux directory that contains all the system configuration files.
Syntax :
cat /etc/timezone
OR
cd /etc
cat timezone
Example 1:
Using the first command “cat /etc/timezone”
using cat /etc/timezone commands to find the timezone
Example 2:
First go to the Linux directory /etc and then type the command cat timezone.
A step by step process to display timezone using cd and cat commands
We can use the date command to view the timezone. Simply type the Linux command date in the terminal and you will get the required output.
Syntax :
date
Example :
Using date command to display timezone
As we can see from the above example, We have used the date command and timezone is displayed, which in our case is IST.
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Basic Operators in Shell Scripting
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24672,
"s": 24406,
"text": "There are a number of time management utilities available on Linux such as timedatectl, date, etc by which you can view the current timezone in your Linux system. In this article, we will be discussing some ways by which you can check the system timezone in Linux. "
},
{
"code": null,
"e": 24821,
"s": 24672,
"text": "We can use the timedatectl command to display the timezone along with other information. We can check for the timezone-related info from the output."
},
{
"code": null,
"e": 24831,
"s": 24821,
"text": "Syntax : "
},
{
"code": null,
"e": 24843,
"s": 24831,
"text": "timedatectl"
},
{
"code": null,
"e": 24853,
"s": 24843,
"text": "Example :"
},
{
"code": null,
"e": 24904,
"s": 24853,
"text": "Using the command timedatectl to display timezone"
},
{
"code": null,
"e": 25055,
"s": 24904,
"text": "As we can see in the above example, we can easily find the timezone-related info which is “Asia/Kolkata ( IST, +0530)” in the above output screenshot."
},
{
"code": null,
"e": 25356,
"s": 25055,
"text": "We can use the pipeline feature of Linux ( output from one command becomes the input of another command ) to find out the timezone. In this case, the output generated from the timedatectl command is searched for a keyword, which in our case is “Time Zone” and we only get the relevant output finally."
},
{
"code": null,
"e": 25365,
"s": 25356,
"text": "Syntax :"
},
{
"code": null,
"e": 25396,
"s": 25365,
"text": "timedatectl | grep \"Time zone\""
},
{
"code": null,
"e": 25406,
"s": 25396,
"text": "Example :"
},
{
"code": null,
"e": 25482,
"s": 25406,
"text": "Using pipeline feature of Linux on timedatectl and grep to display timezone"
},
{
"code": null,
"e": 25788,
"s": 25482,
"text": "In the above example, we have only got the required output “Time zone: Asia/Kolkata ( IST, +0530)” as compared to the previous method in which the only timedatectl was used. This can be a better method if you do not want to search for the required line in the output by yourself as in the previous method."
},
{
"code": null,
"e": 26100,
"s": 25788,
"text": "We can use the cat command and the required file to display the timezone. the cat command displays the contents of a file and for our case, in order to find the timezone, we will search for a file named timezone in /etc Linux directory. etc is a Linux directory that contains all the system configuration files."
},
{
"code": null,
"e": 26109,
"s": 26100,
"text": "Syntax :"
},
{
"code": null,
"e": 26153,
"s": 26109,
"text": "cat /etc/timezone\n\nOR\n\ncd /etc\ncat timezone"
},
{
"code": null,
"e": 26164,
"s": 26153,
"text": "Example 1:"
},
{
"code": null,
"e": 26208,
"s": 26164,
"text": "Using the first command “cat /etc/timezone”"
},
{
"code": null,
"e": 26262,
"s": 26208,
"text": "using cat /etc/timezone commands to find the timezone"
},
{
"code": null,
"e": 26273,
"s": 26262,
"text": "Example 2:"
},
{
"code": null,
"e": 26351,
"s": 26273,
"text": "First go to the Linux directory /etc and then type the command cat timezone. "
},
{
"code": null,
"e": 26420,
"s": 26351,
"text": "A step by step process to display timezone using cd and cat commands"
},
{
"code": null,
"e": 26559,
"s": 26420,
"text": "We can use the date command to view the timezone. Simply type the Linux command date in the terminal and you will get the required output."
},
{
"code": null,
"e": 26568,
"s": 26559,
"text": "Syntax :"
},
{
"code": null,
"e": 26573,
"s": 26568,
"text": "date"
},
{
"code": null,
"e": 26583,
"s": 26573,
"text": "Example :"
},
{
"code": null,
"e": 26622,
"s": 26583,
"text": "Using date command to display timezone"
},
{
"code": null,
"e": 26743,
"s": 26622,
"text": "As we can see from the above example, We have used the date command and timezone is displayed, which in our case is IST."
},
{
"code": null,
"e": 26757,
"s": 26743,
"text": "linux-command"
},
{
"code": null,
"e": 26764,
"s": 26757,
"text": "Picked"
},
{
"code": null,
"e": 26775,
"s": 26764,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26873,
"s": 26775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26882,
"s": 26873,
"text": "Comments"
},
{
"code": null,
"e": 26895,
"s": 26882,
"text": "Old Comments"
},
{
"code": null,
"e": 26921,
"s": 26895,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26958,
"s": 26921,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26993,
"s": 26958,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27030,
"s": 26993,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27070,
"s": 27030,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 27104,
"s": 27070,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27139,
"s": 27104,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 27168,
"s": 27139,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27194,
"s": 27168,
"text": "Docker - COPY Instruction"
}
] |
LISP - Functions
|
A function is a group of statements that together perform a task.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.
The macro named defun is used for defining functions. The defun macro needs three arguments −
Name of the function
Parameters of the function
Body of the function
Syntax for defun is −
(defun name (parameter-list) "Optional documentation string." body)
Let us illustrate the concept with simple examples.
Let's write a function named averagenum that will print the average of four numbers. We will send these numbers as parameters.
Create a new source code file named main.lisp and type the following code in it.
(defun averagenum (n1 n2 n3 n4)
(/ ( + n1 n2 n3 n4) 4)
)
(write(averagenum 10 20 30 40))
When you execute the code, it returns the following result −
25
Let's define and call a function that would calculate the area of a circle when the radius of the circle is given as an argument.
Create a new source code file named main.lisp and type the following code in it.
(defun area-circle(rad)
"Calculates area of a circle with given radius"
(terpri)
(format t "Radius: ~5f" rad)
(format t "~%Area: ~10f" (* 3.141592 rad rad))
)
(area-circle 10)
When you execute the code, it returns the following result −
Radius: 10.0
Area: 314.1592
Please note that −
You can provide an empty list as parameters, which means the function takes no arguments, the list is empty, written as ().
You can provide an empty list as parameters, which means the function takes no arguments, the list is empty, written as ().
LISP also allows optional, multiple, and keyword arguments.
LISP also allows optional, multiple, and keyword arguments.
The documentation string describes the purpose of the function. It is associated with the name of the function and can be obtained using the documentation function.
The documentation string describes the purpose of the function. It is associated with the name of the function and can be obtained using the documentation function.
The body of the function may consist of any number of Lisp expressions.
The body of the function may consist of any number of Lisp expressions.
The value of the last expression in the body is returned as the value of the function.
The value of the last expression in the body is returned as the value of the function.
You can also return a value from the function using the return-from special operator.
You can also return a value from the function using the return-from special operator.
Let us discuss the above concepts in brief. Click following links to find details −
Optional Parameters
Optional Parameters
Rest Parameters
Rest Parameters
Keyword Parameters
Keyword Parameters
Returning Values from a Function
Returning Values from a Function
Lambda Functions
Lambda Functions
Mapping Functions
Mapping Functions
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2126,
"s": 2060,
"text": "A function is a group of statements that together perform a task."
},
{
"code": null,
"e": 2328,
"s": 2126,
"text": "You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task."
},
{
"code": null,
"e": 2422,
"s": 2328,
"text": "The macro named defun is used for defining functions. The defun macro needs three arguments −"
},
{
"code": null,
"e": 2443,
"s": 2422,
"text": "Name of the function"
},
{
"code": null,
"e": 2470,
"s": 2443,
"text": "Parameters of the function"
},
{
"code": null,
"e": 2491,
"s": 2470,
"text": "Body of the function"
},
{
"code": null,
"e": 2513,
"s": 2491,
"text": "Syntax for defun is −"
},
{
"code": null,
"e": 2581,
"s": 2513,
"text": "(defun name (parameter-list) \"Optional documentation string.\" body)"
},
{
"code": null,
"e": 2633,
"s": 2581,
"text": "Let us illustrate the concept with simple examples."
},
{
"code": null,
"e": 2760,
"s": 2633,
"text": "Let's write a function named averagenum that will print the average of four numbers. We will send these numbers as parameters."
},
{
"code": null,
"e": 2841,
"s": 2760,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 2933,
"s": 2841,
"text": "(defun averagenum (n1 n2 n3 n4)\n (/ ( + n1 n2 n3 n4) 4)\n)\n(write(averagenum 10 20 30 40))"
},
{
"code": null,
"e": 2994,
"s": 2933,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 2998,
"s": 2994,
"text": "25\n"
},
{
"code": null,
"e": 3128,
"s": 2998,
"text": "Let's define and call a function that would calculate the area of a circle when the radius of the circle is given as an argument."
},
{
"code": null,
"e": 3209,
"s": 3128,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 3397,
"s": 3209,
"text": "(defun area-circle(rad)\n \"Calculates area of a circle with given radius\"\n (terpri)\n (format t \"Radius: ~5f\" rad)\n (format t \"~%Area: ~10f\" (* 3.141592 rad rad))\n)\n(area-circle 10)"
},
{
"code": null,
"e": 3458,
"s": 3397,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 3490,
"s": 3458,
"text": "Radius: 10.0\nArea: 314.1592\n"
},
{
"code": null,
"e": 3509,
"s": 3490,
"text": "Please note that −"
},
{
"code": null,
"e": 3633,
"s": 3509,
"text": "You can provide an empty list as parameters, which means the function takes no arguments, the list is empty, written as ()."
},
{
"code": null,
"e": 3757,
"s": 3633,
"text": "You can provide an empty list as parameters, which means the function takes no arguments, the list is empty, written as ()."
},
{
"code": null,
"e": 3817,
"s": 3757,
"text": "LISP also allows optional, multiple, and keyword arguments."
},
{
"code": null,
"e": 3877,
"s": 3817,
"text": "LISP also allows optional, multiple, and keyword arguments."
},
{
"code": null,
"e": 4042,
"s": 3877,
"text": "The documentation string describes the purpose of the function. It is associated with the name of the function and can be obtained using the documentation function."
},
{
"code": null,
"e": 4207,
"s": 4042,
"text": "The documentation string describes the purpose of the function. It is associated with the name of the function and can be obtained using the documentation function."
},
{
"code": null,
"e": 4279,
"s": 4207,
"text": "The body of the function may consist of any number of Lisp expressions."
},
{
"code": null,
"e": 4351,
"s": 4279,
"text": "The body of the function may consist of any number of Lisp expressions."
},
{
"code": null,
"e": 4438,
"s": 4351,
"text": "The value of the last expression in the body is returned as the value of the function."
},
{
"code": null,
"e": 4525,
"s": 4438,
"text": "The value of the last expression in the body is returned as the value of the function."
},
{
"code": null,
"e": 4611,
"s": 4525,
"text": "You can also return a value from the function using the return-from special operator."
},
{
"code": null,
"e": 4697,
"s": 4611,
"text": "You can also return a value from the function using the return-from special operator."
},
{
"code": null,
"e": 4781,
"s": 4697,
"text": "Let us discuss the above concepts in brief. Click following links to find details −"
},
{
"code": null,
"e": 4801,
"s": 4781,
"text": "Optional Parameters"
},
{
"code": null,
"e": 4821,
"s": 4801,
"text": "Optional Parameters"
},
{
"code": null,
"e": 4837,
"s": 4821,
"text": "Rest Parameters"
},
{
"code": null,
"e": 4853,
"s": 4837,
"text": "Rest Parameters"
},
{
"code": null,
"e": 4872,
"s": 4853,
"text": "Keyword Parameters"
},
{
"code": null,
"e": 4891,
"s": 4872,
"text": "Keyword Parameters"
},
{
"code": null,
"e": 4924,
"s": 4891,
"text": "Returning Values from a Function"
},
{
"code": null,
"e": 4957,
"s": 4924,
"text": "Returning Values from a Function"
},
{
"code": null,
"e": 4974,
"s": 4957,
"text": "Lambda Functions"
},
{
"code": null,
"e": 4991,
"s": 4974,
"text": "Lambda Functions"
},
{
"code": null,
"e": 5009,
"s": 4991,
"text": "Mapping Functions"
},
{
"code": null,
"e": 5027,
"s": 5009,
"text": "Mapping Functions"
},
{
"code": null,
"e": 5060,
"s": 5027,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5075,
"s": 5060,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5082,
"s": 5075,
"text": " Print"
},
{
"code": null,
"e": 5093,
"s": 5082,
"text": " Add Notes"
}
] |
How to match a word in python using Regular Expression?
|
The following code matches the word ‘meeting’ in the given string.
It uses positive look-ahead and look-behind assertions to respect enclosing characters but without including them in the match.
import re
s = """http://www.google.com/meeting_agenda_minutes.html"""
result = re.findall(r'(?<=[\W_])meeting(?=[\W_])', s)
print result
['meeting']
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "The following code matches the word ‘meeting’ in the given string."
},
{
"code": null,
"e": 1257,
"s": 1129,
"text": "It uses positive look-ahead and look-behind assertions to respect enclosing characters but without including them in the match."
},
{
"code": null,
"e": 1394,
"s": 1257,
"text": "import re\ns = \"\"\"http://www.google.com/meeting_agenda_minutes.html\"\"\"\nresult = re.findall(r'(?<=[\\W_])meeting(?=[\\W_])', s)\nprint result"
},
{
"code": null,
"e": 1406,
"s": 1394,
"text": "['meeting']"
}
] |
What is InputMisMatchException in Java how do we handle it?
|
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.
To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().
Whenever you take inputs from the user using a Scanner class. If the inputs passed doesn’t match the method or an InputMisMatchException is thrown. For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs.
import java.util.Scanner;
public class StudentData{
int age;
String name;
public StudentData(String name, int age){
this.age = age;
this.name = name;
}
public void display() {
System.out.println("Name of the student is: "+name);
System.out.println("Age of the student is: "+age);
}
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your age: ");
int age = sc.nextInt();
StudentData obj = new StudentData(name, age);
obj.display();
}
}
Enter your name:
Krishna
Enter your age:
twenty
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at july_set3.StudentData.main(StudentData.java:20)
The only way to handle this exception is to make sure that you enter proper values while passing inputs. It is suggested to specify required values with complete details while reading data from user using scanner class.
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions."
},
{
"code": null,
"e": 1543,
"s": 1285,
"text": "To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next()."
},
{
"code": null,
"e": 1822,
"s": 1543,
"text": "Whenever you take inputs from the user using a Scanner class. If the inputs passed doesn’t match the method or an InputMisMatchException is thrown. For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs."
},
{
"code": null,
"e": 2467,
"s": 1822,
"text": "import java.util.Scanner;\npublic class StudentData{\n int age;\n String name;\n public StudentData(String name, int age){\n this.age = age;\n this.name = name;\n }\n public void display() {\n System.out.println(\"Name of the student is: \"+name);\n System.out.println(\"Age of the student is: \"+age);\n }\n public static void main (String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your age: \");\n int age = sc.nextInt();\n StudentData obj = new StudentData(name, age);\n obj.display();\n }\n}"
},
{
"code": null,
"e": 2819,
"s": 2467,
"text": "Enter your name:\nKrishna\nEnter your age:\ntwenty\nException in thread \"main\" java.util.InputMismatchException\n at java.util.Scanner.throwFor(Unknown Source)\n at java.util.Scanner.next(Unknown Source)\n at java.util.Scanner.nextInt(Unknown Source)\n at java.util.Scanner.nextInt(Unknown Source)\n at july_set3.StudentData.main(StudentData.java:20)"
},
{
"code": null,
"e": 3039,
"s": 2819,
"text": "The only way to handle this exception is to make sure that you enter proper values while passing inputs. It is suggested to specify required values with complete details while reading data from user using scanner class."
}
] |
Attention is all you need: Discovering the Transformer paper | by Eduardo Muñoz | Towards Data Science
|
In this post we will describe and demystify the relevant artifacts in the paper “Attention is all you need” (Vaswani, Ashish & Shazeer, Noam & Parmar, Niki & Uszkoreit, Jakob & Jones, Llion & Gomez, Aidan & Kaiser, Lukasz & Polosukhin, Illia. (2017))[1]. This paper was a great advance in the use of the attention mechanism, being the main improvement for a model called Transformer. The most famous current models that are emerging in NLP tasks consist of dozens of transformers or some of their variants, for example, GPT-2 or BERT.
We will describe the components of this model, analyze their operation and build a simple model that we will apply to a small-scale NMT problem (Neural Machine Translation). To read more about the problem that we will address and to know how the basic attention mechanism works, I recommend you to read my previous post “A Guide on the Encoder-Decoder Model and the Attention Mechanism”.
In sequence-to-sequence problems such as the neural machine translation, the initial proposals were based on the use of RNNs in an encoder-decoder architecture. These architectures have a great limitation when working with long sequences, their ability to retain information from the first elements was lost when new elements were incorporated into the sequence. In the encoder, the hidden state in every step is associated with a certain word in the input sentence, usually one of the most recent. Therefore, if the decoder only accesses the last hidden state of the decoder, it will lose relevant information about the first elements of the sequence. Then to deal with this limitation, a new concept were introduced the attention mechanism.
Instead of paying attention to the last state of the encoder as is usually done with RNNs, in each step of the decoder we look at all the states of the encoder, being able to access information about all the elements of the input sequence. This is what attention does, it extracts information from the whole sequence, a weighted sum of all the past encoder states. This allows the decoder to assign greater weight or importance to a certain element of the input for each element of the output. Learning in every step to focus in the right element of the input to predict the next output element.
But this approach continues to have an important limitation, each sequence must be treated one element at a time. Both the encoder and the decoder have to wait till the completion of t-1 steps to process thet-th step. So when dealing with huge corpus it is very time consuming and computationally inefficient.
In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization ... the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence-aligned RNNs or convolution.
“Attention is all you need” paper [1]
The Transformer model extract features for each word using a self-attention mechanism to figure out how important all the other words in the sentence are w.r.t. to the aforementioned word. And no recurrent units are used to obtain this features, they are just weighted sums and activations, so they can be very parallelizable and efficient.
But we will dive deeper into its architecture (next figure) to understand what all this pieces do [1].
We can observe there is an encoder model on the left side and the decoder on the right one. Both contains a core block of “an attention and a feed-forward network” repeated N times. But first we need to explore a core concept in depth: the self-attention mechanism.
Self-attention is a sequence-to-sequence operation: a sequence of vectors goes in, and a sequence of vectors comes out. Let’s call the input vectors x1, x2,..., xt and the corresponding output vectors y1, y2,..., yt. The vectors all have dimension k. To produce output vector yi, the self attention operation simply takes a weighted average over all the input vectors, the simplest option is the dot product.
Transformers from scratch by Peter Bloem [2]
In the self-attention mechanism of our model we need to introduce three elements: Queries, Values and Keys
Every input vector is used in three different ways in the self-attention mechanism: the Query, the Key and the Value. In every role, it is compared to the other vectors to get its own output yi(Query), to get the j-th output yj(Key) and to compute each output vector once the weights have been established (Value).
To obtain this roles, we need three weight matrices of dimensions k x k and compute three linear transformation for each xi:
These three matrices are usually known as K, Q and V, three learnable weight layers that are applied to the same encoded input. Consequently, as each of these three matrices come from the same input, we can apply the attention mechanism of the input vector with itself, a “self-attention”.
The input consists of queries and keys of dimension dk, and values of dimension dv. We compute the dot product of the query with all keys, divide each by the square root of dk, and apply a softmax function to obtain the weights on the values.
“Attention is all you need” paper [1]
Then we use the Q, K and V matrices to calculate the attention scores. The scores measure how much focus to place on other places or words of the input sequence w.r.t a word at a certain position. That is, the dot product of the query vector with the key vector of the respective word we’re scoring. So, for position 1 we calculate the dot product (.) of q1and k1, then q1. k2, q1. k3 and so on,...
Next we apply the “scaled” factor to have more stable gradients. The softmax function can not work properly with large values, resulting in vanishing the gradients and slowing down the learning, [2]. After “softmaxing” we multiply by the Value matrix to keep the values of the words we want to focus on and minimizing or removing the values for the irrelevant words (its value in V matrix should be very small).
The formula for these operations is:
In the previous description the attention scores are focused on the whole sentence at a time, this would produce the same results even if two sentences contain the same words in a different order. Instead, we would like to attend to different segments of the words. “We can give the self attention greater power of discrimination, by combining several self attention heads, dividing the words vectors into a fixed number (h, number of heads) of chunks, and then self-attention is applied on the corresponding chunks, using Q, K and V sub-matrices.”, [2] Peter Bloem, “Transformers from scratch”. This produce h different output matrices of scores.
But the next layer (the Feed-Forward layer) is expecting just one matrix, a vector for each word, so “after calculating the dot product of every head, we concatenate the output matrices and multiply them by an additional weights matrix Wo,”[3]. This final matrix captures information from all the attention heads.
We mentioned briefly that the order of the words in the sentence is an issue to solve in this model, because the network and the self-attention mechanism is permutation invariant. If we shuffle up the words in the input sentence, we get the same solutions. We need to create a representation of the position of the word in the sentence and add it to the word embedding.
To this end, we add “positional encodings” to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension as the embeddings, so that the two can be summed. There are many choices of positional encodings.
“Attention is all you need” paper
So, we apply a function to map the position in the sentence to a real valued vector. The network will learn how to use this information. Another approach would be to use a position embedding, similar to word embedding, coding every known position with a vector. “It would requiere sentences of all accepted positions during the training loop but positional encoding allow the model to extrapolate to sequence lengths longer than the ones encountered during training”, [2].
In the paper a sinusoidal function is applied:
Now that all the main pieces of the model have been described we can introduce the encoder components, [4]:
Positional encoding: Add the position encoding to the input embedding (our input words are transformed to embedding vectors). “The same weight matrix is shared between the two embedding layers (encoder and decoder) and the pre-softmax linear transformation. In the embedding layers, we multiply those weights by square root of the model dimension” [1].
N=6 identical layers, containing two sub-layers: a multi-head self-attention mechanism, and a fully connected feed-forward network (two linear transformations with a ReLU activation). But it is applied position-wise to the input, which means that the same neural network is applied to every single “token” vector belonging to the sentence sequence.
There is a residual connection around each sub-layer (attention and FC network), summing up the output of the layer with its input, followed by a layer normalization.
Before every residual connection, a regularization is applied: “We apply dropout to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks” [1] with a dropout rate of 0.1.
Normalization and residual connections are standard tricks used to help deep neural networks train faster and more accurately. The layer normalization is applied over the embedding dimension only.
Peter Bloem, “Transformers from scratch” [2]
First we implement the encoder layer, each one of the six blocks, contained in an encoder:
The next figure will show the components detailed:
And the encoder code:
Keep in mind that only the vector from the last layer (6-th) is sent to the decoder.
The decoder share some components with the encoder but they are used in a different way to take into account the encoder output, [4]:
Positional encoding: Similar that the one in the encoder
N=6 identical layers, containing 3 three sub-layers. First, the Masked Multi-head attention or masked causal attention to prevent positions from attending to subsequent positions. “This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i” [1]. It is implemented setting to −∞ the values corresponding to the forbidden states in the softmax layer of the dot-product attention modules. The second component or “encoder-decoder attention” performs multi-head attention over the output of the decoder, the Key and Value vectors come from the output of the encoder but the queries come from the previous decoder layer. “This allows every position in the decoder to attend over all positions in the input sequence” [1]. And finally the fully-connected network.
The residual connection and layer normalization around each sub-layer, similar to the encoder.
And repeat the same residual dropout that was executed in the encoder.
The decoder layer:
At the end of the N stacked decoders, the linear layer, a fully-connected network, transforms the stacked outputs to a much larger vector, the logits. “The softmax layer then turns those scores (logits) into probabilities (all positive, all add up to 1.0). The cell with the highest probability is chosen, and the word associated with it is produced as the output for this time step”, [3] Jay Alammar, “The Ilustrated Transformer” .
The decoder component:
Once we have defined our components and created the encoder, the decoder and the linear-softmax final layer, we join the pieces to form our model, the Transformer.
It is worth mentioning that we create 3 masks, each of which will allow us:
Encoder mask: It is a padding mask to discard the pad tokens from the attention calculation.
Decoder mask 1: this mask is a union of the padding mask and the look ahead mask which will help the causal attention to discard the tokens “in the future”. We take the maximum value between the padding mask and the look ahead one.
Decoder mask 2: it is the padding mask and is applied in the encoder-decoder attention layer.
As you can see, then we call the encoder, the decoder and the final linear-softmax layer to get the predicted output from our Transformer model.
Now that we have described in detail the components in the paper, we are ready to implement them and train a transformer model on a NMT problem. It is a toy problem for educational purposes.
We won’t deal with the data wrangling in this blog post. Follow the link I mentioned in the introduction for more information and the code provided to see how the data is loaded and prepared. In summary, create the vocabulary, tokenize (including a eos and sos token) and pad the sentences. Then we create a Dataset, a batch data generator, for training on batches.
We need to create a custom loss function to mask the padding tokens.
We use an Adam optimizer described in the paper, with beta1=0.9, beta2=0.98 and epsilon=10e-9 . And then we create a scheduler to vary the learning rate over the training process according to:
The train function is similar to many other Tensorflow trainings, an usual training loop for sequence-to-sequence tasks:
For every iteration on the batch generator that produce batch size inputs and outputs
Get the input sequence from 0 to length-1 and the actual outputs from 1 to length, the next word expected at every sequence step.
Call the transformer to get the predictions
Calculate the loss function between the real outputs and the predictions
Apply the gradients to update the weights in the model and update the optimizer too
Calculate the mean loss and the accuracy for the batch data
Show some results and save the model in every epoch
And that’s all, we have all the necessary elements to train our model, we just need to create them and call the train function:
When training a ML model we are not only interested in optimize losses or accuracies, we want our model to make good enough predictions and, in this case, see how the model works with new sentences. The predict function will input a tokenized sentence to the model and return the predicted new sentence, in our example, a translation from English to Spanish.
These are the steps in that process:
Tokenize the input sentence to a sequence of tokens
Set the initial output sequence to the sos token
Until we reach the max length or the eos token is returned by the model
Get the next word predicted. The model returns the logits, remember that the softmax function is applied in the loss calculation.
Get the index in the vocabulary of the word with the highest probability
Concatenate the next word predicted to the output sequence
And finally our last function receives a sentence in English, calls the transformer to translate it to Spanish and shows the result.
For this example, we just experiment with some values for the model dimension and the units of the feedforward network to train the model for an hour. If you want to optimize the model, you should probably train it for longer and with many different values for the hyperparameters.
The code is available in my github repository “Transformer-NMT”. The code is partially extracted from an excellent course by SuperDataScience Team called “Modern Natural Language Processing in Python” on Udemy. I highly recommend it.
Some examples of translations are:
#Show some translationssentence = "you should pay for it."print("Input sentence: {}".format(sentence))predicted_sentence = translate(sentence)print("Output sentence: {}".format(predicted_sentence))Input sentence: you should pay for it. Output sentence: Deberías pagar por ello.#Show some translationssentence = "we have no extra money."print("Input sentence: {}".format(sentence))predicted_sentence = translate(sentence)print("Output sentence: {}".format(predicted_sentence))Input sentence: we have no extra money. Output sentence: No tenemos dinero extra.#Show some translationssentence = "This is a problem to deal with."print("Input sentence: {}".format(sentence))predicted_sentence = translate(sentence)print("Output sentence: {}".format(predicted_sentence))Input sentence: This is a problem to deal with. Output sentence: Este problema es un problema con eso.
I hope you enjoy experimenting with the Transformer model. In future post we will deal with another NLP tasks.
[1] Vaswani, Ashish & Shazeer, Noam & Parmar, Niki & Uszkoreit, Jakob & Jones, Llion & Gomez, Aidan & Kaiser, Lukasz & Polosukhin, Illia, “Attention is all you need” , 2017.
[2] Peter Bloem, “Transformers from scratch” blog post, 2019.
[3] Jay Alammar, “The Ilustrated Transformer” blog post, 2018.
[4] Lilian Weng, “Attention? Attention!!” blog post, 2018.
[5] Ricardo Faúndez-CArrasco, “Attention is all you need’s review” blog post, 2017
[6] Alexander Rush, “The Annotated Transformer”, 2018, Harvard NLP group.
|
[
{
"code": null,
"e": 706,
"s": 171,
"text": "In this post we will describe and demystify the relevant artifacts in the paper “Attention is all you need” (Vaswani, Ashish & Shazeer, Noam & Parmar, Niki & Uszkoreit, Jakob & Jones, Llion & Gomez, Aidan & Kaiser, Lukasz & Polosukhin, Illia. (2017))[1]. This paper was a great advance in the use of the attention mechanism, being the main improvement for a model called Transformer. The most famous current models that are emerging in NLP tasks consist of dozens of transformers or some of their variants, for example, GPT-2 or BERT."
},
{
"code": null,
"e": 1094,
"s": 706,
"text": "We will describe the components of this model, analyze their operation and build a simple model that we will apply to a small-scale NMT problem (Neural Machine Translation). To read more about the problem that we will address and to know how the basic attention mechanism works, I recommend you to read my previous post “A Guide on the Encoder-Decoder Model and the Attention Mechanism”."
},
{
"code": null,
"e": 1837,
"s": 1094,
"text": "In sequence-to-sequence problems such as the neural machine translation, the initial proposals were based on the use of RNNs in an encoder-decoder architecture. These architectures have a great limitation when working with long sequences, their ability to retain information from the first elements was lost when new elements were incorporated into the sequence. In the encoder, the hidden state in every step is associated with a certain word in the input sentence, usually one of the most recent. Therefore, if the decoder only accesses the last hidden state of the decoder, it will lose relevant information about the first elements of the sequence. Then to deal with this limitation, a new concept were introduced the attention mechanism."
},
{
"code": null,
"e": 2433,
"s": 1837,
"text": "Instead of paying attention to the last state of the encoder as is usually done with RNNs, in each step of the decoder we look at all the states of the encoder, being able to access information about all the elements of the input sequence. This is what attention does, it extracts information from the whole sequence, a weighted sum of all the past encoder states. This allows the decoder to assign greater weight or importance to a certain element of the input for each element of the output. Learning in every step to focus in the right element of the input to predict the next output element."
},
{
"code": null,
"e": 2743,
"s": 2433,
"text": "But this approach continues to have an important limitation, each sequence must be treated one element at a time. Both the encoder and the decoder have to wait till the completion of t-1 steps to process thet-th step. So when dealing with huge corpus it is very time consuming and computationally inefficient."
},
{
"code": null,
"e": 3187,
"s": 2743,
"text": "In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization ... the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence-aligned RNNs or convolution."
},
{
"code": null,
"e": 3225,
"s": 3187,
"text": "“Attention is all you need” paper [1]"
},
{
"code": null,
"e": 3566,
"s": 3225,
"text": "The Transformer model extract features for each word using a self-attention mechanism to figure out how important all the other words in the sentence are w.r.t. to the aforementioned word. And no recurrent units are used to obtain this features, they are just weighted sums and activations, so they can be very parallelizable and efficient."
},
{
"code": null,
"e": 3669,
"s": 3566,
"text": "But we will dive deeper into its architecture (next figure) to understand what all this pieces do [1]."
},
{
"code": null,
"e": 3935,
"s": 3669,
"text": "We can observe there is an encoder model on the left side and the decoder on the right one. Both contains a core block of “an attention and a feed-forward network” repeated N times. But first we need to explore a core concept in depth: the self-attention mechanism."
},
{
"code": null,
"e": 4344,
"s": 3935,
"text": "Self-attention is a sequence-to-sequence operation: a sequence of vectors goes in, and a sequence of vectors comes out. Let’s call the input vectors x1, x2,..., xt and the corresponding output vectors y1, y2,..., yt. The vectors all have dimension k. To produce output vector yi, the self attention operation simply takes a weighted average over all the input vectors, the simplest option is the dot product."
},
{
"code": null,
"e": 4389,
"s": 4344,
"text": "Transformers from scratch by Peter Bloem [2]"
},
{
"code": null,
"e": 4496,
"s": 4389,
"text": "In the self-attention mechanism of our model we need to introduce three elements: Queries, Values and Keys"
},
{
"code": null,
"e": 4811,
"s": 4496,
"text": "Every input vector is used in three different ways in the self-attention mechanism: the Query, the Key and the Value. In every role, it is compared to the other vectors to get its own output yi(Query), to get the j-th output yj(Key) and to compute each output vector once the weights have been established (Value)."
},
{
"code": null,
"e": 4936,
"s": 4811,
"text": "To obtain this roles, we need three weight matrices of dimensions k x k and compute three linear transformation for each xi:"
},
{
"code": null,
"e": 5226,
"s": 4936,
"text": "These three matrices are usually known as K, Q and V, three learnable weight layers that are applied to the same encoded input. Consequently, as each of these three matrices come from the same input, we can apply the attention mechanism of the input vector with itself, a “self-attention”."
},
{
"code": null,
"e": 5469,
"s": 5226,
"text": "The input consists of queries and keys of dimension dk, and values of dimension dv. We compute the dot product of the query with all keys, divide each by the square root of dk, and apply a softmax function to obtain the weights on the values."
},
{
"code": null,
"e": 5507,
"s": 5469,
"text": "“Attention is all you need” paper [1]"
},
{
"code": null,
"e": 5906,
"s": 5507,
"text": "Then we use the Q, K and V matrices to calculate the attention scores. The scores measure how much focus to place on other places or words of the input sequence w.r.t a word at a certain position. That is, the dot product of the query vector with the key vector of the respective word we’re scoring. So, for position 1 we calculate the dot product (.) of q1and k1, then q1. k2, q1. k3 and so on,..."
},
{
"code": null,
"e": 6318,
"s": 5906,
"text": "Next we apply the “scaled” factor to have more stable gradients. The softmax function can not work properly with large values, resulting in vanishing the gradients and slowing down the learning, [2]. After “softmaxing” we multiply by the Value matrix to keep the values of the words we want to focus on and minimizing or removing the values for the irrelevant words (its value in V matrix should be very small)."
},
{
"code": null,
"e": 6355,
"s": 6318,
"text": "The formula for these operations is:"
},
{
"code": null,
"e": 7003,
"s": 6355,
"text": "In the previous description the attention scores are focused on the whole sentence at a time, this would produce the same results even if two sentences contain the same words in a different order. Instead, we would like to attend to different segments of the words. “We can give the self attention greater power of discrimination, by combining several self attention heads, dividing the words vectors into a fixed number (h, number of heads) of chunks, and then self-attention is applied on the corresponding chunks, using Q, K and V sub-matrices.”, [2] Peter Bloem, “Transformers from scratch”. This produce h different output matrices of scores."
},
{
"code": null,
"e": 7317,
"s": 7003,
"text": "But the next layer (the Feed-Forward layer) is expecting just one matrix, a vector for each word, so “after calculating the dot product of every head, we concatenate the output matrices and multiply them by an additional weights matrix Wo,”[3]. This final matrix captures information from all the attention heads."
},
{
"code": null,
"e": 7687,
"s": 7317,
"text": "We mentioned briefly that the order of the words in the sentence is an issue to solve in this model, because the network and the self-attention mechanism is permutation invariant. If we shuffle up the words in the input sentence, we get the same solutions. We need to create a representation of the position of the word in the sentence and add it to the word embedding."
},
{
"code": null,
"e": 7951,
"s": 7687,
"text": "To this end, we add “positional encodings” to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension as the embeddings, so that the two can be summed. There are many choices of positional encodings."
},
{
"code": null,
"e": 7985,
"s": 7951,
"text": "“Attention is all you need” paper"
},
{
"code": null,
"e": 8458,
"s": 7985,
"text": "So, we apply a function to map the position in the sentence to a real valued vector. The network will learn how to use this information. Another approach would be to use a position embedding, similar to word embedding, coding every known position with a vector. “It would requiere sentences of all accepted positions during the training loop but positional encoding allow the model to extrapolate to sequence lengths longer than the ones encountered during training”, [2]."
},
{
"code": null,
"e": 8505,
"s": 8458,
"text": "In the paper a sinusoidal function is applied:"
},
{
"code": null,
"e": 8613,
"s": 8505,
"text": "Now that all the main pieces of the model have been described we can introduce the encoder components, [4]:"
},
{
"code": null,
"e": 8966,
"s": 8613,
"text": "Positional encoding: Add the position encoding to the input embedding (our input words are transformed to embedding vectors). “The same weight matrix is shared between the two embedding layers (encoder and decoder) and the pre-softmax linear transformation. In the embedding layers, we multiply those weights by square root of the model dimension” [1]."
},
{
"code": null,
"e": 9315,
"s": 8966,
"text": "N=6 identical layers, containing two sub-layers: a multi-head self-attention mechanism, and a fully connected feed-forward network (two linear transformations with a ReLU activation). But it is applied position-wise to the input, which means that the same neural network is applied to every single “token” vector belonging to the sentence sequence."
},
{
"code": null,
"e": 9482,
"s": 9315,
"text": "There is a residual connection around each sub-layer (attention and FC network), summing up the output of the layer with its input, followed by a layer normalization."
},
{
"code": null,
"e": 9815,
"s": 9482,
"text": "Before every residual connection, a regularization is applied: “We apply dropout to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks” [1] with a dropout rate of 0.1."
},
{
"code": null,
"e": 10012,
"s": 9815,
"text": "Normalization and residual connections are standard tricks used to help deep neural networks train faster and more accurately. The layer normalization is applied over the embedding dimension only."
},
{
"code": null,
"e": 10057,
"s": 10012,
"text": "Peter Bloem, “Transformers from scratch” [2]"
},
{
"code": null,
"e": 10148,
"s": 10057,
"text": "First we implement the encoder layer, each one of the six blocks, contained in an encoder:"
},
{
"code": null,
"e": 10199,
"s": 10148,
"text": "The next figure will show the components detailed:"
},
{
"code": null,
"e": 10221,
"s": 10199,
"text": "And the encoder code:"
},
{
"code": null,
"e": 10306,
"s": 10221,
"text": "Keep in mind that only the vector from the last layer (6-th) is sent to the decoder."
},
{
"code": null,
"e": 10440,
"s": 10306,
"text": "The decoder share some components with the encoder but they are used in a different way to take into account the encoder output, [4]:"
},
{
"code": null,
"e": 10497,
"s": 10440,
"text": "Positional encoding: Similar that the one in the encoder"
},
{
"code": null,
"e": 11389,
"s": 10497,
"text": "N=6 identical layers, containing 3 three sub-layers. First, the Masked Multi-head attention or masked causal attention to prevent positions from attending to subsequent positions. “This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i” [1]. It is implemented setting to −∞ the values corresponding to the forbidden states in the softmax layer of the dot-product attention modules. The second component or “encoder-decoder attention” performs multi-head attention over the output of the decoder, the Key and Value vectors come from the output of the encoder but the queries come from the previous decoder layer. “This allows every position in the decoder to attend over all positions in the input sequence” [1]. And finally the fully-connected network."
},
{
"code": null,
"e": 11484,
"s": 11389,
"text": "The residual connection and layer normalization around each sub-layer, similar to the encoder."
},
{
"code": null,
"e": 11555,
"s": 11484,
"text": "And repeat the same residual dropout that was executed in the encoder."
},
{
"code": null,
"e": 11574,
"s": 11555,
"text": "The decoder layer:"
},
{
"code": null,
"e": 12007,
"s": 11574,
"text": "At the end of the N stacked decoders, the linear layer, a fully-connected network, transforms the stacked outputs to a much larger vector, the logits. “The softmax layer then turns those scores (logits) into probabilities (all positive, all add up to 1.0). The cell with the highest probability is chosen, and the word associated with it is produced as the output for this time step”, [3] Jay Alammar, “The Ilustrated Transformer” ."
},
{
"code": null,
"e": 12030,
"s": 12007,
"text": "The decoder component:"
},
{
"code": null,
"e": 12194,
"s": 12030,
"text": "Once we have defined our components and created the encoder, the decoder and the linear-softmax final layer, we join the pieces to form our model, the Transformer."
},
{
"code": null,
"e": 12270,
"s": 12194,
"text": "It is worth mentioning that we create 3 masks, each of which will allow us:"
},
{
"code": null,
"e": 12363,
"s": 12270,
"text": "Encoder mask: It is a padding mask to discard the pad tokens from the attention calculation."
},
{
"code": null,
"e": 12595,
"s": 12363,
"text": "Decoder mask 1: this mask is a union of the padding mask and the look ahead mask which will help the causal attention to discard the tokens “in the future”. We take the maximum value between the padding mask and the look ahead one."
},
{
"code": null,
"e": 12689,
"s": 12595,
"text": "Decoder mask 2: it is the padding mask and is applied in the encoder-decoder attention layer."
},
{
"code": null,
"e": 12834,
"s": 12689,
"text": "As you can see, then we call the encoder, the decoder and the final linear-softmax layer to get the predicted output from our Transformer model."
},
{
"code": null,
"e": 13025,
"s": 12834,
"text": "Now that we have described in detail the components in the paper, we are ready to implement them and train a transformer model on a NMT problem. It is a toy problem for educational purposes."
},
{
"code": null,
"e": 13391,
"s": 13025,
"text": "We won’t deal with the data wrangling in this blog post. Follow the link I mentioned in the introduction for more information and the code provided to see how the data is loaded and prepared. In summary, create the vocabulary, tokenize (including a eos and sos token) and pad the sentences. Then we create a Dataset, a batch data generator, for training on batches."
},
{
"code": null,
"e": 13460,
"s": 13391,
"text": "We need to create a custom loss function to mask the padding tokens."
},
{
"code": null,
"e": 13653,
"s": 13460,
"text": "We use an Adam optimizer described in the paper, with beta1=0.9, beta2=0.98 and epsilon=10e-9 . And then we create a scheduler to vary the learning rate over the training process according to:"
},
{
"code": null,
"e": 13774,
"s": 13653,
"text": "The train function is similar to many other Tensorflow trainings, an usual training loop for sequence-to-sequence tasks:"
},
{
"code": null,
"e": 13860,
"s": 13774,
"text": "For every iteration on the batch generator that produce batch size inputs and outputs"
},
{
"code": null,
"e": 13990,
"s": 13860,
"text": "Get the input sequence from 0 to length-1 and the actual outputs from 1 to length, the next word expected at every sequence step."
},
{
"code": null,
"e": 14034,
"s": 13990,
"text": "Call the transformer to get the predictions"
},
{
"code": null,
"e": 14107,
"s": 14034,
"text": "Calculate the loss function between the real outputs and the predictions"
},
{
"code": null,
"e": 14191,
"s": 14107,
"text": "Apply the gradients to update the weights in the model and update the optimizer too"
},
{
"code": null,
"e": 14251,
"s": 14191,
"text": "Calculate the mean loss and the accuracy for the batch data"
},
{
"code": null,
"e": 14303,
"s": 14251,
"text": "Show some results and save the model in every epoch"
},
{
"code": null,
"e": 14431,
"s": 14303,
"text": "And that’s all, we have all the necessary elements to train our model, we just need to create them and call the train function:"
},
{
"code": null,
"e": 14790,
"s": 14431,
"text": "When training a ML model we are not only interested in optimize losses or accuracies, we want our model to make good enough predictions and, in this case, see how the model works with new sentences. The predict function will input a tokenized sentence to the model and return the predicted new sentence, in our example, a translation from English to Spanish."
},
{
"code": null,
"e": 14827,
"s": 14790,
"text": "These are the steps in that process:"
},
{
"code": null,
"e": 14879,
"s": 14827,
"text": "Tokenize the input sentence to a sequence of tokens"
},
{
"code": null,
"e": 14928,
"s": 14879,
"text": "Set the initial output sequence to the sos token"
},
{
"code": null,
"e": 15000,
"s": 14928,
"text": "Until we reach the max length or the eos token is returned by the model"
},
{
"code": null,
"e": 15130,
"s": 15000,
"text": "Get the next word predicted. The model returns the logits, remember that the softmax function is applied in the loss calculation."
},
{
"code": null,
"e": 15203,
"s": 15130,
"text": "Get the index in the vocabulary of the word with the highest probability"
},
{
"code": null,
"e": 15262,
"s": 15203,
"text": "Concatenate the next word predicted to the output sequence"
},
{
"code": null,
"e": 15395,
"s": 15262,
"text": "And finally our last function receives a sentence in English, calls the transformer to translate it to Spanish and shows the result."
},
{
"code": null,
"e": 15677,
"s": 15395,
"text": "For this example, we just experiment with some values for the model dimension and the units of the feedforward network to train the model for an hour. If you want to optimize the model, you should probably train it for longer and with many different values for the hyperparameters."
},
{
"code": null,
"e": 15911,
"s": 15677,
"text": "The code is available in my github repository “Transformer-NMT”. The code is partially extracted from an excellent course by SuperDataScience Team called “Modern Natural Language Processing in Python” on Udemy. I highly recommend it."
},
{
"code": null,
"e": 15946,
"s": 15911,
"text": "Some examples of translations are:"
},
{
"code": null,
"e": 16812,
"s": 15946,
"text": "#Show some translationssentence = \"you should pay for it.\"print(\"Input sentence: {}\".format(sentence))predicted_sentence = translate(sentence)print(\"Output sentence: {}\".format(predicted_sentence))Input sentence: you should pay for it. Output sentence: Deberías pagar por ello.#Show some translationssentence = \"we have no extra money.\"print(\"Input sentence: {}\".format(sentence))predicted_sentence = translate(sentence)print(\"Output sentence: {}\".format(predicted_sentence))Input sentence: we have no extra money. Output sentence: No tenemos dinero extra.#Show some translationssentence = \"This is a problem to deal with.\"print(\"Input sentence: {}\".format(sentence))predicted_sentence = translate(sentence)print(\"Output sentence: {}\".format(predicted_sentence))Input sentence: This is a problem to deal with. Output sentence: Este problema es un problema con eso."
},
{
"code": null,
"e": 16923,
"s": 16812,
"text": "I hope you enjoy experimenting with the Transformer model. In future post we will deal with another NLP tasks."
},
{
"code": null,
"e": 17097,
"s": 16923,
"text": "[1] Vaswani, Ashish & Shazeer, Noam & Parmar, Niki & Uszkoreit, Jakob & Jones, Llion & Gomez, Aidan & Kaiser, Lukasz & Polosukhin, Illia, “Attention is all you need” , 2017."
},
{
"code": null,
"e": 17159,
"s": 17097,
"text": "[2] Peter Bloem, “Transformers from scratch” blog post, 2019."
},
{
"code": null,
"e": 17222,
"s": 17159,
"text": "[3] Jay Alammar, “The Ilustrated Transformer” blog post, 2018."
},
{
"code": null,
"e": 17281,
"s": 17222,
"text": "[4] Lilian Weng, “Attention? Attention!!” blog post, 2018."
},
{
"code": null,
"e": 17365,
"s": 17281,
"text": "[5] Ricardo Faúndez-CArrasco, “Attention is all you need’s review” blog post, 2017"
}
] |
How to convert an image to a PyTorch Tensor?
|
A PyTorch tensor is an n-dimensional array (matrix) containing elements of a single data type. A tensor is like a numpy array. The difference between
numpy arrays and PyTorch tensors is that the tensors utilize the GPUs to
accelerate the numeric computations. For the accelerated computations, the
images are converted to the tensors.
To convert an image to a PyTorch tensor, we can take the following steps −
Import the required libraries. The required libraries are torch,
torchvision, Pillow.
Import the required libraries. The required libraries are torch,
torchvision, Pillow.
Read the image. The image must be either a PIL image or a numpy.ndarray (HxWxC) in the range [0, 255]. Here H, W, and C are the height, width, and the number of channels of the image.
Read the image. The image must be either a PIL image or a numpy.ndarray (HxWxC) in the range [0, 255]. Here H, W, and C are the height, width, and the number of channels of the image.
Define a transform to convert the image to tensor. We use transforms.ToTensor() to define a transform.
Define a transform to convert the image to tensor. We use transforms.ToTensor() to define a transform.
Convert the image to tensor using the above-defined transform.
Convert the image to tensor using the above-defined transform.
# Import the required libraries
import torch
from PIL import Image
import torchvision.transforms as transforms
# Read the image
image = Image.open('Penguins.jpg')
# Define a transform to convert the image to tensor
transform = transforms.ToTensor()
# Convert the image to PyTorch tensor
tensor = transform(image)
# print the converted image tensor
print(tensor)
tensor([[[0.4510, 0.4549, 0.4667, ..., 0.3333, 0.3333, 0.3333],
[0.4549, 0.4510, 0.4627, ..., 0.3373, 0.3373, 0.3373],
[0.4667, 0.4588, 0.4667, ..., 0.3451, 0.3451, 0.3412],
...,
[0.6706, 0.5020, 0.5490, ..., 0.4627, 0.4275, 0.3333],
[0.4196, 0.5922, 0.6784, ..., 0.4627, 0.4549, 0.3569],
[0.3569, 0.3529, 0.4784, ..., 0.3922, 0.4314, 0.3490]],
[[0.6824, 0.6863, 0.7020, ..., 0.6392, 0.6392, 0.6392],
[0.6863, 0.6824, 0.6980, ..., 0.6314, 0.6314, 0.6314],
[0.6980, 0.6902, 0.6980, ..., 0.6392, 0.6392, 0.6353],
...,
[0.7255, 0.5412, 0.5765, ..., 0.5255, 0.5020, 0.4157],
[0.4706, 0.6314, 0.7098, ..., 0.5255, 0.5294, 0.4392],
[0.4196, 0.3961, 0.5020, ..., 0.4510, 0.5059, 0.4314]],
[[0.8157, 0.8196, 0.8353, ..., 0.7922, 0.7922, 0.7922],
[0.8196, 0.8157, 0.8314, ..., 0.7882, 0.7882, 0.7882],
[0.8314, 0.8235, 0.8314, ..., 0.7961, 0.7961, 0.7922],
...,
[0.6235, 0.5059, 0.6157, ..., 0.4863, 0.4941, 0.4196],
[0.3922, 0.6000, 0.7176, ..., 0.4863, 0.5216, 0.4431],
[0.3686, 0.3647, 0.4863, ..., 0.4235, 0.4980, 0.4353]]])
In the above Python program, we have converted a PIL image to a tensor.
We can also read the image using OpenCV. The image read using OpenCV are of type numpy.ndarray. We can convert a numpy.ndarray to a tensor using transforms.ToTensor(). Have a look at the following example.
# Import the required libraries
import torch
import cv2
import torchvision.transforms as transforms
# Read the image
image = cv2.imread('Penguins.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Define a transform to convert the image to tensor
transform = transforms.ToTensor()
# Convert the image to PyTorch tensor
tensor = transform(image)
# Print the converted image tensor
print(tensor)
tensor([[[0.4510, 0.4549, 0.4667, ..., 0.3333, 0.3333, 0.3333],
[0.4549, 0.4510, 0.4627, ..., 0.3373, 0.3373, 0.3373],
[0.4667, 0.4588, 0.4667, ..., 0.3451, 0.3451, 0.3412],
...,
[0.6706, 0.5020, 0.5490, ..., 0.4627, 0.4275, 0.3333],
[0.4196, 0.5922, 0.6784, ..., 0.4627, 0.4549, 0.3569],
[0.3569, 0.3529, 0.4784, ..., 0.3922, 0.4314, 0.3490]],
[[0.6824, 0.6863, 0.7020, ..., 0.6392, 0.6392, 0.6392],
[0.6863, 0.6824, 0.6980, ..., 0.6314, 0.6314, 0.6314],
[0.6980, 0.6902, 0.6980, ..., 0.6392, 0.6392, 0.6353],
...,
[0.7255, 0.5412, 0.5765, ..., 0.5255, 0.5020, 0.4157],
[0.4706, 0.6314, 0.7098, ..., 0.5255, 0.5294, 0.4392],
[0.4196, 0.3961, 0.5020, ..., 0.4510, 0.5059, 0.4314]],
[[0.8157, 0.8196, 0.8353, ..., 0.7922, 0.7922, 0.7922],
[0.8196, 0.8157, 0.8314, ..., 0.7882, 0.7882, 0.7882],
[0.8314, 0.8235, 0.8314, ..., 0.7961, 0.7961, 0.7922],
...,
[0.6235, 0.5059, 0.6157, ..., 0.4863, 0.4941, 0.4196],
[0.3922, 0.6000, 0.7176, ..., 0.4863, 0.5216, 0.4431],
[0.3686, 0.3647, 0.4863, ..., 0.4235, 0.4980, 0.4353]]])
|
[
{
"code": null,
"e": 1397,
"s": 1062,
"text": "A PyTorch tensor is an n-dimensional array (matrix) containing elements of a single data type. A tensor is like a numpy array. The difference between\nnumpy arrays and PyTorch tensors is that the tensors utilize the GPUs to\naccelerate the numeric computations. For the accelerated computations, the\nimages are converted to the tensors."
},
{
"code": null,
"e": 1472,
"s": 1397,
"text": "To convert an image to a PyTorch tensor, we can take the following steps −"
},
{
"code": null,
"e": 1558,
"s": 1472,
"text": "Import the required libraries. The required libraries are torch,\ntorchvision, Pillow."
},
{
"code": null,
"e": 1644,
"s": 1558,
"text": "Import the required libraries. The required libraries are torch,\ntorchvision, Pillow."
},
{
"code": null,
"e": 1828,
"s": 1644,
"text": "Read the image. The image must be either a PIL image or a numpy.ndarray (HxWxC) in the range [0, 255]. Here H, W, and C are the height, width, and the number of channels of the image."
},
{
"code": null,
"e": 2012,
"s": 1828,
"text": "Read the image. The image must be either a PIL image or a numpy.ndarray (HxWxC) in the range [0, 255]. Here H, W, and C are the height, width, and the number of channels of the image."
},
{
"code": null,
"e": 2115,
"s": 2012,
"text": "Define a transform to convert the image to tensor. We use transforms.ToTensor() to define a transform."
},
{
"code": null,
"e": 2218,
"s": 2115,
"text": "Define a transform to convert the image to tensor. We use transforms.ToTensor() to define a transform."
},
{
"code": null,
"e": 2281,
"s": 2218,
"text": "Convert the image to tensor using the above-defined transform."
},
{
"code": null,
"e": 2344,
"s": 2281,
"text": "Convert the image to tensor using the above-defined transform."
},
{
"code": null,
"e": 2710,
"s": 2344,
"text": "# Import the required libraries\nimport torch\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\n# Read the image\nimage = Image.open('Penguins.jpg')\n\n# Define a transform to convert the image to tensor\ntransform = transforms.ToTensor()\n\n# Convert the image to PyTorch tensor\ntensor = transform(image)\n\n# print the converted image tensor\nprint(tensor)"
},
{
"code": null,
"e": 3910,
"s": 2710,
"text": "tensor([[[0.4510, 0.4549, 0.4667, ..., 0.3333, 0.3333, 0.3333],\n [0.4549, 0.4510, 0.4627, ..., 0.3373, 0.3373, 0.3373],\n [0.4667, 0.4588, 0.4667, ..., 0.3451, 0.3451, 0.3412],\n ...,\n [0.6706, 0.5020, 0.5490, ..., 0.4627, 0.4275, 0.3333],\n [0.4196, 0.5922, 0.6784, ..., 0.4627, 0.4549, 0.3569],\n [0.3569, 0.3529, 0.4784, ..., 0.3922, 0.4314, 0.3490]],\n [[0.6824, 0.6863, 0.7020, ..., 0.6392, 0.6392, 0.6392],\n [0.6863, 0.6824, 0.6980, ..., 0.6314, 0.6314, 0.6314],\n [0.6980, 0.6902, 0.6980, ..., 0.6392, 0.6392, 0.6353],\n ...,\n [0.7255, 0.5412, 0.5765, ..., 0.5255, 0.5020, 0.4157],\n [0.4706, 0.6314, 0.7098, ..., 0.5255, 0.5294, 0.4392],\n [0.4196, 0.3961, 0.5020, ..., 0.4510, 0.5059, 0.4314]],\n [[0.8157, 0.8196, 0.8353, ..., 0.7922, 0.7922, 0.7922],\n [0.8196, 0.8157, 0.8314, ..., 0.7882, 0.7882, 0.7882],\n [0.8314, 0.8235, 0.8314, ..., 0.7961, 0.7961, 0.7922],\n ...,\n [0.6235, 0.5059, 0.6157, ..., 0.4863, 0.4941, 0.4196],\n [0.3922, 0.6000, 0.7176, ..., 0.4863, 0.5216, 0.4431],\n [0.3686, 0.3647, 0.4863, ..., 0.4235, 0.4980, 0.4353]]])"
},
{
"code": null,
"e": 3982,
"s": 3910,
"text": "In the above Python program, we have converted a PIL image to a tensor."
},
{
"code": null,
"e": 4188,
"s": 3982,
"text": "We can also read the image using OpenCV. The image read using OpenCV are of type numpy.ndarray. We can convert a numpy.ndarray to a tensor using transforms.ToTensor(). Have a look at the following example."
},
{
"code": null,
"e": 4590,
"s": 4188,
"text": "# Import the required libraries\nimport torch\nimport cv2\nimport torchvision.transforms as transforms\n\n# Read the image\nimage = cv2.imread('Penguins.jpg')\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# Define a transform to convert the image to tensor\ntransform = transforms.ToTensor()\n\n# Convert the image to PyTorch tensor\ntensor = transform(image)\n\n# Print the converted image tensor\nprint(tensor)"
},
{
"code": null,
"e": 5790,
"s": 4590,
"text": "tensor([[[0.4510, 0.4549, 0.4667, ..., 0.3333, 0.3333, 0.3333],\n [0.4549, 0.4510, 0.4627, ..., 0.3373, 0.3373, 0.3373],\n [0.4667, 0.4588, 0.4667, ..., 0.3451, 0.3451, 0.3412],\n ...,\n [0.6706, 0.5020, 0.5490, ..., 0.4627, 0.4275, 0.3333],\n [0.4196, 0.5922, 0.6784, ..., 0.4627, 0.4549, 0.3569],\n [0.3569, 0.3529, 0.4784, ..., 0.3922, 0.4314, 0.3490]],\n [[0.6824, 0.6863, 0.7020, ..., 0.6392, 0.6392, 0.6392],\n [0.6863, 0.6824, 0.6980, ..., 0.6314, 0.6314, 0.6314],\n [0.6980, 0.6902, 0.6980, ..., 0.6392, 0.6392, 0.6353],\n ...,\n [0.7255, 0.5412, 0.5765, ..., 0.5255, 0.5020, 0.4157],\n [0.4706, 0.6314, 0.7098, ..., 0.5255, 0.5294, 0.4392],\n [0.4196, 0.3961, 0.5020, ..., 0.4510, 0.5059, 0.4314]],\n [[0.8157, 0.8196, 0.8353, ..., 0.7922, 0.7922, 0.7922],\n [0.8196, 0.8157, 0.8314, ..., 0.7882, 0.7882, 0.7882],\n [0.8314, 0.8235, 0.8314, ..., 0.7961, 0.7961, 0.7922],\n ...,\n [0.6235, 0.5059, 0.6157, ..., 0.4863, 0.4941, 0.4196],\n [0.3922, 0.6000, 0.7176, ..., 0.4863, 0.5216, 0.4431],\n [0.3686, 0.3647, 0.4863, ..., 0.4235, 0.4980, 0.4353]]])"
}
] |
Association Rule - GeeksforGeeks
|
14 Sep, 2018
Association rule mining finds interesting associations and relationships among large sets of data items. This rule shows how frequently a itemset occurs in a transaction. A typical example is Market Based Analysis.
Market Based Analysis is one of the key techniques used by large relations to show associations between items.It allows retailers to identify relationships between the items that people buy together frequently.
Given a set of transactions, we can find rules that will predict the occurrence of an item based on the occurrences of other items in the transaction.
Before we start defining the rule, let us first see the basic definitions.
Support Count() – Frequency of occurrence of a itemset.
Here ({Milk, Bread, Diaper})=2
Frequent Itemset – An itemset whose support is greater than or equal to minsup threshold.
Association Rule – An implication expression of the form X -> Y, where X and Y are any 2 itemsets.
Example: {Milk, Diaper}->{Beer}
Rule Evaluation Metrics –
Support(s) –The number of transactions that include items in the {X} and {Y} parts of the rule as a percentage of the total number of transaction.It is a measure of how frequently the collection of items occur together as a percentage of all transactions.
Support = (X+Y) total –It is interpreted as fraction of transactions that contain both X and Y.
Confidence(c) –It is the ratio of the no of transactions that includes all items in {B} as well as the no of transactions that includes all items in {A} to the no of transactions that includes all items in {A}.
Conf(X=>Y) = Supp(XY) Supp(X) –It measures how often each item in Y appears in transactions that contains items in X also.
Lift(l) –The lift of the rule X=>Y is the confidence of the rule divided by the expected confidence, assuming that the itemsets X and Y are independent of each other.The expected confidence is the confidence divided by the frequency of {Y}.
Lift(X=>Y) = Conf(X=>Y) Supp(Y) –Lift value near 1 indicates X and Y almost often appear together as expected, greater than 1 means they appear together more than expected and less than 1 means they appear less than expected.Greater lift values indicate stronger association.
Example – From the above table, {Milk, Diaper}=>{Beer}
s= ({Milk, Diaper, Beer}) |T|
= 2/5
= 0.4
c= (Milk, Diaper, Beer) (Milk, Diaper)
= 2/3
= 0.67
l= Supp({Milk, Diaper, Beer}) Supp({Milk, Diaper})*Supp({Beer})
= 0.4/(0.6*0.6)
= 1.11
The Association rule is very useful in analyzing datasets. The data is collected using bar-code scanners in supermarkets. Such databases consists of a large number of transaction records which list all items bought by a customer on a single purchase. So the manager could know if certain groups of items are consistently purchased together and use this data for adjusting store layouts, cross-selling, promotions based on statistics.
data mining
Machine Learning
Misc
Misc
Misc
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Elbow Method for optimal value of k in KMeans
ML | Underfitting and Overfitting
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n14 Sep, 2018"
},
{
"code": null,
"e": 24230,
"s": 24015,
"text": "Association rule mining finds interesting associations and relationships among large sets of data items. This rule shows how frequently a itemset occurs in a transaction. A typical example is Market Based Analysis."
},
{
"code": null,
"e": 24441,
"s": 24230,
"text": "Market Based Analysis is one of the key techniques used by large relations to show associations between items.It allows retailers to identify relationships between the items that people buy together frequently."
},
{
"code": null,
"e": 24592,
"s": 24441,
"text": "Given a set of transactions, we can find rules that will predict the occurrence of an item based on the occurrences of other items in the transaction."
},
{
"code": null,
"e": 24667,
"s": 24592,
"text": "Before we start defining the rule, let us first see the basic definitions."
},
{
"code": null,
"e": 24723,
"s": 24667,
"text": "Support Count() – Frequency of occurrence of a itemset."
},
{
"code": null,
"e": 24755,
"s": 24723,
"text": "Here ({Milk, Bread, Diaper})=2 "
},
{
"code": null,
"e": 24845,
"s": 24755,
"text": "Frequent Itemset – An itemset whose support is greater than or equal to minsup threshold."
},
{
"code": null,
"e": 24944,
"s": 24845,
"text": "Association Rule – An implication expression of the form X -> Y, where X and Y are any 2 itemsets."
},
{
"code": null,
"e": 24977,
"s": 24944,
"text": "Example: {Milk, Diaper}->{Beer} "
},
{
"code": null,
"e": 25003,
"s": 24977,
"text": "Rule Evaluation Metrics –"
},
{
"code": null,
"e": 25259,
"s": 25003,
"text": "Support(s) –The number of transactions that include items in the {X} and {Y} parts of the rule as a percentage of the total number of transaction.It is a measure of how frequently the collection of items occur together as a percentage of all transactions."
},
{
"code": null,
"e": 25356,
"s": 25259,
"text": "Support = (X+Y) total –It is interpreted as fraction of transactions that contain both X and Y."
},
{
"code": null,
"e": 25567,
"s": 25356,
"text": "Confidence(c) –It is the ratio of the no of transactions that includes all items in {B} as well as the no of transactions that includes all items in {A} to the no of transactions that includes all items in {A}."
},
{
"code": null,
"e": 25691,
"s": 25567,
"text": "Conf(X=>Y) = Supp(XY) Supp(X) –It measures how often each item in Y appears in transactions that contains items in X also."
},
{
"code": null,
"e": 25932,
"s": 25691,
"text": "Lift(l) –The lift of the rule X=>Y is the confidence of the rule divided by the expected confidence, assuming that the itemsets X and Y are independent of each other.The expected confidence is the confidence divided by the frequency of {Y}."
},
{
"code": null,
"e": 26209,
"s": 25932,
"text": "Lift(X=>Y) = Conf(X=>Y) Supp(Y) –Lift value near 1 indicates X and Y almost often appear together as expected, greater than 1 means they appear together more than expected and less than 1 means they appear less than expected.Greater lift values indicate stronger association."
},
{
"code": null,
"e": 26264,
"s": 26209,
"text": "Example – From the above table, {Milk, Diaper}=>{Beer}"
},
{
"code": null,
"e": 26451,
"s": 26264,
"text": "s= ({Milk, Diaper, Beer}) |T|\n= 2/5\n= 0.4\n\nc= (Milk, Diaper, Beer) (Milk, Diaper)\n= 2/3\n= 0.67\n\nl= Supp({Milk, Diaper, Beer}) Supp({Milk, Diaper})*Supp({Beer})\n= 0.4/(0.6*0.6)\n= 1.11 "
},
{
"code": null,
"e": 26885,
"s": 26451,
"text": "The Association rule is very useful in analyzing datasets. The data is collected using bar-code scanners in supermarkets. Such databases consists of a large number of transaction records which list all items bought by a customer on a single purchase. So the manager could know if certain groups of items are consistently purchased together and use this data for adjusting store layouts, cross-selling, promotions based on statistics."
},
{
"code": null,
"e": 26897,
"s": 26885,
"text": "data mining"
},
{
"code": null,
"e": 26914,
"s": 26897,
"text": "Machine Learning"
},
{
"code": null,
"e": 26919,
"s": 26914,
"text": "Misc"
},
{
"code": null,
"e": 26924,
"s": 26919,
"text": "Misc"
},
{
"code": null,
"e": 26929,
"s": 26924,
"text": "Misc"
},
{
"code": null,
"e": 26946,
"s": 26929,
"text": "Machine Learning"
},
{
"code": null,
"e": 27044,
"s": 26946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27053,
"s": 27044,
"text": "Comments"
},
{
"code": null,
"e": 27066,
"s": 27053,
"text": "Old Comments"
},
{
"code": null,
"e": 27089,
"s": 27066,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27145,
"s": 27089,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 27187,
"s": 27145,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 27233,
"s": 27187,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 27267,
"s": 27233,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 27308,
"s": 27267,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 27362,
"s": 27308,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 27423,
"s": 27362,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 27457,
"s": 27423,
"text": "How to write Regular Expressions?"
}
] |
Concatenate date and time from separate columns into a single column in MySQL
|
For this, concatenate both the date and time using CONCAT() function. Let us first create a table −
mysql> create table DemoTable
-> (
-> ShippingDate date,
-> ShippingTime time,
-> ShippingDatetime datetime
-> );
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ShippingDate,ShippingTime) values('2019-01-10', '10:40:20');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ShippingDate,ShippingTime) values('2019-06-14', '04:00:10');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+--------------+--------------+------------------+
| ShippingDate | ShippingTime | ShippingDatetime |
+--------------+--------------+------------------+
| 2019-01-10 | 10:40:20 | NULL |
| 2019-06-14 | 04:00:10 | NULL |
+--------------+--------------+------------------+
2 rows in set (0.00 sec)
Here is the query to concatenate date and time from separate columns into a single column in MySQL −
mysql> update DemoTable set ShippingDatetime=concat(ShippingDate,' ',ShippingTime);
Query OK, 2 rows affected (0.11 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
+--------------+--------------+---------------------+
| ShippingDate | ShippingTime | ShippingDatetime |
+--------------+--------------+---------------------+
| 2019-01-10 | 10:40:20 | 2019-01-10 10:40:20 |
| 2019-06-14 | 04:00:10 | 2019-06-14 04:00:10 |
+--------------+--------------+---------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "For this, concatenate both the date and time using CONCAT() function. Let us first create a table −"
},
{
"code": null,
"e": 1328,
"s": 1162,
"text": "mysql> create table DemoTable\n -> (\n -> ShippingDate date,\n -> ShippingTime time,\n -> ShippingDatetime datetime\n -> );\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1384,
"s": 1328,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1637,
"s": 1384,
"text": "mysql> insert into DemoTable(ShippingDate,ShippingTime) values('2019-01-10', '10:40:20');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable(ShippingDate,ShippingTime) values('2019-06-14', '04:00:10');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1697,
"s": 1637,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1728,
"s": 1697,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2059,
"s": 1728,
"text": "+--------------+--------------+------------------+\n| ShippingDate | ShippingTime | ShippingDatetime |\n+--------------+--------------+------------------+\n| 2019-01-10 | 10:40:20 | NULL |\n| 2019-06-14 | 04:00:10 | NULL |\n+--------------+--------------+------------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2160,
"s": 2059,
"text": "Here is the query to concatenate date and time from separate columns into a single column in MySQL −"
},
{
"code": null,
"e": 2320,
"s": 2160,
"text": "mysql> update DemoTable set ShippingDatetime=concat(ShippingDate,' ',ShippingTime);\nQuery OK, 2 rows affected (0.11 sec)\nRows matched: 2 Changed: 2 Warnings: 0"
},
{
"code": null,
"e": 2360,
"s": 2320,
"text": "Let us check table records once again −"
},
{
"code": null,
"e": 2391,
"s": 2360,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2740,
"s": 2391,
"text": "+--------------+--------------+---------------------+\n| ShippingDate | ShippingTime | ShippingDatetime |\n+--------------+--------------+---------------------+\n| 2019-01-10 | 10:40:20 | 2019-01-10 10:40:20 |\n| 2019-06-14 | 04:00:10 | 2019-06-14 04:00:10 |\n+--------------+--------------+---------------------+\n2 rows in set (0.00 sec)"
}
] |
Beating the world record in Tetris (GB) with genetics algorithm | by Duc Anh Bui | Towards Data Science
|
A couple of weeks ago, I found this awesome Game Boy emulator written in Python with support for AI/bots. I was very excited because now I could use my Machine Learning knowledge to create agents for games that haunted my childhood.
In this article, I’ll show how we can use a simple implementation of genetics algorithm and neural network to create an agent that can play the original Tetris on Game Boy extremely well and able to beat the world record which is set at 999999 and 523 lines according to TwinGalaxies.
Tetris, one of the best selling video game franchises, is a puzzle game where the main goal is to reach the highest possible score by clearing lines of Tetrominoes (yes, that’s what those pieces are called). The rules of the game are very simple, yet, it’s actually a NP-complete problem [1]. This means coding a rules based agent might not be the wisest approach and heuristics, such as a genetics algorithm, would be a better fit.
Genetics algorithms (GA) are a set of algorithms that are inspired by Darwin’s theory of evolution. These algorithms are used to solve optimisation problems. This means we can use GA to optimise the weights of a neural network (and they can do that pretty well too). I won’t go into what is a neural network in this article as there’re plenty of resources out there for it already, such as here.
The general idea is that we’ll create a neural network (NN) that will produce a score for each action the agent does. For every new tetromino, the agent will try all possible actions it could do and choose the action with the highest score. Using GA, we wish to optimise the network to converge to an optimal state via evolution.
In GA, we have a number of key concepts: fitness, elitism, crossover, and mutation.
Fitness is how we measure the ability of the network to correlate its output with how good the move is.
Elitism is when a percentage of top performing networks are brought over to the new generation.
Crossover is the process of creating a new network using the genes (weights) of two other networks.
Mutation involves randomly modifying the weights of a network.
The steps are as follows:
Generate a population of neural networks with randomised initial weights.For each network, play until the game is over.Calculate the fitness score of each network.Bring the top x performing networks over to the next set of the population (elitism).Randomly select 2 networks (parents) from the current population and perform crossover to produce a new network (children).Mutating the new network weights with a probability of x%.Continue until we reach the number of generations wanted.
Generate a population of neural networks with randomised initial weights.
For each network, play until the game is over.
Calculate the fitness score of each network.
Bring the top x performing networks over to the next set of the population (elitism).
Randomly select 2 networks (parents) from the current population and perform crossover to produce a new network (children).
Mutating the new network weights with a probability of x%.
Continue until we reach the number of generations wanted.
Like many other Machine Learning problems, the first step we need to do is collect data, or in this case, state data from the environment. Here’s a quick example that shows how to quickly initialise the environment.
The script itself is pretty self-explanatory. The developers have made it very easy to get a captured state of the game via tetris.game_area() . We can then create a sparse matrix where 0s are the blank tiles and 1s are the pieces:
area = np.asarray(tetris.game_area())area = (area != 47).astype(np.int16)
Using the matrix above, we can define a number of features as seen in [2]:
Aggregate HeightThis calculates a sum of all the column heights. In the example above, the sum would be 16.
Number of holesThe number of holes on the board. There are 6 holes in the board below:
Number of columns with at least one holeThat would be 5 in the example above.
BumpinessThe sum of absolute height differences between the columns. In the board below, it’s: 1 + 0 + 2 + 2 + 0 + 0 + 1 + 0 + 0 = 7
Row transitionsThe number of transitions from occupied to unoccupied tiles in each row summed. Each red dot in the picture below counts as one transition:
Column transitionsLike above but column wise.
Number of pitsA pit is defined as a column without any blocks. There are 3 pits in the board below:
Deepest wellA well is best explained via the image below. In this case, the deepest well has a height of 2.
Lines clearedThe number of lines cleared with the move.
Let’s implement these features using the matrix representation:
Now, let’s implement the algorithm:
First, we create a class for the Network
Our model is a simple network with an input layer with size 9 and an output layer with size 1. This simple network will allow us to interpret the weights easily and can be represented as follows:
I’m using PyTorch to create the network but feel free to use any other library or implement your own. Using this, we can create a Population class with crossover and mutation implemented:
For each new generation, we’ll bring over the top 20% networks.
For crossover, we sample parents with probability distribution generated from population fitnesses (the higher a Network fitness it the more likely it will be chosen). Each weight is chosen randomly with a 50/50 chance from either parent.
Afterwards, weights have 20% chance of being mutated with the addition of random Gaussian noise multiplied by a factor of 0.5.
The next step is to code some logic to play the game. First, let’s define some helper functions to move the blocks:
For each new piece, we’ll try all the possible moves with that piece. The number of turns and sideways moves we need to check is dependant on the block type. We can use these 3 functions to determine them:
Now we have all we needed to start simulating the networks. For each new piece, we pass the board information to get_score() to get the output of the network for each possible action. We choose the action with the highest output. Once the game is over, we return the fitness of the network which is the score of the game.
Due to the randomness of the game, the network won’t produce the same result for each run. We could evaluate multiple runs for each network via run_per_child to better approximate the network fitness.
As the agent gets better at the game, training time can get much longer. To speed training up, we stop the game once the agent has reached the maximum score (999999) and utilise multiprocessing. It’s simple enough to spawn multiple processes to evaluate networks parallelly like so:
And there you have it, we have implemented a genetic algorithm to create a simple agent that can play Tetris. Here’s an example run with the best model obtained after just 10 generations with a population size of 50:
Scores: [999999.0, 999999.0, 729892.0, 372490.0, 999999.0, 296117.0, 299328.0, 533870.0, 282609.0, 525193.0]Average: 603949.6Lines: [1031, 1002, 825, 415, 935, 393, 364, 622, 389, 582]Average: 655.8
There’re definitely some limitations to the agent due to its simplicity, however. As the agent only takes into account of present reward and disregards future rewards, it’s very likely to get into situations where placing a block gets lines cleared but worsen the board positioning. In addition, due to the small board size (18x10), if the agent gets multiple bad blocks in a row, it’s very likely to lose. These lead to a very high standard deviation between runs like the example above where, in the best run, the agent clear 1031 lines and 364 lines in the worst one.
And that’s it, I hope you had fun reading my approach to this project. Feel free to check out the full source code available at and make any improvements as you wish: https://github.com/uiucanh/tetris
References:
[1] Erik D. Demaine, Susan Hohenberger, David Liben-Nowell. Tetris is Hard, Even to Approximate.
[2] Renan Samuel da Silva, Rafael Stubs Parpinelli. Playing the Original Game Boy Tetris Using a Real Coded Genetic Algorithm
|
[
{
"code": null,
"e": 405,
"s": 172,
"text": "A couple of weeks ago, I found this awesome Game Boy emulator written in Python with support for AI/bots. I was very excited because now I could use my Machine Learning knowledge to create agents for games that haunted my childhood."
},
{
"code": null,
"e": 690,
"s": 405,
"text": "In this article, I’ll show how we can use a simple implementation of genetics algorithm and neural network to create an agent that can play the original Tetris on Game Boy extremely well and able to beat the world record which is set at 999999 and 523 lines according to TwinGalaxies."
},
{
"code": null,
"e": 1123,
"s": 690,
"text": "Tetris, one of the best selling video game franchises, is a puzzle game where the main goal is to reach the highest possible score by clearing lines of Tetrominoes (yes, that’s what those pieces are called). The rules of the game are very simple, yet, it’s actually a NP-complete problem [1]. This means coding a rules based agent might not be the wisest approach and heuristics, such as a genetics algorithm, would be a better fit."
},
{
"code": null,
"e": 1519,
"s": 1123,
"text": "Genetics algorithms (GA) are a set of algorithms that are inspired by Darwin’s theory of evolution. These algorithms are used to solve optimisation problems. This means we can use GA to optimise the weights of a neural network (and they can do that pretty well too). I won’t go into what is a neural network in this article as there’re plenty of resources out there for it already, such as here."
},
{
"code": null,
"e": 1849,
"s": 1519,
"text": "The general idea is that we’ll create a neural network (NN) that will produce a score for each action the agent does. For every new tetromino, the agent will try all possible actions it could do and choose the action with the highest score. Using GA, we wish to optimise the network to converge to an optimal state via evolution."
},
{
"code": null,
"e": 1933,
"s": 1849,
"text": "In GA, we have a number of key concepts: fitness, elitism, crossover, and mutation."
},
{
"code": null,
"e": 2037,
"s": 1933,
"text": "Fitness is how we measure the ability of the network to correlate its output with how good the move is."
},
{
"code": null,
"e": 2133,
"s": 2037,
"text": "Elitism is when a percentage of top performing networks are brought over to the new generation."
},
{
"code": null,
"e": 2233,
"s": 2133,
"text": "Crossover is the process of creating a new network using the genes (weights) of two other networks."
},
{
"code": null,
"e": 2296,
"s": 2233,
"text": "Mutation involves randomly modifying the weights of a network."
},
{
"code": null,
"e": 2322,
"s": 2296,
"text": "The steps are as follows:"
},
{
"code": null,
"e": 2809,
"s": 2322,
"text": "Generate a population of neural networks with randomised initial weights.For each network, play until the game is over.Calculate the fitness score of each network.Bring the top x performing networks over to the next set of the population (elitism).Randomly select 2 networks (parents) from the current population and perform crossover to produce a new network (children).Mutating the new network weights with a probability of x%.Continue until we reach the number of generations wanted."
},
{
"code": null,
"e": 2883,
"s": 2809,
"text": "Generate a population of neural networks with randomised initial weights."
},
{
"code": null,
"e": 2930,
"s": 2883,
"text": "For each network, play until the game is over."
},
{
"code": null,
"e": 2975,
"s": 2930,
"text": "Calculate the fitness score of each network."
},
{
"code": null,
"e": 3061,
"s": 2975,
"text": "Bring the top x performing networks over to the next set of the population (elitism)."
},
{
"code": null,
"e": 3185,
"s": 3061,
"text": "Randomly select 2 networks (parents) from the current population and perform crossover to produce a new network (children)."
},
{
"code": null,
"e": 3244,
"s": 3185,
"text": "Mutating the new network weights with a probability of x%."
},
{
"code": null,
"e": 3302,
"s": 3244,
"text": "Continue until we reach the number of generations wanted."
},
{
"code": null,
"e": 3518,
"s": 3302,
"text": "Like many other Machine Learning problems, the first step we need to do is collect data, or in this case, state data from the environment. Here’s a quick example that shows how to quickly initialise the environment."
},
{
"code": null,
"e": 3750,
"s": 3518,
"text": "The script itself is pretty self-explanatory. The developers have made it very easy to get a captured state of the game via tetris.game_area() . We can then create a sparse matrix where 0s are the blank tiles and 1s are the pieces:"
},
{
"code": null,
"e": 3824,
"s": 3750,
"text": "area = np.asarray(tetris.game_area())area = (area != 47).astype(np.int16)"
},
{
"code": null,
"e": 3899,
"s": 3824,
"text": "Using the matrix above, we can define a number of features as seen in [2]:"
},
{
"code": null,
"e": 4007,
"s": 3899,
"text": "Aggregate HeightThis calculates a sum of all the column heights. In the example above, the sum would be 16."
},
{
"code": null,
"e": 4094,
"s": 4007,
"text": "Number of holesThe number of holes on the board. There are 6 holes in the board below:"
},
{
"code": null,
"e": 4172,
"s": 4094,
"text": "Number of columns with at least one holeThat would be 5 in the example above."
},
{
"code": null,
"e": 4305,
"s": 4172,
"text": "BumpinessThe sum of absolute height differences between the columns. In the board below, it’s: 1 + 0 + 2 + 2 + 0 + 0 + 1 + 0 + 0 = 7"
},
{
"code": null,
"e": 4460,
"s": 4305,
"text": "Row transitionsThe number of transitions from occupied to unoccupied tiles in each row summed. Each red dot in the picture below counts as one transition:"
},
{
"code": null,
"e": 4506,
"s": 4460,
"text": "Column transitionsLike above but column wise."
},
{
"code": null,
"e": 4606,
"s": 4506,
"text": "Number of pitsA pit is defined as a column without any blocks. There are 3 pits in the board below:"
},
{
"code": null,
"e": 4714,
"s": 4606,
"text": "Deepest wellA well is best explained via the image below. In this case, the deepest well has a height of 2."
},
{
"code": null,
"e": 4770,
"s": 4714,
"text": "Lines clearedThe number of lines cleared with the move."
},
{
"code": null,
"e": 4834,
"s": 4770,
"text": "Let’s implement these features using the matrix representation:"
},
{
"code": null,
"e": 4870,
"s": 4834,
"text": "Now, let’s implement the algorithm:"
},
{
"code": null,
"e": 4911,
"s": 4870,
"text": "First, we create a class for the Network"
},
{
"code": null,
"e": 5107,
"s": 4911,
"text": "Our model is a simple network with an input layer with size 9 and an output layer with size 1. This simple network will allow us to interpret the weights easily and can be represented as follows:"
},
{
"code": null,
"e": 5295,
"s": 5107,
"text": "I’m using PyTorch to create the network but feel free to use any other library or implement your own. Using this, we can create a Population class with crossover and mutation implemented:"
},
{
"code": null,
"e": 5359,
"s": 5295,
"text": "For each new generation, we’ll bring over the top 20% networks."
},
{
"code": null,
"e": 5598,
"s": 5359,
"text": "For crossover, we sample parents with probability distribution generated from population fitnesses (the higher a Network fitness it the more likely it will be chosen). Each weight is chosen randomly with a 50/50 chance from either parent."
},
{
"code": null,
"e": 5725,
"s": 5598,
"text": "Afterwards, weights have 20% chance of being mutated with the addition of random Gaussian noise multiplied by a factor of 0.5."
},
{
"code": null,
"e": 5841,
"s": 5725,
"text": "The next step is to code some logic to play the game. First, let’s define some helper functions to move the blocks:"
},
{
"code": null,
"e": 6047,
"s": 5841,
"text": "For each new piece, we’ll try all the possible moves with that piece. The number of turns and sideways moves we need to check is dependant on the block type. We can use these 3 functions to determine them:"
},
{
"code": null,
"e": 6369,
"s": 6047,
"text": "Now we have all we needed to start simulating the networks. For each new piece, we pass the board information to get_score() to get the output of the network for each possible action. We choose the action with the highest output. Once the game is over, we return the fitness of the network which is the score of the game."
},
{
"code": null,
"e": 6570,
"s": 6369,
"text": "Due to the randomness of the game, the network won’t produce the same result for each run. We could evaluate multiple runs for each network via run_per_child to better approximate the network fitness."
},
{
"code": null,
"e": 6853,
"s": 6570,
"text": "As the agent gets better at the game, training time can get much longer. To speed training up, we stop the game once the agent has reached the maximum score (999999) and utilise multiprocessing. It’s simple enough to spawn multiple processes to evaluate networks parallelly like so:"
},
{
"code": null,
"e": 7070,
"s": 6853,
"text": "And there you have it, we have implemented a genetic algorithm to create a simple agent that can play Tetris. Here’s an example run with the best model obtained after just 10 generations with a population size of 50:"
},
{
"code": null,
"e": 7269,
"s": 7070,
"text": "Scores: [999999.0, 999999.0, 729892.0, 372490.0, 999999.0, 296117.0, 299328.0, 533870.0, 282609.0, 525193.0]Average: 603949.6Lines: [1031, 1002, 825, 415, 935, 393, 364, 622, 389, 582]Average: 655.8"
},
{
"code": null,
"e": 7840,
"s": 7269,
"text": "There’re definitely some limitations to the agent due to its simplicity, however. As the agent only takes into account of present reward and disregards future rewards, it’s very likely to get into situations where placing a block gets lines cleared but worsen the board positioning. In addition, due to the small board size (18x10), if the agent gets multiple bad blocks in a row, it’s very likely to lose. These lead to a very high standard deviation between runs like the example above where, in the best run, the agent clear 1031 lines and 364 lines in the worst one."
},
{
"code": null,
"e": 8041,
"s": 7840,
"text": "And that’s it, I hope you had fun reading my approach to this project. Feel free to check out the full source code available at and make any improvements as you wish: https://github.com/uiucanh/tetris"
},
{
"code": null,
"e": 8053,
"s": 8041,
"text": "References:"
},
{
"code": null,
"e": 8150,
"s": 8053,
"text": "[1] Erik D. Demaine, Susan Hohenberger, David Liben-Nowell. Tetris is Hard, Even to Approximate."
}
] |
T-SQL - ORDER BY Clause
|
The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default.
Following is the basic syntax of ORDER BY clause.
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example, which would sort the result in ascending order by NAME and SALARY.
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY
The above command will produce the following output.
ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
3 kaushik 23 Kota 2000.00
2 Khilan 25 Delhi 1500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
1 Ramesh 32 Ahmedabad 2000.00
Following command is an example, which would sort the result in descending order by NAME.
SELECT * FROM CUSTOMERS
ORDER BY NAME DESC
The above command will produce the following result −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
7 Muffy 24 Indore 10000.00
6 Komal 22 MP 4500.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
4 Chaitali 25 Mumbai 6500.00
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2247,
"s": 2060,
"text": "The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default."
},
{
"code": null,
"e": 2297,
"s": 2247,
"text": "Following is the basic syntax of ORDER BY clause."
},
{
"code": null,
"e": 2411,
"s": 2297,
"text": "SELECT column-list \nFROM table_name \n[WHERE condition] \n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n"
},
{
"code": null,
"e": 2555,
"s": 2411,
"text": "You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list."
},
{
"code": null,
"e": 2615,
"s": 2555,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 3040,
"s": 2615,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 3140,
"s": 3040,
"text": "Following command is an example, which would sort the result in ascending order by NAME and SALARY."
},
{
"code": null,
"e": 3191,
"s": 3140,
"text": "SELECT * FROM CUSTOMERS \n ORDER BY NAME, SALARY "
},
{
"code": null,
"e": 3244,
"s": 3191,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 3661,
"s": 3244,
"text": "ID NAME AGE ADDRESS SALARY \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n3 kaushik 23 Kota 2000.00 \n2 Khilan 25 Delhi 1500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n1 Ramesh 32 Ahmedabad 2000.00 \n"
},
{
"code": null,
"e": 3751,
"s": 3661,
"text": "Following command is an example, which would sort the result in descending order by NAME."
},
{
"code": null,
"e": 3798,
"s": 3751,
"text": "SELECT * FROM CUSTOMERS \n ORDER BY NAME DESC"
},
{
"code": null,
"e": 3852,
"s": 3798,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 4276,
"s": 3852,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00\n7 Muffy 24 Indore 10000.00 \n6 Komal 22 MP 4500.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00\n5 Hardik 27 Bhopal 8500.00\n4 Chaitali 25 Mumbai 6500.00 \n"
},
{
"code": null,
"e": 4309,
"s": 4276,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4324,
"s": 4309,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4359,
"s": 4324,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4374,
"s": 4359,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4409,
"s": 4374,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4424,
"s": 4409,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4457,
"s": 4424,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4471,
"s": 4457,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4506,
"s": 4471,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4521,
"s": 4506,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4556,
"s": 4521,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4570,
"s": 4556,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4577,
"s": 4570,
"text": " Print"
},
{
"code": null,
"e": 4588,
"s": 4577,
"text": " Add Notes"
}
] |
Machine Learning for Supply Chain Forecasting | by Nicolas Vandeput | Towards Data Science
|
The article below is an extract from my book Data Science for Supply Chain Forecast, available here. You can find my other publications here. I am also active on LinkedIn.
Supply chain practitioners usually use old-school statistics to predict demand. But with the recent rise of machine learning algorithms, we have new tools at our disposal that can easily achieve excellent performance in terms of forecast accuracy for a typical industrial demand dataset. These models will be able to learn many relationships that are beyond the ability of traditional statistical models. For example, how to add external information (such as the weather) to a forecast model.
Traditional statistical models use a predefined model to populate a forecast based on historical demand. The issue is that these models couldn’t adapt to historical demand. If you use a double exponential smoothing model to predict a seasonal product, it will fail to interpret the seasonal patterns. On the other hand, If you use a triple exponential smoothing model on a non-seasonal demand, it might overfit the noise of the demand and interpret it as a seasonality.
Machine learning is different: here, the algorithm (i.e., the machine) will learn relationships from a training dataset (i.e., our historical demand) and then be able to apply these relationships on new data. Whereas a traditional statistical model will use a predefined relationship (model) to forecast the demand, a machine learning algorithm will not assume a priori a particular relationship (like seasonality or a linear trend); it will learn these patterns directly from the historical demand.
For a machine learning algorithm to learn how to make predictions, we will have to show it both the inputs and the desired respective outputs. It will then automatically understand the relationships between these inputs and outputs.
Another critical difference between using machine learning and exponential smoothing models to forecast our demand is the fact that a machine learning algorithm will learn patterns from all our dataset. Exponential smoothing models will treat each item individually, independently of the others. A machine learning algorithm will learn patterns from all the dataset and will apply what works best to each product. One could improve the accuracy of an exponential smoothing model by increasing the length of each time series (i.e., providing more historical periods for each product). With machine learning, we will be able to increase the accuracy of our model by providing more products.
Welcome to the world of machine learning.
In order to make a forecast, the question we will ask the machine learning algorithm is the following:Based on the last n periods of demand, what will the demand be during the next period(s)?We will train the model by providing it the data with a specific layout:- n consecutive periods of demand as input.- the demand for the very next period(s) as output.Let’s see an example (with a quarterly forecast to simplify the table):
For our forecast problem, we will basically show our machine learning algorithm different extracts of our historical demand dataset as inputs and each time show what the very next demand observation was. In our example above, the algorithm will learn the relationship between the last four quarters of demand and the demand for the next quarter. The algorithm will learn that if we have 5, 15, 10 & 7 as the last four demand observations, the next demand observation will be 6, so that its prediction should be 6.
Most people will react to this idea with two very different thoughts. Either people will think that “it is simply impossible for a computer to look at the demand and make a prediction” or that “as of now, the humans have nothing left to do.” Both are wrong.
As we will see later, machine learning can generate very accurate predictions. And as the human controlling the machine, we still have to ask ourselves many questions:- Which data to feed the algorithm for it to understand the proper relationships.- Which machine learning algorithm to use (there are many different ones!).- Which parameters to use in our model. As you will see, each machine learning algorithm has some settings that we can tweak to improve its accuracy.
As always, there is no definitive one-size-fits-all answer. Experimentation will help you find what is best for your dataset.
Data preparationThe first step of any machine learning algorithm project is to clean and format the data correctly. In our case, we need to format the historical demand dataset to obtain one similar to the table shown above.
Naming convention During our data cleaning process, we will use the standard data science notation and call the inputs X and the outputs Y. Specifically, the datasets X_train & Y_train will contain all the historical demand we will use to train our algorithm (X_train being the inputs and Y_train the outputs). And the datasets X_test & Y_test will be used to test our model.
You can see on the table below an example of a typical historical demand dataset you should have at the beginning of a forecast project.
We now have to format this dataset to something similar to the first table. Let’s say for now that we want to predict the demand for a product during one quarter based on the demand observations of this product during the previous four quarters. We will populate the datasets X_train & Y_train by going through the different products we have and each time create a data sample with four consecutive quarters as X_train and the next quarter as Y_train. This way, the machine learning algorithm will learn the relationship(s) between one quarter of demand and the previous four.
You can see on the table below an illustration for the first iterations. To validate our model, we will keep Y3Q4 aside as a test set.
This means that our training set won’t go until Y3Q4 as it is kept for the test set: the last loop will be used as a final test.
Our X_train and Y_train datasets will look like the table below:
Remember that our algorithm will learn relationships in X_train to predict Y_train. So we could write that as X_train -> Y_train.
The final test will be given to our tool via these X_test & Y_test datasets:
These are each time the four latest demand quarters we know for each item just before Y3Q4 (i.e., Y2Q4 to Y3Q3). That means that our algorithm won’t see these relationships during its training phase as it will be tested on the accuracy it achieved on these specific prediction exercises. We will measure its accuracy on this test set and assume its accuracy when predicting future demand will be similar.
Dataset lengthIt is important for any machine learning exercise to pay attention to how much data is fed to the algorithm. The more, the better. On the other hand, the more periods we use to make a prediction (we will call this x_len), the less we will be able to loop through the dataset. Also, if we want to predict more periods at once (y_len), it will cost us a part of the dataset, as we need more data (Y_train is longer) to perform one loop in our dataset.
Typically, if we have a dataset with n periods, we will be able to make 1+n-x_len-y_len runs through it.
loops = 1 + n- x_len- y_len
It is a best practice to keep at the very least enough runs to loop through two full years so that 23 + x_len + y_len ≤ n. This means that the algorithm will have two full seasonal cycles to learn any possible relationships. If it had just one, you would be facing high risks of overfitting.
Do It YourselfData collectionThe dataset creation and cleaning is an essential part of any data science project. In order to illustrate all the models we will create in the next chapters, we will use the historical sales of cars in Norway from January 2007 to January 2017 as an example dataset. You can download this dataset here: www.supchains.com/downloadYou will get a csv file called norway_new_car_sales_by_make.csv. This dataset contains the sales of 65 car makers across 121 months. On average, a bit more than 140,000 new cars are sold in Norway per year so that the market can then be roughly estimated to be worth 4B$ if we assume that the price of a new car is, on average, around 30,000$ in Norway. This dataset is modest in terms of size, but it is big enough to be relevant to experiment with new models and ideas. Nevertheless, machine learning models might show better results on other bigger datasets.
Bring Your Own Data Set In the second part of the article, we will discuss how to apply a machine learning model to this example dataset. But what we are actually interested in is your own dataset. Do not waste any time and already start to gather some historical demand data so that you can test the following models on your own historical demand data as we progress through the different topics. It is recommended that you start with a dataset with at least three years of data (5 would be better) and more than a hundred different products. The bigger, the better.Training and test sets creationWe will make a first code to extract the data from this csv and format it with the dates as columns and the products as lines.
# Load the CSV file (should be in the same directory) data = pd.read_csv(“norway_new_car_sales_by_make.csv”) # Create a column “Period” with both the Year and the Month data[“Period”] = data[“Year”].astype(str) + “-” + data[“Month”].astype(str) # We use the datetime formatting to make sure format is consistent data[“Period”] = pd.to_datetime(data[“Period”]).dt.strftime(“%Y-%m”) # Create a pivot of the data to show the periods on columns and the car makers on rows df = pd.pivot_table(data=data, values=”Quantity”, index=”Make”, columns=”Period”, aggfunc=’sum’, fill_value=0) # Print data to Excel for reference df.to_excel(“Clean Demand.xlsx”)
Note that we print the results in an excel file for later reference. It is always good practice to visually check what the dataset looks like to be sure the code worked as intended.
You can also define a function to store these steps for later use.
def import_data(): data = pd.read_csv(“norway_new_car_sales_by_make.csv”) data[“Period”] = data[“Year”].astype(str) + “-” + data[“Month”].astype(str) data[“Period”] = pd.to_datetime(data[“Period”]).dt.strftime(“%Y-%m”) df = pd.pivot_table(data=data,values=”Quantity”,index=”Make”,columns=”Period”,aggfunc=’sum’,fill_value=0) return df
Now that we have our dataset with the proper formatting, we can create our training and test sets. For this purpose, we will create a function datasets that takes as inputs:
df our initial historical demand; x_len the number of months we will use to make a prediction; y_len the number of months we want to predict; y_test_len the number of months we leave as a final test;
and returns X_train, Y_train, X_test & Y_test.
def datasets(df, x_len=12, y_len=1, y_test_len=12):D = df.values periods = D.shape[1] # Training set creation: run through all the possible time windows loops = periods + 1 — x_len — y_len — y_test_len train = [] for col in range(loops): train.append(D[:,col:col+x_len+y_len]) train = np.vstack(train) X_train, Y_train = np.split(train,[x_len],axis=1) # Test set creation: unseen “future” data with the demand just before max_col_test = periods — x_len — y_len + 1 test = [] for col in range(loops,max_col_test): test.append(D[:,col:col+x_len+y_len]) test = np.vstack(test) X_test, Y_test = np.split(test,[x_len],axis=1) # this data formatting is needed if we only predict a single period if y_len == 1: Y_train = Y_train.ravel() Y_test = Y_test.ravel() return X_train, Y_train, X_test, Y_test
In our function, we have to use .ravel() on both Y_train and Y_test if we only want to predict one period at a time. array.ravel() reduces the dimension of a NumPy array to 1D. Our function always creates Y_train and Y_test as 2D arrays (i.e., arrays with rows and columns). If we only want to predict one period at a time, these arrays will then only have one column (and multiple rows). Unfortunately, the functions we will use later will need 1D arrays if we want to forecast only one period.
We can now easily call our new function datasets(df) as well as import_data().
import numpy as npimport pandas as pddf = import_data()X_train, Y_train, X_test, Y_test = datasets(df)
We now obtain the datasets we need to feed our machine learning algorithm (X_train & Y_train) and the datasets we need to test it (X_test & Y_test).
Note that we took y_test_len as 12 periods. That means we will test our algorithm over 12 different predictions (as we only predict one period at a time).Forecasting multiple periods at once You can change y_len if you want to forecast multiple periods at once. You need to pay attention to keep y_test_len ≥ y_len; otherwise, you won’t be able to test all the predictions of your algorithm.
As a first machine learning algorithm, we will use a decision tree. Decision trees are a class of machine learning algorithms that will create a map (a tree actually) of questions to make a prediction. We call these trees regression trees if we want them to predict a number or classification trees if we want them to predict a category or a label.
In order to make a prediction, the tree will start at its foundation with a first yes/no question; and based on the answer, it will continue asking new yes/no questions until it gets to a final prediction. Somehow you could see these trees like a big game of Guess Who? (the famous ’80s game): the model will ask multiple consecutive questions until it gets to a right answer.
In a decision tree, each question is called a node. For example, in the figure above, ‘Does the person have a big nose?’ is a node. Each possible final answer is called a leaf. In the example above, each leaf contains only one single person. But that is not mandatory. You could imagine that multiple people have a big mouth and a big nose. In such case, the leaf would contain multiple values.
The different pieces of information that a tree has at its disposal to split a node are called the features. For example, the tree we had on the figure above could split a node on the three features Mouth, Nose, and Glasses.
How does it work?To illustrate how our tree will grow, let’s take back our quarterly dummy dataset.
Based on this training dataset, a smart question to ask yourself to make a prediction is: Is the first demand observation > 7?
This is a smart question as you know that the answer (Yes/No) will provide an interesting indication of the behavior of the demand for the next quarter. If the answer is yes, the demand we try to predict is likely to be rather high (>8), and if the answer is no, then the demand we try to predict is likely to be low (≤7).
Here is an example of a bad question.
This does not help as this question does not separate our dataset into two different subsets (i.e., there is still a lot of variation inside each subset). If the answer to the question Is the third demand observation <6? is yes, we still have a range of demand going from 1 to 11, and if the answer is no, the range goes from 4 to 13. This question is simply not helpful in forecasting future demand.
Without going too much into details of the tree’s mathematical inner workings, the algorithm to grow our tree will, at each node, choose a question (i.e., a split) about one of the available features (i.e., the previous quarters) that will minimize the prediction error across the two new data subsets. The first algorithm proposed to create a decision tree was published in 1963 by Morgan and Sonquist in their paper “Problems in the Analysis of Survey Data and a Proposal.” There are many different algorithms on how to grow a decision tree (many were developed since the ‘60s). They all follow the objective of asking the most meaningful questions about the different features of a dataset in order to split it into different subsets until some criterion is reached.
ParametersIt’s important to realize that without a criterion to stop the growth of our tree, it will grow until each data observation (otherwise called sample) has its own leaf. This is a terrible idea as even though you will have perfect accuracy on your training set, you will not be able to replicate these results on new data. We will limit the growth of our tree based on some criterion. Let’s take a look at the most important ones (we are already using the scikit-learn naming convention).
Max depth Maximum amount of consecutive questions (nodes) the tree can ask.Min samples split Minimum amount of samples that are required in a node to trigger a new split. If you set this to 6, a node with only 5 observations left won’t be split further. Min samples leaf Minimum amount of observations that need to be in a leaf. This is a very important parameter. The closer this is to 0, the higher the risk of overfitting, as your tree will actually grow until it asks enough questions to treat each observation separately. Criterion This is the KPI that the algorithm will minimize (either MSE or MAE).
Of course, depending on your dataset, you might want to give different values to these parameters. We will discuss how to choose the best parameters in the following chapter.
Do It YourselfWe will use the scikit-learn Python library (www.scikit-learn.org) to grow our first tree. This is a well-known open-source library that is used all over the world by data scientists. It is built on top of NumPy so that it interacts easily with the rest of our code.
The first step is to call scikit-learn and create an instance of a regression tree. Once this is done, we have to train it based on our X_train and Y_train arrays.
from sklearn.tree import DecisionTreeRegressor # — Instantiate a Decision Tree Regressor tree = DecisionTreeRegressor(max_depth=5,min_samples_leaf=5) # — Fit the tree to the training data tree.fit(X_train,Y_train)
Note that we created a tree with a maximum depth of 5 (i.e., a maximum of five yes/no consecutive questions are asked to classify one point), where each tree leaf has at minimum 5 samples.
We now have a tree trained to our specific demand history. We can already measure its accuracy on the training dataset.
# Create a prediction based on our model Y_train_pred = tree.predict(X_train) # Compute the Mean Absolute Error of the model import numpy as npMAE_tree = np.mean(abs(Y_train — Y_train_pred))/np.mean(Y_train) # Print the results print(“Tree on train set MAE%:”,round(MAE_tree*100,1))
You should obtain an MAE of 15.1%. Now let’s measure the accuracy against the test set:
Y_test_pred = tree.predict(X_test) MAE_test = np.mean(abs(Y_test — Y_test_pred))/np.mean(Y_test) print(“Tree on test set MAE%:”,round(MAE_test*100,1))
We now obtain around 21.1%. This means that our regression tree is overfitted to the historical demand: we lost 6 points of MAE in the test set compared to the historical dataset.
There are many ways to improve this result further:- Optimize the tree parameters.- Use more advanced models (like a Forest, ETR, Extreme Gradient Boosting).- Optimize the input data.- Use external data.
All of these are explained in the book Data Science for Supply Chain Forecast (available on Amazon)
www.linkedin.com
Nicolas Vandeput is a supply chain data scientist specialized in demand forecasting and inventory optimization. He founded his consultancy company SupChains in 2016 and co-founded SKU Science — a fast, simple, and affordable demand forecasting platform — in 2018. Passionate about education, Nicolas is both an avid learner and enjoys teaching at universities: he has taught forecasting and inventory optimization to master students since 2014 in Brussels, Belgium. Since 2020, he is also teaching both subjects at CentraleSupelec, Paris, France. He published Data Science for Supply Chain Forecasting in 2018 (2nd edition in 2021) and Inventory Optimization: Models and Simulations in 2020.
|
[
{
"code": null,
"e": 343,
"s": 171,
"text": "The article below is an extract from my book Data Science for Supply Chain Forecast, available here. You can find my other publications here. I am also active on LinkedIn."
},
{
"code": null,
"e": 836,
"s": 343,
"text": "Supply chain practitioners usually use old-school statistics to predict demand. But with the recent rise of machine learning algorithms, we have new tools at our disposal that can easily achieve excellent performance in terms of forecast accuracy for a typical industrial demand dataset. These models will be able to learn many relationships that are beyond the ability of traditional statistical models. For example, how to add external information (such as the weather) to a forecast model."
},
{
"code": null,
"e": 1306,
"s": 836,
"text": "Traditional statistical models use a predefined model to populate a forecast based on historical demand. The issue is that these models couldn’t adapt to historical demand. If you use a double exponential smoothing model to predict a seasonal product, it will fail to interpret the seasonal patterns. On the other hand, If you use a triple exponential smoothing model on a non-seasonal demand, it might overfit the noise of the demand and interpret it as a seasonality."
},
{
"code": null,
"e": 1806,
"s": 1306,
"text": "Machine learning is different: here, the algorithm (i.e., the machine) will learn relationships from a training dataset (i.e., our historical demand) and then be able to apply these relationships on new data. Whereas a traditional statistical model will use a predefined relationship (model) to forecast the demand, a machine learning algorithm will not assume a priori a particular relationship (like seasonality or a linear trend); it will learn these patterns directly from the historical demand."
},
{
"code": null,
"e": 2039,
"s": 1806,
"text": "For a machine learning algorithm to learn how to make predictions, we will have to show it both the inputs and the desired respective outputs. It will then automatically understand the relationships between these inputs and outputs."
},
{
"code": null,
"e": 2728,
"s": 2039,
"text": "Another critical difference between using machine learning and exponential smoothing models to forecast our demand is the fact that a machine learning algorithm will learn patterns from all our dataset. Exponential smoothing models will treat each item individually, independently of the others. A machine learning algorithm will learn patterns from all the dataset and will apply what works best to each product. One could improve the accuracy of an exponential smoothing model by increasing the length of each time series (i.e., providing more historical periods for each product). With machine learning, we will be able to increase the accuracy of our model by providing more products."
},
{
"code": null,
"e": 2770,
"s": 2728,
"text": "Welcome to the world of machine learning."
},
{
"code": null,
"e": 3199,
"s": 2770,
"text": "In order to make a forecast, the question we will ask the machine learning algorithm is the following:Based on the last n periods of demand, what will the demand be during the next period(s)?We will train the model by providing it the data with a specific layout:- n consecutive periods of demand as input.- the demand for the very next period(s) as output.Let’s see an example (with a quarterly forecast to simplify the table):"
},
{
"code": null,
"e": 3713,
"s": 3199,
"text": "For our forecast problem, we will basically show our machine learning algorithm different extracts of our historical demand dataset as inputs and each time show what the very next demand observation was. In our example above, the algorithm will learn the relationship between the last four quarters of demand and the demand for the next quarter. The algorithm will learn that if we have 5, 15, 10 & 7 as the last four demand observations, the next demand observation will be 6, so that its prediction should be 6."
},
{
"code": null,
"e": 3971,
"s": 3713,
"text": "Most people will react to this idea with two very different thoughts. Either people will think that “it is simply impossible for a computer to look at the demand and make a prediction” or that “as of now, the humans have nothing left to do.” Both are wrong."
},
{
"code": null,
"e": 4444,
"s": 3971,
"text": "As we will see later, machine learning can generate very accurate predictions. And as the human controlling the machine, we still have to ask ourselves many questions:- Which data to feed the algorithm for it to understand the proper relationships.- Which machine learning algorithm to use (there are many different ones!).- Which parameters to use in our model. As you will see, each machine learning algorithm has some settings that we can tweak to improve its accuracy."
},
{
"code": null,
"e": 4570,
"s": 4444,
"text": "As always, there is no definitive one-size-fits-all answer. Experimentation will help you find what is best for your dataset."
},
{
"code": null,
"e": 4795,
"s": 4570,
"text": "Data preparationThe first step of any machine learning algorithm project is to clean and format the data correctly. In our case, we need to format the historical demand dataset to obtain one similar to the table shown above."
},
{
"code": null,
"e": 5171,
"s": 4795,
"text": "Naming convention During our data cleaning process, we will use the standard data science notation and call the inputs X and the outputs Y. Specifically, the datasets X_train & Y_train will contain all the historical demand we will use to train our algorithm (X_train being the inputs and Y_train the outputs). And the datasets X_test & Y_test will be used to test our model."
},
{
"code": null,
"e": 5308,
"s": 5171,
"text": "You can see on the table below an example of a typical historical demand dataset you should have at the beginning of a forecast project."
},
{
"code": null,
"e": 5885,
"s": 5308,
"text": "We now have to format this dataset to something similar to the first table. Let’s say for now that we want to predict the demand for a product during one quarter based on the demand observations of this product during the previous four quarters. We will populate the datasets X_train & Y_train by going through the different products we have and each time create a data sample with four consecutive quarters as X_train and the next quarter as Y_train. This way, the machine learning algorithm will learn the relationship(s) between one quarter of demand and the previous four."
},
{
"code": null,
"e": 6020,
"s": 5885,
"text": "You can see on the table below an illustration for the first iterations. To validate our model, we will keep Y3Q4 aside as a test set."
},
{
"code": null,
"e": 6149,
"s": 6020,
"text": "This means that our training set won’t go until Y3Q4 as it is kept for the test set: the last loop will be used as a final test."
},
{
"code": null,
"e": 6214,
"s": 6149,
"text": "Our X_train and Y_train datasets will look like the table below:"
},
{
"code": null,
"e": 6344,
"s": 6214,
"text": "Remember that our algorithm will learn relationships in X_train to predict Y_train. So we could write that as X_train -> Y_train."
},
{
"code": null,
"e": 6421,
"s": 6344,
"text": "The final test will be given to our tool via these X_test & Y_test datasets:"
},
{
"code": null,
"e": 6826,
"s": 6421,
"text": "These are each time the four latest demand quarters we know for each item just before Y3Q4 (i.e., Y2Q4 to Y3Q3). That means that our algorithm won’t see these relationships during its training phase as it will be tested on the accuracy it achieved on these specific prediction exercises. We will measure its accuracy on this test set and assume its accuracy when predicting future demand will be similar."
},
{
"code": null,
"e": 7290,
"s": 6826,
"text": "Dataset lengthIt is important for any machine learning exercise to pay attention to how much data is fed to the algorithm. The more, the better. On the other hand, the more periods we use to make a prediction (we will call this x_len), the less we will be able to loop through the dataset. Also, if we want to predict more periods at once (y_len), it will cost us a part of the dataset, as we need more data (Y_train is longer) to perform one loop in our dataset."
},
{
"code": null,
"e": 7395,
"s": 7290,
"text": "Typically, if we have a dataset with n periods, we will be able to make 1+n-x_len-y_len runs through it."
},
{
"code": null,
"e": 7423,
"s": 7395,
"text": "loops = 1 + n- x_len- y_len"
},
{
"code": null,
"e": 7715,
"s": 7423,
"text": "It is a best practice to keep at the very least enough runs to loop through two full years so that 23 + x_len + y_len ≤ n. This means that the algorithm will have two full seasonal cycles to learn any possible relationships. If it had just one, you would be facing high risks of overfitting."
},
{
"code": null,
"e": 8635,
"s": 7715,
"text": "Do It YourselfData collectionThe dataset creation and cleaning is an essential part of any data science project. In order to illustrate all the models we will create in the next chapters, we will use the historical sales of cars in Norway from January 2007 to January 2017 as an example dataset. You can download this dataset here: www.supchains.com/downloadYou will get a csv file called norway_new_car_sales_by_make.csv. This dataset contains the sales of 65 car makers across 121 months. On average, a bit more than 140,000 new cars are sold in Norway per year so that the market can then be roughly estimated to be worth 4B$ if we assume that the price of a new car is, on average, around 30,000$ in Norway. This dataset is modest in terms of size, but it is big enough to be relevant to experiment with new models and ideas. Nevertheless, machine learning models might show better results on other bigger datasets."
},
{
"code": null,
"e": 9360,
"s": 8635,
"text": "Bring Your Own Data Set In the second part of the article, we will discuss how to apply a machine learning model to this example dataset. But what we are actually interested in is your own dataset. Do not waste any time and already start to gather some historical demand data so that you can test the following models on your own historical demand data as we progress through the different topics. It is recommended that you start with a dataset with at least three years of data (5 would be better) and more than a hundred different products. The bigger, the better.Training and test sets creationWe will make a first code to extract the data from this csv and format it with the dates as columns and the products as lines."
},
{
"code": null,
"e": 10011,
"s": 9360,
"text": "# Load the CSV file (should be in the same directory) data = pd.read_csv(“norway_new_car_sales_by_make.csv”) # Create a column “Period” with both the Year and the Month data[“Period”] = data[“Year”].astype(str) + “-” + data[“Month”].astype(str) # We use the datetime formatting to make sure format is consistent data[“Period”] = pd.to_datetime(data[“Period”]).dt.strftime(“%Y-%m”) # Create a pivot of the data to show the periods on columns and the car makers on rows df = pd.pivot_table(data=data, values=”Quantity”, index=”Make”, columns=”Period”, aggfunc=’sum’, fill_value=0) # Print data to Excel for reference df.to_excel(“Clean Demand.xlsx”)"
},
{
"code": null,
"e": 10193,
"s": 10011,
"text": "Note that we print the results in an excel file for later reference. It is always good practice to visually check what the dataset looks like to be sure the code worked as intended."
},
{
"code": null,
"e": 10260,
"s": 10193,
"text": "You can also define a function to store these steps for later use."
},
{
"code": null,
"e": 10595,
"s": 10260,
"text": "def import_data(): data = pd.read_csv(“norway_new_car_sales_by_make.csv”) data[“Period”] = data[“Year”].astype(str) + “-” + data[“Month”].astype(str) data[“Period”] = pd.to_datetime(data[“Period”]).dt.strftime(“%Y-%m”) df = pd.pivot_table(data=data,values=”Quantity”,index=”Make”,columns=”Period”,aggfunc=’sum’,fill_value=0) return df"
},
{
"code": null,
"e": 10769,
"s": 10595,
"text": "Now that we have our dataset with the proper formatting, we can create our training and test sets. For this purpose, we will create a function datasets that takes as inputs:"
},
{
"code": null,
"e": 10969,
"s": 10769,
"text": "df our initial historical demand; x_len the number of months we will use to make a prediction; y_len the number of months we want to predict; y_test_len the number of months we leave as a final test;"
},
{
"code": null,
"e": 11016,
"s": 10969,
"text": "and returns X_train, Y_train, X_test & Y_test."
},
{
"code": null,
"e": 11815,
"s": 11016,
"text": "def datasets(df, x_len=12, y_len=1, y_test_len=12):D = df.values periods = D.shape[1] # Training set creation: run through all the possible time windows loops = periods + 1 — x_len — y_len — y_test_len train = [] for col in range(loops): train.append(D[:,col:col+x_len+y_len]) train = np.vstack(train) X_train, Y_train = np.split(train,[x_len],axis=1) # Test set creation: unseen “future” data with the demand just before max_col_test = periods — x_len — y_len + 1 test = [] for col in range(loops,max_col_test): test.append(D[:,col:col+x_len+y_len]) test = np.vstack(test) X_test, Y_test = np.split(test,[x_len],axis=1) # this data formatting is needed if we only predict a single period if y_len == 1: Y_train = Y_train.ravel() Y_test = Y_test.ravel() return X_train, Y_train, X_test, Y_test"
},
{
"code": null,
"e": 12312,
"s": 11815,
"text": "In our function, we have to use .ravel() on both Y_train and Y_test if we only want to predict one period at a time. array.ravel() reduces the dimension of a NumPy array to 1D. Our function always creates Y_train and Y_test as 2D arrays (i.e., arrays with rows and columns). If we only want to predict one period at a time, these arrays will then only have one column (and multiple rows). Unfortunately, the functions we will use later will need 1D arrays if we want to forecast only one period."
},
{
"code": null,
"e": 12391,
"s": 12312,
"text": "We can now easily call our new function datasets(df) as well as import_data()."
},
{
"code": null,
"e": 12494,
"s": 12391,
"text": "import numpy as npimport pandas as pddf = import_data()X_train, Y_train, X_test, Y_test = datasets(df)"
},
{
"code": null,
"e": 12643,
"s": 12494,
"text": "We now obtain the datasets we need to feed our machine learning algorithm (X_train & Y_train) and the datasets we need to test it (X_test & Y_test)."
},
{
"code": null,
"e": 13035,
"s": 12643,
"text": "Note that we took y_test_len as 12 periods. That means we will test our algorithm over 12 different predictions (as we only predict one period at a time).Forecasting multiple periods at once You can change y_len if you want to forecast multiple periods at once. You need to pay attention to keep y_test_len ≥ y_len; otherwise, you won’t be able to test all the predictions of your algorithm."
},
{
"code": null,
"e": 13384,
"s": 13035,
"text": "As a first machine learning algorithm, we will use a decision tree. Decision trees are a class of machine learning algorithms that will create a map (a tree actually) of questions to make a prediction. We call these trees regression trees if we want them to predict a number or classification trees if we want them to predict a category or a label."
},
{
"code": null,
"e": 13761,
"s": 13384,
"text": "In order to make a prediction, the tree will start at its foundation with a first yes/no question; and based on the answer, it will continue asking new yes/no questions until it gets to a final prediction. Somehow you could see these trees like a big game of Guess Who? (the famous ’80s game): the model will ask multiple consecutive questions until it gets to a right answer."
},
{
"code": null,
"e": 14156,
"s": 13761,
"text": "In a decision tree, each question is called a node. For example, in the figure above, ‘Does the person have a big nose?’ is a node. Each possible final answer is called a leaf. In the example above, each leaf contains only one single person. But that is not mandatory. You could imagine that multiple people have a big mouth and a big nose. In such case, the leaf would contain multiple values."
},
{
"code": null,
"e": 14381,
"s": 14156,
"text": "The different pieces of information that a tree has at its disposal to split a node are called the features. For example, the tree we had on the figure above could split a node on the three features Mouth, Nose, and Glasses."
},
{
"code": null,
"e": 14481,
"s": 14381,
"text": "How does it work?To illustrate how our tree will grow, let’s take back our quarterly dummy dataset."
},
{
"code": null,
"e": 14608,
"s": 14481,
"text": "Based on this training dataset, a smart question to ask yourself to make a prediction is: Is the first demand observation > 7?"
},
{
"code": null,
"e": 14931,
"s": 14608,
"text": "This is a smart question as you know that the answer (Yes/No) will provide an interesting indication of the behavior of the demand for the next quarter. If the answer is yes, the demand we try to predict is likely to be rather high (>8), and if the answer is no, then the demand we try to predict is likely to be low (≤7)."
},
{
"code": null,
"e": 14969,
"s": 14931,
"text": "Here is an example of a bad question."
},
{
"code": null,
"e": 15370,
"s": 14969,
"text": "This does not help as this question does not separate our dataset into two different subsets (i.e., there is still a lot of variation inside each subset). If the answer to the question Is the third demand observation <6? is yes, we still have a range of demand going from 1 to 11, and if the answer is no, the range goes from 4 to 13. This question is simply not helpful in forecasting future demand."
},
{
"code": null,
"e": 16140,
"s": 15370,
"text": "Without going too much into details of the tree’s mathematical inner workings, the algorithm to grow our tree will, at each node, choose a question (i.e., a split) about one of the available features (i.e., the previous quarters) that will minimize the prediction error across the two new data subsets. The first algorithm proposed to create a decision tree was published in 1963 by Morgan and Sonquist in their paper “Problems in the Analysis of Survey Data and a Proposal.” There are many different algorithms on how to grow a decision tree (many were developed since the ‘60s). They all follow the objective of asking the most meaningful questions about the different features of a dataset in order to split it into different subsets until some criterion is reached."
},
{
"code": null,
"e": 16637,
"s": 16140,
"text": "ParametersIt’s important to realize that without a criterion to stop the growth of our tree, it will grow until each data observation (otherwise called sample) has its own leaf. This is a terrible idea as even though you will have perfect accuracy on your training set, you will not be able to replicate these results on new data. We will limit the growth of our tree based on some criterion. Let’s take a look at the most important ones (we are already using the scikit-learn naming convention)."
},
{
"code": null,
"e": 17244,
"s": 16637,
"text": "Max depth Maximum amount of consecutive questions (nodes) the tree can ask.Min samples split Minimum amount of samples that are required in a node to trigger a new split. If you set this to 6, a node with only 5 observations left won’t be split further. Min samples leaf Minimum amount of observations that need to be in a leaf. This is a very important parameter. The closer this is to 0, the higher the risk of overfitting, as your tree will actually grow until it asks enough questions to treat each observation separately. Criterion This is the KPI that the algorithm will minimize (either MSE or MAE)."
},
{
"code": null,
"e": 17419,
"s": 17244,
"text": "Of course, depending on your dataset, you might want to give different values to these parameters. We will discuss how to choose the best parameters in the following chapter."
},
{
"code": null,
"e": 17700,
"s": 17419,
"text": "Do It YourselfWe will use the scikit-learn Python library (www.scikit-learn.org) to grow our first tree. This is a well-known open-source library that is used all over the world by data scientists. It is built on top of NumPy so that it interacts easily with the rest of our code."
},
{
"code": null,
"e": 17864,
"s": 17700,
"text": "The first step is to call scikit-learn and create an instance of a regression tree. Once this is done, we have to train it based on our X_train and Y_train arrays."
},
{
"code": null,
"e": 18080,
"s": 17864,
"text": "from sklearn.tree import DecisionTreeRegressor # — Instantiate a Decision Tree Regressor tree = DecisionTreeRegressor(max_depth=5,min_samples_leaf=5) # — Fit the tree to the training data tree.fit(X_train,Y_train)"
},
{
"code": null,
"e": 18269,
"s": 18080,
"text": "Note that we created a tree with a maximum depth of 5 (i.e., a maximum of five yes/no consecutive questions are asked to classify one point), where each tree leaf has at minimum 5 samples."
},
{
"code": null,
"e": 18389,
"s": 18269,
"text": "We now have a tree trained to our specific demand history. We can already measure its accuracy on the training dataset."
},
{
"code": null,
"e": 18674,
"s": 18389,
"text": "# Create a prediction based on our model Y_train_pred = tree.predict(X_train) # Compute the Mean Absolute Error of the model import numpy as npMAE_tree = np.mean(abs(Y_train — Y_train_pred))/np.mean(Y_train) # Print the results print(“Tree on train set MAE%:”,round(MAE_tree*100,1))"
},
{
"code": null,
"e": 18762,
"s": 18674,
"text": "You should obtain an MAE of 15.1%. Now let’s measure the accuracy against the test set:"
},
{
"code": null,
"e": 18913,
"s": 18762,
"text": "Y_test_pred = tree.predict(X_test) MAE_test = np.mean(abs(Y_test — Y_test_pred))/np.mean(Y_test) print(“Tree on test set MAE%:”,round(MAE_test*100,1))"
},
{
"code": null,
"e": 19093,
"s": 18913,
"text": "We now obtain around 21.1%. This means that our regression tree is overfitted to the historical demand: we lost 6 points of MAE in the test set compared to the historical dataset."
},
{
"code": null,
"e": 19297,
"s": 19093,
"text": "There are many ways to improve this result further:- Optimize the tree parameters.- Use more advanced models (like a Forest, ETR, Extreme Gradient Boosting).- Optimize the input data.- Use external data."
},
{
"code": null,
"e": 19397,
"s": 19297,
"text": "All of these are explained in the book Data Science for Supply Chain Forecast (available on Amazon)"
},
{
"code": null,
"e": 19414,
"s": 19397,
"text": "www.linkedin.com"
}
] |
How to update the image of a Tkinter Label widget?
|
We have used Label widget to group all the widgets in the application. A Label widget takes text and images in the constructor that sets the label with the position in the top-left corner of the window. However, to change or update the image associated with the Label, we can use a callable method where we provide the information of other images.
In the following example, we will create a button to update the Label image.
#Import the required library
from tkinter import*
from PIL import Image, ImageTk
#Create an instance of tkinter frame
win= Tk()
#Define geometry of the window
win.geometry("750x600")
win.title("Gallery")
#Define a Function to change to Image
def change_img():
img2=ImageTk.PhotoImage(Image.open("tutorialspoint.png"))
label.configure(image=img2)
label.image=img2
#Convert To PhotoImage
img1= ImageTk.PhotoImage(Image.open("logo.png"))
#Create a Label widget
label= Label(win,image= img1)
label.pack()
#Create a Button to handle the update Image event
button= Button(win, text= "Change", font= ('Helvetica 13 bold'),
command= change_img)
button.pack(pady=15)
win.bind("<Return>", change_img)
win.mainloop()
Running the example code will display a window with a Label Image and a button that helps to change the label image.
Now, just click the "Change" button to update the Label Image.
|
[
{
"code": null,
"e": 1410,
"s": 1062,
"text": "We have used Label widget to group all the widgets in the application. A Label widget takes text and images in the constructor that sets the label with the position in the top-left corner of the window. However, to change or update the image associated with the Label, we can use a callable method where we provide the information of other images."
},
{
"code": null,
"e": 1487,
"s": 1410,
"text": "In the following example, we will create a button to update the Label image."
},
{
"code": null,
"e": 2208,
"s": 1487,
"text": "#Import the required library\nfrom tkinter import*\nfrom PIL import Image, ImageTk\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Define geometry of the window\nwin.geometry(\"750x600\")\nwin.title(\"Gallery\")\n\n#Define a Function to change to Image\ndef change_img():\n img2=ImageTk.PhotoImage(Image.open(\"tutorialspoint.png\"))\n label.configure(image=img2)\n label.image=img2\n\n#Convert To PhotoImage\nimg1= ImageTk.PhotoImage(Image.open(\"logo.png\"))\n\n#Create a Label widget\nlabel= Label(win,image= img1)\nlabel.pack()\n\n#Create a Button to handle the update Image event\nbutton= Button(win, text= \"Change\", font= ('Helvetica 13 bold'),\ncommand= change_img)\nbutton.pack(pady=15)\nwin.bind(\"<Return>\", change_img)\nwin.mainloop()"
},
{
"code": null,
"e": 2325,
"s": 2208,
"text": "Running the example code will display a window with a Label Image and a button that helps to change the label image."
},
{
"code": null,
"e": 2388,
"s": 2325,
"text": "Now, just click the \"Change\" button to update the Label Image."
}
] |
Java Swing JTabbedPane Example - 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, we are going to create a simple Swing JTabbedPane, which allows the user to switch between a group of components by clicking on tabs.
We can see the tabbed pane in windows operating by opening the system properties like below.
As part this example I am going to create a simple Swing JTabbedPane like above.
package com.swing.examples;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TabbedPane extends JFrame {
JTabbedPane tabs;
CoursePanel cource;
SelectCoursePanel selectCourse;
TabbedPane() {
super("Tabbed Pane Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Setting the JTabbedPane Position and Layout as Wrap
tabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
cource = new CoursePanel();
selectCourse = new SelectCoursePanel();
// Adding user defined pannels to JTabbedPane
tabs.addTab("Cources", cource);
tabs.addTab("Select Course", selectCourse);
// Adding JPanels to JTabbedPane
tabs.addTab("Listing", new JPanel());
tabs.addTab("Comment", new JTextArea(10, 40));
tabs.addTab("Register", new JPanel());
tabs.addTab("Contact Us", new JPanel());
tabs.addTab("More..", new JPanel());
getContentPane().add(tabs);
}
}
/*Creating CoursePanel by extending JPanel*/
class CoursePanel extends JPanel {
JButton addCourse, clear;
CoursePanel() {
addCourse = new JButton("Add Course");
clear = new JButton("Clear");
setLayout(new FlowLayout());
add(addCourse);
add(clear);
}
}
/*Creating SelectCoursePanel by extending JPanel*/
class SelectCoursePanel extends JPanel {
JCheckBox java, swing, hibernate;
SelectCoursePanel() {
java = new JCheckBox("Java");
swing = new JCheckBox("Spring");
hibernate = new JCheckBox("Hibernate");
setLayout(new FlowLayout());
add(java);
add(swing);
add(hibernate);
}
}
class JTabbedPaneDemo {
public static void main(String args[]) throws Exception {
TabbedPane frame = new TabbedPane();
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Output :
On the above example the tabs wrapped based on the width of the panel. If we don’t want to wrap the tabs, it is possible to make it as scroll by changing the tab layout like below :
tabs = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
Output :
We can also change the JTabbedPane position by using TabPlacement like below.
tabs = new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.WRAP_TAB_LAYOUT);
Output :
Happy Learning 🙂
Java JColorChooser Example
Java Swing JLabel Example
Java Swing Login Example
Java Swing JSplitPane Example
Java Swing ProgressBar Example
Java Swing JTable Example
Java Swing Advanced JTable Example
Java Swing JMenu Example
Java Swing JToolBar Example
Java Swing JOptionPane Example
Java Swing JTree Example
How to create Java Smiley Swing
How to create Java Rainbow using Swing
Java Swing BorderFactory Example
Java Swing JList Example
Java JColorChooser Example
Java Swing JLabel Example
Java Swing Login Example
Java Swing JSplitPane Example
Java Swing ProgressBar Example
Java Swing JTable Example
Java Swing Advanced JTable Example
Java Swing JMenu Example
Java Swing JToolBar Example
Java Swing JOptionPane Example
Java Swing JTree Example
How to create Java Smiley Swing
How to create Java Rainbow using Swing
Java Swing BorderFactory Example
Java Swing JList Example
yashav
September 26, 2019 at 4:45 pm - Reply
Could not find or load main class TabbedPane is the error
yashav
September 26, 2019 at 4:45 pm - Reply
Could not find or load main class TabbedPane is the error
Could not find or load main class TabbedPane is the error
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"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": 550,
"s": 398,
"text": "In this tutorial, we are going to create a simple Swing JTabbedPane, which allows the user to switch between a group of components by clicking on tabs."
},
{
"code": null,
"e": 643,
"s": 550,
"text": "We can see the tabbed pane in windows operating by opening the system properties like below."
},
{
"code": null,
"e": 724,
"s": 643,
"text": "As part this example I am going to create a simple Swing JTabbedPane like above."
},
{
"code": null,
"e": 2677,
"s": 724,
"text": "package com.swing.examples;\n\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\nclass TabbedPane extends JFrame {\n JTabbedPane tabs;\n CoursePanel cource;\n SelectCoursePanel selectCourse;\n\n TabbedPane() {\n super(\"Tabbed Pane Example\");\n\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n // Setting the JTabbedPane Position and Layout as Wrap\n tabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);\n\n cource = new CoursePanel();\n selectCourse = new SelectCoursePanel();\n // Adding user defined pannels to JTabbedPane\n tabs.addTab(\"Cources\", cource);\n tabs.addTab(\"Select Course\", selectCourse);\n \n // Adding JPanels to JTabbedPane\n tabs.addTab(\"Listing\", new JPanel());\n tabs.addTab(\"Comment\", new JTextArea(10, 40));\n\n tabs.addTab(\"Register\", new JPanel());\n tabs.addTab(\"Contact Us\", new JPanel());\n\n tabs.addTab(\"More..\", new JPanel());\n\n getContentPane().add(tabs);\n }\n}\n\n/*Creating CoursePanel by extending JPanel*/\nclass CoursePanel extends JPanel {\n JButton addCourse, clear;\n\n CoursePanel() {\n addCourse = new JButton(\"Add Course\");\n clear = new JButton(\"Clear\");\n\n setLayout(new FlowLayout());\n\n add(addCourse);\n add(clear);\n }\n}\n/*Creating SelectCoursePanel by extending JPanel*/\nclass SelectCoursePanel extends JPanel {\n JCheckBox java, swing, hibernate;\n\n SelectCoursePanel() {\n java = new JCheckBox(\"Java\");\n swing = new JCheckBox(\"Spring\");\n hibernate = new JCheckBox(\"Hibernate\");\n\n setLayout(new FlowLayout());\n add(java);\n add(swing);\n add(hibernate);\n }\n}\n\nclass JTabbedPaneDemo {\n public static void main(String args[]) throws Exception {\n TabbedPane frame = new TabbedPane();\n frame.setSize(400, 400);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2686,
"s": 2677,
"text": "Output :"
},
{
"code": null,
"e": 2870,
"s": 2688,
"text": "On the above example the tabs wrapped based on the width of the panel. If we don’t want to wrap the tabs, it is possible to make it as scroll by changing the tab layout like below :"
},
{
"code": null,
"e": 2942,
"s": 2870,
"text": "tabs = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);\n"
},
{
"code": null,
"e": 2951,
"s": 2942,
"text": "Output :"
},
{
"code": null,
"e": 3029,
"s": 2951,
"text": "We can also change the JTabbedPane position by using TabPlacement like below."
},
{
"code": null,
"e": 3100,
"s": 3029,
"text": "tabs = new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.WRAP_TAB_LAYOUT);\n"
},
{
"code": null,
"e": 3109,
"s": 3100,
"text": "Output :"
},
{
"code": null,
"e": 3126,
"s": 3109,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3566,
"s": 3126,
"text": "\nJava JColorChooser Example\nJava Swing JLabel Example\nJava Swing Login Example\nJava Swing JSplitPane Example\nJava Swing ProgressBar Example\nJava Swing JTable Example\nJava Swing Advanced JTable Example\nJava Swing JMenu Example\nJava Swing JToolBar Example\nJava Swing JOptionPane Example\nJava Swing JTree Example\nHow to create Java Smiley Swing\nHow to create Java Rainbow using Swing\nJava Swing BorderFactory Example\nJava Swing JList Example\n"
},
{
"code": null,
"e": 3593,
"s": 3566,
"text": "Java JColorChooser Example"
},
{
"code": null,
"e": 3619,
"s": 3593,
"text": "Java Swing JLabel Example"
},
{
"code": null,
"e": 3644,
"s": 3619,
"text": "Java Swing Login Example"
},
{
"code": null,
"e": 3674,
"s": 3644,
"text": "Java Swing JSplitPane Example"
},
{
"code": null,
"e": 3705,
"s": 3674,
"text": "Java Swing ProgressBar Example"
},
{
"code": null,
"e": 3731,
"s": 3705,
"text": "Java Swing JTable Example"
},
{
"code": null,
"e": 3766,
"s": 3731,
"text": "Java Swing Advanced JTable Example"
},
{
"code": null,
"e": 3791,
"s": 3766,
"text": "Java Swing JMenu Example"
},
{
"code": null,
"e": 3819,
"s": 3791,
"text": "Java Swing JToolBar Example"
},
{
"code": null,
"e": 3850,
"s": 3819,
"text": "Java Swing JOptionPane Example"
},
{
"code": null,
"e": 3875,
"s": 3850,
"text": "Java Swing JTree Example"
},
{
"code": null,
"e": 3907,
"s": 3875,
"text": "How to create Java Smiley Swing"
},
{
"code": null,
"e": 3946,
"s": 3907,
"text": "How to create Java Rainbow using Swing"
},
{
"code": null,
"e": 3979,
"s": 3946,
"text": "Java Swing BorderFactory Example"
},
{
"code": null,
"e": 4004,
"s": 3979,
"text": "Java Swing JList Example"
},
{
"code": null,
"e": 4120,
"s": 4004,
"text": "\n\n\n\n\n\nyashav\nSeptember 26, 2019 at 4:45 pm - Reply \n\nCould not find or load main class TabbedPane is the error\n\n\n\n\n"
},
{
"code": null,
"e": 4234,
"s": 4120,
"text": "\n\n\n\n\nyashav\nSeptember 26, 2019 at 4:45 pm - Reply \n\nCould not find or load main class TabbedPane is the error\n\n\n\n"
},
{
"code": null,
"e": 4292,
"s": 4234,
"text": "Could not find or load main class TabbedPane is the error"
},
{
"code": null,
"e": 4298,
"s": 4296,
"text": "Δ"
},
{
"code": null,
"e": 4322,
"s": 4298,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 4350,
"s": 4322,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 4379,
"s": 4350,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 4414,
"s": 4379,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 4441,
"s": 4414,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 4468,
"s": 4441,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 4497,
"s": 4468,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 4523,
"s": 4497,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 4549,
"s": 4523,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 4585,
"s": 4549,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 4619,
"s": 4585,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 4645,
"s": 4619,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 4670,
"s": 4645,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 4704,
"s": 4670,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 4739,
"s": 4704,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 4763,
"s": 4739,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 4792,
"s": 4763,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 4824,
"s": 4792,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 4857,
"s": 4824,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 4882,
"s": 4857,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 4899,
"s": 4882,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 4927,
"s": 4899,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 4958,
"s": 4927,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 4990,
"s": 4958,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 5010,
"s": 4990,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 5030,
"s": 5010,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 5054,
"s": 5030,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 5084,
"s": 5054,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 5116,
"s": 5084,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 5152,
"s": 5116,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 5196,
"s": 5152,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 5228,
"s": 5196,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 5269,
"s": 5228,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 5306,
"s": 5269,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 5346,
"s": 5306,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 5375,
"s": 5346,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 5407,
"s": 5375,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 5427,
"s": 5407,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 5449,
"s": 5427,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 5479,
"s": 5449,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 5530,
"s": 5479,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 5566,
"s": 5530,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 5598,
"s": 5566,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 5633,
"s": 5598,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 5656,
"s": 5633,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 5703,
"s": 5656,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 5728,
"s": 5703,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5772,
"s": 5728,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
Python Tkinter – How to position a topLevel() widget relative to the root window?
|
In Tkinter, the toplevel widget is used to create a popup modal window. The popup window created by the toplevel window works similar to the default window of the tkinter application. It can have widgets such as text widget, button widget, canvas widget, frame, etc.
The size and position of the toplevel window can be decided by making it flexible throughout the screen. In the toplevel window, all the widgets are always placed on top of the other windows.
You can use root.winfo_x() and root.winfo_y() to get the position of the root window. Then, you can use the geometry method to position a toplevel widget relative to the root window. Making the toplevel widget relative to the root window prevents the overlapping of the two windows and separates them. Let's take an example to demonstrate how it works.
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x300")
win.title("Root Window")
# Create a toplevel window
top = Toplevel(win)
top.geometry("400x200")
# Create a Label in the toplevel widget
Label(top, text= "This is a Toplevel window", font="Calibri, 12").pack()
x = win.winfo_x()
y = win.winfo_y()
top.geometry("+%d+%d" %(x+200,y+200))
# Keep the toplevel window in front of the root window
top.wm_transient(win)
top.mainloop()
Running the above code will display a toplevel window apart from the main window.
|
[
{
"code": null,
"e": 1329,
"s": 1062,
"text": "In Tkinter, the toplevel widget is used to create a popup modal window. The popup window created by the toplevel window works similar to the default window of the tkinter application. It can have widgets such as text widget, button widget, canvas widget, frame, etc."
},
{
"code": null,
"e": 1521,
"s": 1329,
"text": "The size and position of the toplevel window can be decided by making it flexible throughout the screen. In the toplevel window, all the widgets are always placed on top of the other windows."
},
{
"code": null,
"e": 1874,
"s": 1521,
"text": "You can use root.winfo_x() and root.winfo_y() to get the position of the root window. Then, you can use the geometry method to position a toplevel widget relative to the root window. Making the toplevel widget relative to the root window prevents the overlapping of the two windows and separates them. Let's take an example to demonstrate how it works."
},
{
"code": null,
"e": 2421,
"s": 1874,
"text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x300\")\nwin.title(\"Root Window\")\n\n# Create a toplevel window\ntop = Toplevel(win)\ntop.geometry(\"400x200\")\n\n# Create a Label in the toplevel widget\nLabel(top, text= \"This is a Toplevel window\", font=\"Calibri, 12\").pack()\nx = win.winfo_x()\ny = win.winfo_y()\ntop.geometry(\"+%d+%d\" %(x+200,y+200))\n\n# Keep the toplevel window in front of the root window\ntop.wm_transient(win)\n\ntop.mainloop()"
},
{
"code": null,
"e": 2503,
"s": 2421,
"text": "Running the above code will display a toplevel window apart from the main window."
}
] |
Display MySQL Database, Table, and Column Information
|
The mysqlshow client can be used to see what databases exist, their tables, or a table's columns or indexes.It provides a command-line interface for several SQL SHOW statements.
The mysqlshow utility can be invoked as shown below −
shell> mysqlshow [options] [db_name [tbl_name [col_name]]]
Here,
If no database is provided, a list of database names are displayed.
If no database is provided, a list of database names are displayed.
If no table is given, all matching tables in the database are displayed.
If no table is given, all matching tables in the database are displayed.
If no column is provided, all matching columns and column types in the table are shown.
If no column is provided, all matching columns and column types in the table are shown.
The output displays the names of only those databases, tables, or columns for which the user has certain privileges.
The output displays the names of only those databases, tables, or columns for which the user has certain privileges.
mysqlshow supports the below options. These can be specified on the command line or in the [mysqlshow] and [client] groups of an option file.
--bind-address=ip_address
If a computer has multiple network interfaces, this option can be used to select which interface has to be used to connect to the MySQL server.
--character-sets-dir=dir_name
It is the directory where character sets are installed.
--compress, -C
It compresses all information that is sent between the client and the server if possible.
--count
It will show the number of rows per table. This can be slow for non-MyISAM tables.
--port=port_num, -P port_num
It is for TCP/IP connections, it tells about the port number to use.
--print-defaults
It prints the program name and all options that it gets from option files.
--user=user_name, -u user_name
It is the user name of the MySQL account that is used to connect to the server.
--verbose, -v
It is the verbose mode. It prints more information about what the program does. This option can be used multiple times to increase the amount of information.
--version, -V
It displays the version information and exits.
|
[
{
"code": null,
"e": 1240,
"s": 1062,
"text": "The mysqlshow client can be used to see what databases exist, their tables, or a table's columns or indexes.It provides a command-line interface for several SQL SHOW statements."
},
{
"code": null,
"e": 1294,
"s": 1240,
"text": "The mysqlshow utility can be invoked as shown below −"
},
{
"code": null,
"e": 1353,
"s": 1294,
"text": "shell> mysqlshow [options] [db_name [tbl_name [col_name]]]"
},
{
"code": null,
"e": 1359,
"s": 1353,
"text": "Here,"
},
{
"code": null,
"e": 1427,
"s": 1359,
"text": "If no database is provided, a list of database names are displayed."
},
{
"code": null,
"e": 1495,
"s": 1427,
"text": "If no database is provided, a list of database names are displayed."
},
{
"code": null,
"e": 1568,
"s": 1495,
"text": "If no table is given, all matching tables in the database are displayed."
},
{
"code": null,
"e": 1641,
"s": 1568,
"text": "If no table is given, all matching tables in the database are displayed."
},
{
"code": null,
"e": 1729,
"s": 1641,
"text": "If no column is provided, all matching columns and column types in the table are shown."
},
{
"code": null,
"e": 1817,
"s": 1729,
"text": "If no column is provided, all matching columns and column types in the table are shown."
},
{
"code": null,
"e": 1934,
"s": 1817,
"text": "The output displays the names of only those databases, tables, or columns for which the user has certain privileges."
},
{
"code": null,
"e": 2051,
"s": 1934,
"text": "The output displays the names of only those databases, tables, or columns for which the user has certain privileges."
},
{
"code": null,
"e": 2193,
"s": 2051,
"text": "mysqlshow supports the below options. These can be specified on the command line or in the [mysqlshow] and [client] groups of an option file."
},
{
"code": null,
"e": 2219,
"s": 2193,
"text": "--bind-address=ip_address"
},
{
"code": null,
"e": 2363,
"s": 2219,
"text": "If a computer has multiple network interfaces, this option can be used to select which interface has to be used to connect to the MySQL server."
},
{
"code": null,
"e": 2393,
"s": 2363,
"text": "--character-sets-dir=dir_name"
},
{
"code": null,
"e": 2449,
"s": 2393,
"text": "It is the directory where character sets are installed."
},
{
"code": null,
"e": 2464,
"s": 2449,
"text": "--compress, -C"
},
{
"code": null,
"e": 2554,
"s": 2464,
"text": "It compresses all information that is sent between the client and the server if possible."
},
{
"code": null,
"e": 2562,
"s": 2554,
"text": "--count"
},
{
"code": null,
"e": 2645,
"s": 2562,
"text": "It will show the number of rows per table. This can be slow for non-MyISAM tables."
},
{
"code": null,
"e": 2674,
"s": 2645,
"text": "--port=port_num, -P port_num"
},
{
"code": null,
"e": 2743,
"s": 2674,
"text": "It is for TCP/IP connections, it tells about the port number to use."
},
{
"code": null,
"e": 2760,
"s": 2743,
"text": "--print-defaults"
},
{
"code": null,
"e": 2835,
"s": 2760,
"text": "It prints the program name and all options that it gets from option files."
},
{
"code": null,
"e": 2866,
"s": 2835,
"text": "--user=user_name, -u user_name"
},
{
"code": null,
"e": 2946,
"s": 2866,
"text": "It is the user name of the MySQL account that is used to connect to the server."
},
{
"code": null,
"e": 2960,
"s": 2946,
"text": "--verbose, -v"
},
{
"code": null,
"e": 3118,
"s": 2960,
"text": "It is the verbose mode. It prints more information about what the program does. This option can be used multiple times to increase the amount of information."
},
{
"code": null,
"e": 3132,
"s": 3118,
"text": "--version, -V"
},
{
"code": null,
"e": 3179,
"s": 3132,
"text": "It displays the version information and exits."
}
] |
Environment Variables in Linux/Unix - GeeksforGeeks
|
30 Jul, 2021
Environment variables or ENVs basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment.
Scope of any variable is the region from which it can be accessed or over which it is defined. An environment variable in Linux can have global or local scope.
Global
A globally scoped ENV that is defined in a terminal can be accessed from anywhere in that particular environment which exists in the terminal. That means it can be used in all kind of scripts, programs or processes running in the environment bound by that terminal.
Local
A locally scoped ENV that is defined in a terminal cannot be accessed by any program or process running in the terminal. It can only be accessed by the terminal( in which it was defined) itself.
SYNTAX:
$NAME
NOTE: Both local and global environment variables are accessed in the same way.
SYNTAX:
$ echo $NAME
SYNTAX:
$ printenv //displays all the global ENVs
or
$ set //display all the ENVs(global as well as local)
or
$ env //display all the global ENVs
EXAMPLE:
To set a global ENV
$ export NAME=Value
or
$ set NAME=Value
EXAMPLE:
SYNTAX:
$ NAME=Value
EXAMPLE:
These variable are set and configured in ~/.bashrc, ~/.bash_profile, ~/.bash_login, ~/.profile files according to the requirement. These variables can be accessed by a particular user and persist through power offs.
Following steps can be followed to do so: Step 1: Open the terminal. Step 2:
$ sudo vi ~/.bashrc
Step 3:Enter password. Step 4:Add variable in the file opened.
export NAME=Value
Step 5: Save and close the file. Step 6:
$ source ~/.bashrc
EXAMPLE:
These variable are set and configured in /etc/environment, /etc/profile, /etc/profile.d/, /etc/bash.bashrc files according to the requirement.These variables can be accessed by any user and persist through power offs.
Following steps can be followed to do so: Step 1: Open the terminal. Step 2:
$ sudo -H vi /etc/environment
Step 3:Enter password. Step 4:Add variable in the file opened.
NAME=Value
Step 5: Save and close the file. Step 6: Logout and Login again.
SYNTAX:
$ unset NAME
or
$ NAME=''
EXAMPLE:
NOTE: To unset permanent ENVs, you need to re-edit the files and remove the lines that were added while defining them.
$USER: Gives current user's name.
$PATH: Gives search path for commands.
$PWD: Gives the path of present working directory.
$HOME: Gives path of home directory.
$HOSTNAME: Gives name of the host.
$LANG: Gives the default system language.
$EDITOR: Gives default file editor.
$UID: Gives user ID of current user.
$SHELL: Gives location of current user's shell program.
EXAMPLE:
rajeev0719singh
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
|
[
{
"code": null,
"e": 24172,
"s": 24144,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 24346,
"s": 24172,
"text": "Environment variables or ENVs basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment. "
},
{
"code": null,
"e": 24508,
"s": 24346,
"text": "Scope of any variable is the region from which it can be accessed or over which it is defined. An environment variable in Linux can have global or local scope. "
},
{
"code": null,
"e": 24515,
"s": 24508,
"text": "Global"
},
{
"code": null,
"e": 24782,
"s": 24515,
"text": "A globally scoped ENV that is defined in a terminal can be accessed from anywhere in that particular environment which exists in the terminal. That means it can be used in all kind of scripts, programs or processes running in the environment bound by that terminal. "
},
{
"code": null,
"e": 24788,
"s": 24782,
"text": "Local"
},
{
"code": null,
"e": 24984,
"s": 24788,
"text": "A locally scoped ENV that is defined in a terminal cannot be accessed by any program or process running in the terminal. It can only be accessed by the terminal( in which it was defined) itself. "
},
{
"code": null,
"e": 24994,
"s": 24984,
"text": "SYNTAX: "
},
{
"code": null,
"e": 25002,
"s": 24994,
"text": " $NAME "
},
{
"code": null,
"e": 25084,
"s": 25002,
"text": "NOTE: Both local and global environment variables are accessed in the same way. "
},
{
"code": null,
"e": 25094,
"s": 25084,
"text": "SYNTAX: "
},
{
"code": null,
"e": 25108,
"s": 25094,
"text": "$ echo $NAME "
},
{
"code": null,
"e": 25118,
"s": 25108,
"text": "SYNTAX: "
},
{
"code": null,
"e": 25256,
"s": 25118,
"text": "$ printenv //displays all the global ENVs\nor\n$ set //display all the ENVs(global as well as local)\nor\n$ env //display all the global ENVs"
},
{
"code": null,
"e": 25267,
"s": 25256,
"text": "EXAMPLE: "
},
{
"code": null,
"e": 25289,
"s": 25267,
"text": "To set a global ENV "
},
{
"code": null,
"e": 25329,
"s": 25289,
"text": "$ export NAME=Value\nor\n$ set NAME=Value"
},
{
"code": null,
"e": 25340,
"s": 25329,
"text": "EXAMPLE: "
},
{
"code": null,
"e": 25350,
"s": 25340,
"text": "SYNTAX: "
},
{
"code": null,
"e": 25363,
"s": 25350,
"text": "$ NAME=Value"
},
{
"code": null,
"e": 25374,
"s": 25363,
"text": "EXAMPLE: "
},
{
"code": null,
"e": 25591,
"s": 25374,
"text": "These variable are set and configured in ~/.bashrc, ~/.bash_profile, ~/.bash_login, ~/.profile files according to the requirement. These variables can be accessed by a particular user and persist through power offs. "
},
{
"code": null,
"e": 25669,
"s": 25591,
"text": "Following steps can be followed to do so: Step 1: Open the terminal. Step 2: "
},
{
"code": null,
"e": 25689,
"s": 25669,
"text": "$ sudo vi ~/.bashrc"
},
{
"code": null,
"e": 25754,
"s": 25689,
"text": "Step 3:Enter password. Step 4:Add variable in the file opened. "
},
{
"code": null,
"e": 25772,
"s": 25754,
"text": "export NAME=Value"
},
{
"code": null,
"e": 25815,
"s": 25772,
"text": "Step 5: Save and close the file. Step 6: "
},
{
"code": null,
"e": 25835,
"s": 25815,
"text": "$ source ~/.bashrc "
},
{
"code": null,
"e": 25846,
"s": 25835,
"text": "EXAMPLE: "
},
{
"code": null,
"e": 26065,
"s": 25846,
"text": "These variable are set and configured in /etc/environment, /etc/profile, /etc/profile.d/, /etc/bash.bashrc files according to the requirement.These variables can be accessed by any user and persist through power offs. "
},
{
"code": null,
"e": 26143,
"s": 26065,
"text": "Following steps can be followed to do so: Step 1: Open the terminal. Step 2: "
},
{
"code": null,
"e": 26173,
"s": 26143,
"text": "$ sudo -H vi /etc/environment"
},
{
"code": null,
"e": 26238,
"s": 26173,
"text": "Step 3:Enter password. Step 4:Add variable in the file opened. "
},
{
"code": null,
"e": 26249,
"s": 26238,
"text": "NAME=Value"
},
{
"code": null,
"e": 26315,
"s": 26249,
"text": "Step 5: Save and close the file. Step 6: Logout and Login again. "
},
{
"code": null,
"e": 26325,
"s": 26315,
"text": "SYNTAX: "
},
{
"code": null,
"e": 26351,
"s": 26325,
"text": "$ unset NAME\nor\n$ NAME=''"
},
{
"code": null,
"e": 26362,
"s": 26351,
"text": "EXAMPLE: "
},
{
"code": null,
"e": 26483,
"s": 26362,
"text": "NOTE: To unset permanent ENVs, you need to re-edit the files and remove the lines that were added while defining them. "
},
{
"code": null,
"e": 26850,
"s": 26483,
"text": "$USER: Gives current user's name.\n$PATH: Gives search path for commands.\n$PWD: Gives the path of present working directory.\n$HOME: Gives path of home directory.\n$HOSTNAME: Gives name of the host.\n$LANG: Gives the default system language.\n$EDITOR: Gives default file editor.\n$UID: Gives user ID of current user.\n$SHELL: Gives location of current user's shell program."
},
{
"code": null,
"e": 26861,
"s": 26850,
"text": "EXAMPLE: "
},
{
"code": null,
"e": 26879,
"s": 26863,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 26893,
"s": 26879,
"text": "linux-command"
},
{
"code": null,
"e": 26904,
"s": 26893,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27002,
"s": 26904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27040,
"s": 27002,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27075,
"s": 27040,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 27110,
"s": 27075,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27146,
"s": 27110,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27184,
"s": 27146,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27222,
"s": 27184,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27257,
"s": 27222,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 27293,
"s": 27257,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27330,
"s": 27293,
"text": "touch command in Linux with Examples"
}
] |
Min number of operations to reduce N to 0 by subtracting any digits from N
|
02 Sep, 2021
Given a number N, the task is to find the minimum number of operations required to reduce the number N to zero by subtracting the given number by any digit present in it.
Examples:
Input: N = 4 Output: 1 Explanation: Here 4 is the only digit present hence 4 – 4 = 0 and only one operation is required.
Input: N = 17 Output: 3 Explanation: The given integer is 17 and the steps of reduction are: 17 -> 17 – 7 = 10 10 -> 10 – 1 = 9 9 -> 9 – 9 = 0. Hence 3 operations are required.
Approach: This problem can be solved using Dynamic Programming. For any given number N, traverse each digit in N and recursively check by subtracting each digit one by one until N reduces to 0. But performing recursion will make the time complexity of the approach exponential.Therefore, the idea is use an array(say dp[]) of size (N + 1) such that dp[i] will store the minimum number of operations needed to reduce i to 0.
For every digit x in the number N, the recurrence relation used is given by:
dp[i] = min(dp[i], dp[i-x] + 1), where dp[i] will store the minimum number of operations needed to reduce i to 0.
We will use Bottom-Up Approach to fill the array dp[] from 0 to N and then dp[N] will give the minimum number of operations for N.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nint reduceZero(int N){ // Initialise dp[] to steps vector<int> dp(N + 1, 1e9); dp[0] = 0; // Iterate for all elements for (int i = 0; i <= N; i++) { // For each digit in number i for (char c : to_string(i)) { // Either select the number // or do not select it dp[i] = min(dp[i], dp[i - (c - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Codeint main(){ // Given Number int N = 25; // Function Call cout << reduceZero(N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nstatic int reduceZero(int N){ // Initialise dp[] to steps int []dp = new int[N + 1]; for (int i = 0; i <= N; i++) dp[i] = (int) 1e9; dp[0] = 0; // Iterate for all elements for (int i = 0; i <= N; i++) { // For each digit in number i for (char c : String.valueOf(i).toCharArray()) { // Either select the number // or do not select it dp[i] = Math.min(dp[i], dp[i - (c - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Codepublic static void main(String[] args){ // Given Number int N = 25; // Function Call System.out.print(reduceZero(N));}} // This code is contributed by amal kumar choubey
# Python3 program for the above approach # Function to reduce an integer N# to Zero in minimum operations by# removing digits from Ndef reduceZero(N): # Initialise dp[] to steps dp = [1e9 for i in range(N + 1)] dp[0] = 0 # Iterate for all elements for i in range(N + 1): # For each digit in number i for c in str(i): # Either select the number # or do not select it dp[i] = min(dp[i], dp[i - (ord(c) - 48)] + 1) # dp[N] will give minimum # step for N return dp[N] # Driver CodeN = 25 # Function Callprint(reduceZero(N)) # This code is contributed by Sanjit_Prasad
// C# program for the above approachusing System;class GFG{ // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nstatic int reduceZero(int N){ // Initialise []dp to steps int []dp = new int[N + 1]; for (int i = 0; i <= N; i++) dp[i] = (int) 1e9; dp[0] = 0; // Iterate for all elements for (int i = 0; i <= N; i++) { // For each digit in number i foreach (char c in String.Join("", i).ToCharArray()) { // Either select the number // or do not select it dp[i] = Math.Min(dp[i], dp[i - (c - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Codepublic static void Main(String[] args){ // Given Number int N = 25; // Function Call Console.Write(reduceZero(N));}} // This code is contributed by amal kumar choubey
<script> // Javascript program for the above approach // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nfunction reduceZero(N){ // Initialise dp[] to steps var dp = Array(N + 1).fill(1000000000); dp[0] = 0; // Iterate for all elements for (var i = 0; i <= N; i++) { // For each digit in number i for (var j =0; j< i.toString().length; j++) { // Either select the number // or do not select it dp[i] = Math.min(dp[i], dp[i - (i.toString()[j] - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Code // Given Numbervar N = 25; // Function Calldocument.write( reduceZero(N)); </script>
5
Time Complexity: O(N) Auxiliary Space: O(N)
Amal Kumar Choubey
Sanjit_Prasad
rrrtnx
sweetyty
number-digits
number-theory
Competitive Programming
Dynamic Programming
Mathematical
Recursion
number-theory
Dynamic Programming
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
Algorithm Library | C++ Magicians STL Algorithm
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 225,
"s": 54,
"text": "Given a number N, the task is to find the minimum number of operations required to reduce the number N to zero by subtracting the given number by any digit present in it."
},
{
"code": null,
"e": 236,
"s": 225,
"text": "Examples: "
},
{
"code": null,
"e": 357,
"s": 236,
"text": "Input: N = 4 Output: 1 Explanation: Here 4 is the only digit present hence 4 – 4 = 0 and only one operation is required."
},
{
"code": null,
"e": 535,
"s": 357,
"text": "Input: N = 17 Output: 3 Explanation: The given integer is 17 and the steps of reduction are: 17 -> 17 – 7 = 10 10 -> 10 – 1 = 9 9 -> 9 – 9 = 0. Hence 3 operations are required. "
},
{
"code": null,
"e": 960,
"s": 535,
"text": "Approach: This problem can be solved using Dynamic Programming. For any given number N, traverse each digit in N and recursively check by subtracting each digit one by one until N reduces to 0. But performing recursion will make the time complexity of the approach exponential.Therefore, the idea is use an array(say dp[]) of size (N + 1) such that dp[i] will store the minimum number of operations needed to reduce i to 0. "
},
{
"code": null,
"e": 1039,
"s": 960,
"text": "For every digit x in the number N, the recurrence relation used is given by: "
},
{
"code": null,
"e": 1155,
"s": 1039,
"text": "dp[i] = min(dp[i], dp[i-x] + 1), where dp[i] will store the minimum number of operations needed to reduce i to 0. "
},
{
"code": null,
"e": 1286,
"s": 1155,
"text": "We will use Bottom-Up Approach to fill the array dp[] from 0 to N and then dp[N] will give the minimum number of operations for N."
},
{
"code": null,
"e": 1339,
"s": 1286,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1343,
"s": 1339,
"text": "C++"
},
{
"code": null,
"e": 1348,
"s": 1343,
"text": "Java"
},
{
"code": null,
"e": 1356,
"s": 1348,
"text": "Python3"
},
{
"code": null,
"e": 1359,
"s": 1356,
"text": "C#"
},
{
"code": null,
"e": 1370,
"s": 1359,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nint reduceZero(int N){ // Initialise dp[] to steps vector<int> dp(N + 1, 1e9); dp[0] = 0; // Iterate for all elements for (int i = 0; i <= N; i++) { // For each digit in number i for (char c : to_string(i)) { // Either select the number // or do not select it dp[i] = min(dp[i], dp[i - (c - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Codeint main(){ // Given Number int N = 25; // Function Call cout << reduceZero(N); return 0;}",
"e": 2166,
"s": 1370,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nstatic int reduceZero(int N){ // Initialise dp[] to steps int []dp = new int[N + 1]; for (int i = 0; i <= N; i++) dp[i] = (int) 1e9; dp[0] = 0; // Iterate for all elements for (int i = 0; i <= N; i++) { // For each digit in number i for (char c : String.valueOf(i).toCharArray()) { // Either select the number // or do not select it dp[i] = Math.min(dp[i], dp[i - (c - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Codepublic static void main(String[] args){ // Given Number int N = 25; // Function Call System.out.print(reduceZero(N));}} // This code is contributed by amal kumar choubey",
"e": 3099,
"s": 2166,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to reduce an integer N# to Zero in minimum operations by# removing digits from Ndef reduceZero(N): # Initialise dp[] to steps dp = [1e9 for i in range(N + 1)] dp[0] = 0 # Iterate for all elements for i in range(N + 1): # For each digit in number i for c in str(i): # Either select the number # or do not select it dp[i] = min(dp[i], dp[i - (ord(c) - 48)] + 1) # dp[N] will give minimum # step for N return dp[N] # Driver CodeN = 25 # Function Callprint(reduceZero(N)) # This code is contributed by Sanjit_Prasad",
"e": 3787,
"s": 3099,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nstatic int reduceZero(int N){ // Initialise []dp to steps int []dp = new int[N + 1]; for (int i = 0; i <= N; i++) dp[i] = (int) 1e9; dp[0] = 0; // Iterate for all elements for (int i = 0; i <= N; i++) { // For each digit in number i foreach (char c in String.Join(\"\", i).ToCharArray()) { // Either select the number // or do not select it dp[i] = Math.Min(dp[i], dp[i - (c - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Codepublic static void Main(String[] args){ // Given Number int N = 25; // Function Call Console.Write(reduceZero(N));}} // This code is contributed by amal kumar choubey",
"e": 4715,
"s": 3787,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to reduce an integer N// to Zero in minimum operations by// removing digits from Nfunction reduceZero(N){ // Initialise dp[] to steps var dp = Array(N + 1).fill(1000000000); dp[0] = 0; // Iterate for all elements for (var i = 0; i <= N; i++) { // For each digit in number i for (var j =0; j< i.toString().length; j++) { // Either select the number // or do not select it dp[i] = Math.min(dp[i], dp[i - (i.toString()[j] - '0')] + 1); } } // dp[N] will give minimum // step for N return dp[N];} // Driver Code // Given Numbervar N = 25; // Function Calldocument.write( reduceZero(N)); </script>",
"e": 5516,
"s": 4715,
"text": null
},
{
"code": null,
"e": 5518,
"s": 5516,
"text": "5"
},
{
"code": null,
"e": 5565,
"s": 5520,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 5584,
"s": 5565,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 5598,
"s": 5584,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 5605,
"s": 5598,
"text": "rrrtnx"
},
{
"code": null,
"e": 5614,
"s": 5605,
"text": "sweetyty"
},
{
"code": null,
"e": 5628,
"s": 5614,
"text": "number-digits"
},
{
"code": null,
"e": 5642,
"s": 5628,
"text": "number-theory"
},
{
"code": null,
"e": 5666,
"s": 5642,
"text": "Competitive Programming"
},
{
"code": null,
"e": 5686,
"s": 5666,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5699,
"s": 5686,
"text": "Mathematical"
},
{
"code": null,
"e": 5709,
"s": 5699,
"text": "Recursion"
},
{
"code": null,
"e": 5723,
"s": 5709,
"text": "number-theory"
},
{
"code": null,
"e": 5743,
"s": 5723,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5756,
"s": 5743,
"text": "Mathematical"
},
{
"code": null,
"e": 5766,
"s": 5756,
"text": "Recursion"
},
{
"code": null,
"e": 5864,
"s": 5766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5891,
"s": 5864,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 5969,
"s": 5891,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 6007,
"s": 5969,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 6066,
"s": 6007,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 6114,
"s": 6066,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 6146,
"s": 6114,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 6176,
"s": 6146,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6205,
"s": 6176,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 6239,
"s": 6205,
"text": "Longest Common Subsequence | DP-4"
}
] |
p5.js | value() Function
|
21 Jun, 2021
The value() function is an inbuilt function which is used to set or return the value of the element.This function requires p5.dom library. So add the following line in the head section of the index.html file.
javascript
<script language="javascript" type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:
value()
or
value( value )
Parameters: This function accepts single parameter value which holds the value in number or string format.Return Value: This function returns the value of the element.Below examples illustrate the value() function in p5.js:Example 1: This example uses value() function to display the value as output.
javascript
// Gets the valuevar input_val; function setup() { // Canvas size 400*400 createCanvas(400, 200); // Set background color background('green'); // Create an input element with its value input_val = createInput('Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(30, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); // Set margin property input_val.style('margin-left', '50px');} function mousePressed() { // Display the input value print(input_val.value());}
Output:
Example 2: This example uses value() function to set the value of an element.
javascript
// Set the input valuevar input_val; function setup() { // Canvas size 400*400 createCanvas(400, 200); // Set background color background('green'); // Create an input element with its value input_val = createInput('Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(30, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); // Set margin property input_val.style('margin-left', '50px');} function mousePressed() { // Change input value input_val.value('A computer science portal');}
Output:
Before Click on the Element:
After Click on the Element:
abhishek0719kadiyan
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 239,
"s": 28,
"text": "The value() function is an inbuilt function which is used to set or return the value of the element.This function requires p5.dom library. So add the following line in the head section of the index.html file. "
},
{
"code": null,
"e": 250,
"s": 239,
"text": "javascript"
},
{
"code": "<script language=\"javascript\" type=\"text/javascript\" src=\"path/to/p5.dom.js\"></script>",
"e": 340,
"s": 250,
"text": null
},
{
"code": null,
"e": 350,
"s": 340,
"text": "Syntax: "
},
{
"code": null,
"e": 358,
"s": 350,
"text": "value()"
},
{
"code": null,
"e": 363,
"s": 358,
"text": "or "
},
{
"code": null,
"e": 378,
"s": 363,
"text": "value( value )"
},
{
"code": null,
"e": 681,
"s": 378,
"text": "Parameters: This function accepts single parameter value which holds the value in number or string format.Return Value: This function returns the value of the element.Below examples illustrate the value() function in p5.js:Example 1: This example uses value() function to display the value as output. "
},
{
"code": null,
"e": 692,
"s": 681,
"text": "javascript"
},
{
"code": "// Gets the valuevar input_val; function setup() { // Canvas size 400*400 createCanvas(400, 200); // Set background color background('green'); // Create an input element with its value input_val = createInput('Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(30, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); // Set margin property input_val.style('margin-left', '50px');} function mousePressed() { // Display the input value print(input_val.value());}",
"e": 1350,
"s": 692,
"text": null
},
{
"code": null,
"e": 1360,
"s": 1350,
"text": "Output: "
},
{
"code": null,
"e": 1440,
"s": 1360,
"text": "Example 2: This example uses value() function to set the value of an element. "
},
{
"code": null,
"e": 1451,
"s": 1440,
"text": "javascript"
},
{
"code": "// Set the input valuevar input_val; function setup() { // Canvas size 400*400 createCanvas(400, 200); // Set background color background('green'); // Create an input element with its value input_val = createInput('Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(30, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); // Set margin property input_val.style('margin-left', '50px');} function mousePressed() { // Change input value input_val.value('A computer science portal');}",
"e": 2129,
"s": 1451,
"text": null
},
{
"code": null,
"e": 2139,
"s": 2129,
"text": "Output: "
},
{
"code": null,
"e": 2170,
"s": 2139,
"text": "Before Click on the Element: "
},
{
"code": null,
"e": 2200,
"s": 2170,
"text": "After Click on the Element: "
},
{
"code": null,
"e": 2222,
"s": 2202,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 2239,
"s": 2222,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 2250,
"s": 2239,
"text": "JavaScript"
},
{
"code": null,
"e": 2267,
"s": 2250,
"text": "Web Technologies"
},
{
"code": null,
"e": 2365,
"s": 2267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2426,
"s": 2365,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2498,
"s": 2426,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2538,
"s": 2498,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2579,
"s": 2538,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2625,
"s": 2579,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2687,
"s": 2625,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2748,
"s": 2687,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2798,
"s": 2748,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2841,
"s": 2798,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Kotlin - Quick Guide
|
Kotlin is a new open source programming language like Java, JavaScript, etc. It is a high level strongly statically typed language that combines functional and technical part in a same place. Currently, Kotlin targets Java and JavaScript. It runs on JVM.
Kotlin is influenced by other programming languages such as Java, Scala, Groovy, Gosu, etc. The syntax of Kotlin may not be exactly similar to JAVA, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world.
Following are some of the advantages of using Kotlin for your application development.
Easy Language − Kotlin is a functional language and very easy to learn. The syntax is pretty much similar to Java, hence it is very easy to remember. Kotlin is more expressive, which makes your code more readable and understandable.
Concise − Kotlin is based on JVM and it is a functional language. Thus, it reduce lots of boiler plate code used in other programming languages.
Runtime and Performance − Better performance and small runtime.
Interoperability − Kotlin is mature enough to build an interoperable application in a less complex manner.
Brand New − Kotlin is a brand new language that gives developers a fresh start. It is not a replacement of Java, though it is developed over JVM. It is accepted as the first official language of android development. Kotlin can be defined as - Kotlin = JAVA + extra updated new features.
Following are some of the disadvantages of Kotlin.
Namespace declaration − Kotlin allows developers to declare the functions at the top level. However, whenever the same function is declared in many places of your application, then it is hard to understand which function is being called.
No Static Declaration − Kotlin does not have usual static handling modifier like Java, which can cause some problem to the conventional Java developer.
However, if you still want to use Kotlin offline in your local system, then you need to execute the following steps to configure your local workspace.
Step 1 − Java 8 installation.
Kotlin runs on JVM, hence. it is really necessary to use JDK 8 for your local Kotlin development. Please refer to the official website of oracle to download and install JDK 8 or an above version. You might have to set the environment variable for JAVA such that it can work properly. To verify your installation in Windows operating system, hit “java –version” in the command prompt and as an output it will show you the java version installed in your system.
Step 2 − IDE installation.
There are a number of IDE available over the internet. You can use any of your choice. You can find the download link of different IDE in the following table.
It is always recommended to use the recent software version to drag out maximum facility from it.
Step 3 − Configuring Eclipse.
Open Eclipse and go to “Eclipse Market Place”. You will find the following screen.
Search for Kotlin in the search box and install the same in your local system. It might take some time depending on the internet speed. You may have to restart your Eclipse, once it is successfully installed.
Step 4 − Kotlin Project.
Once Eclipse is successfully restarted and Kotlin is installed, you will be able to create a Kotlin project on the fly. Go to File → New → Others and select “Kotlin project” from the list.
Once the project setup is done, you can create a Kotlin file under “SRC” folder. Left-click on the “Src” folder and hit “new”. You will get an option for Kotlin file, otherwise you may have to search from the “others”. Once the new file is created, your project directory will be look like the following.
Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file.
fun main(args: Array<String>) {
println("Hello, World!")
}
Run it as a Kotlin application and see the output in the console as shown in the following screenshot. For better understanding and availability, we will be using our coding ground tool.
Hello, World!
Kotlin is a programming language and has its own architecture to allocate memory and produce a quality output to the end user. Following are the different scenarios where Kotlin compiler will work differently, whenever it is targeting different other kind of languages such as Java and JavaScript.
Kotlin compiler creates a byte code and that byte code can run on the JVM, which is exactly equal to the byte code generated by the Java .class file. Whenever two byte coded file runs on the JVM, they can communicate with each other and this is how an interoperable feature is established in Kotlin for Java.
Whenever Kotlin targets JavaScript, the Kotlin compiler converts the .kt file into ES5.1 and generates a compatible code for JavaScript. Kotlin compiler is capable of creating platform basis compatible codes via LLVM.
In this chapter, we will learn about the basic data types available in Kotlin programming language.
The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not allow internal conversion of different data types. Following table lists different variable lengths for different numbers.
In the following example, we will see how Kotlin works with different data types. Please enter the following set of code in our coding ground.
fun main(args: Array<String>) {
val a: Int = 10000
val d: Double = 100.00
val f: Float = 100.00f
val l: Long = 1000000004
val s: Short = 10
val b: Byte = 1
println("Your Int Value is "+a);
println("Your Double Value is "+d);
println("Your Float Value is "+f);
println("Your Long Value is "+l);
println("Your Short Value is "+s);
println("Your Byte Value is "+b);
}
When you run the above piece of code in the coding ground, it will generate the following output in the web console.
Your Int Value is 10000
Your Double Value is 100.0
Your Float Value is 100.0
Your Long Value is 1000000004
Your Short Value is 10
Your Byte Value is 1
Kotlin represents character using char. Character should be declared in a single quote like ‘c’. Please enter the following code in our coding ground and see how Kotlin interprets the character variable. Character variable cannot be declared like number variables. Kotlin variable can be declared in two ways - one using “var” and another using “val”.
fun main(args: Array<String>) {
val letter: Char // defining a variable
letter = 'A' // Assigning a value to it
println("$letter")
}
The above piece of code will yield the following output in the browser output window.
A
Boolean is very simple like other programming languages. We have only two values for Boolean – either true or false. In the following example, we will see how Kotlin interprets Boolean.
fun main(args: Array<String>) {
val letter: Boolean // defining a variable
letter = true // Assinging a value to it
println("Your character value is "+"$letter")
}
The above piece of code will yield the following output in the browser.
Your character value is true
Strings are character arrays. Like Java, they are immutable in nature. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. In the following example, we will make use of these strings.
fun main(args: Array<String>) {
var rawString :String = "I am Raw String!"
val escapedString : String = "I am escaped String!\n"
println("Hello!"+escapedString)
println("Hey!!"+rawString)
}
The above example of escaped String allows to provide extra line space after the first print statement. Following will be the output in the browser.
Hello!I am escaped String!
Hey!!I am Raw String!
Arrays are a collection of homogeneous data. Like Java, Kotlin supports arrays of different data types. In the following example, we will make use of different arrays.
fun main(args: Array<String>) {
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Hey!! I am array Example"+numbers[2])
}
The above piece of code yields the following output. The indexing of the array is similar to other programming languages. Here, we are searching for a second index, whose value is “3”.
Hey!! I am array Example3
Collection is a very important part of the data structure, which makes the software development easy for engineers. Kotlin has two types of collection - one is immutable collection (which means lists, maps and sets that cannot be editable) and another is mutable collection (this type of collection is editable). It is very important to keep in mind the type of collection used in your application, as Kotlin system does not represent any specific difference in them.
fun main(args: Array<String>) {
val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //mutable List
val readOnlyView: List<Int> = numbers // immutable list
println("my mutable list--"+numbers) // prints "[1, 2, 3]"
numbers.add(4)
println("my mutable list after addition --"+numbers) // prints "[1, 2, 3, 4]"
println(readOnlyView)
readOnlyView.clear() // ⇒ does not compile
// gives error
}
The above piece of code will yield the following output in the browser. It gives an error when we try to clear the mutable list of collection.
main.kt:9:18: error: unresolved reference: clear
readOnlyView.clear() // -> does not compile
^
In collection, Kotlin provides some useful methods such as first(), last(), filter(), etc. All these methods are self-descriptive and easy to implement. Moreover, Kotlin follows the same structure such as Java while implementing collection. You are free to implement any collection of your choice such as Map and Set.
In the following example, we have implemented Map and Set using different built-in methods.
fun main(args: Array<String>) {
val items = listOf(1, 2, 3, 4)
println("First Element of our list----"+items.first())
println("Last Element of our list----"+items.last())
println("Even Numbers of our List----"+items.
filter { it % 2 = = 0 }) // returns [2, 4]
val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)
println(readWriteMap["foo"]) // prints "1"
val strings = hashSetOf("a", "b", "c", "c")
println("My Set Values are"+strings)
}
The above piece of code yields the following output in the browser.
First Element of our list----1
Last Element of our list----4
Even Numbers of our List----[2, 4]
1
My Set Values are[a, b, c]
Ranges is another unique characteristic of Kotlin. Like Haskell, it provides an operator that helps you iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..).
In the following example, we will see how Kotlin interprets this range operator.
fun main(args: Array<String>) {
val i:Int = 2
for (j in 1..4)
print(j) // prints "1234"
if (i in 1..10) { // equivalent of 1 < = i && i < = 10
println("we found your number --"+i)
}
}
The above piece of code yields the following output in the browser.
1234we found your number --2
In the previous chapter we have learned about different types of data types available in Kotlin system. In this chapter, we will discuss different types of control flow mechanism available in the Kotlin.
Kotlin is a functional language hence like every functional language in Kotlin “if” is an expression, it is not a keyword. The expression “if” will return a value whenever necessary. Like other programming language, “if-else” block is used as an initial conditional checking operator. In the following example, we will compare two variables and provide the required output accordingly.
fun main(args: Array<String>) {
val a:Int = 5
val b:Int = 2
var max: Int
if (a > b) {
max = a
} else {
max = b
}
print("Maximum of a or b is " +max)
// As expression
// val max = if (a > b) a else b
}
The above piece of code yields the following output as a result in the browser. Our example also contains another line of code, which depicts how to use “If” statement as an expression.
Maximum of a or b is 5
If you are familiar with other programming languages, then you might have heard of the term switch statement, which is basically a conditional operator when multiple conditions can be applied on a particular variable. “when” operator matches the variable value against the branch conditions. If it is satisfying the branch condition then it will execute the statement inside that scope. In the following example, we will learn more about “when” in Kotlin.
fun main(args: Array<String>) {
val x:Int = 5
when (x) {
1 -> print("x = = 1")
2 -> print("x = = 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
}
The above piece of code yields the following output in the browser.
x is neither 1 nor 2
In the above example, Kotlin compiler matches the value of x with the given branches. If it is not matching any of the branches, then it will execute the else part. Practically, when is equivalent to multiple if block. Kotlin provides another flexibility to the developer, where the developer can provide multiple checks in the same line by providing “,” inside the checks. Let us modify the above example as follows.
fun main(args: Array<String>) {
val x:Int = 5
when (x) {
1,2 -> print(" Value of X either 1,2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
}
Run the same in the browser, which will yield the following output in the browser.
x is neither 1 nor 2
Loop is such an invention that provides the flexibility to iterate through any kind of data structure. Like other programming languages, Kotlin also provides many kinds of Looping methodology, however, among them “For” is the most successful one. The implementation and use of For loop is conceptually similar to Java for loop. The following example shows how we can use the same in real-life examples.
fun main(args: Array<String>) {
val items = listOf(1, 2, 3, 4)
for (i in items) println("values of the array"+i)
}
In the above piece of code, we have declared one list named as “items” and using for loop we are iterating through that defined list and printing its value in the browser. Following is the output.
values of the array1
values of the array2
values of the array3
values of the array4
Following is another example of code, where we are using some library function to make our development work easier than ever before.
fun main(args: Array<String>) {
val items = listOf(1, 22, 83, 4)
for ((index, value) in items.withIndex()) {
println("the element at $index is $value")
}
}
Once we compile and execute the above piece of code in our coding ground, it will yield the following output in the browser.
the element at 0 is 1
the element at 1 is 22
the element at 2 is 83
the element at 3 is 4
While and Do-While work exactly in a similar way like they do in other programming languages. The only difference between these two loops is, in case of Do-while loop the condition will be tested at the end of the loop. The following example shows the usage of the While loop.
fun main(args: Array<String>) {
var x:Int = 0
println("Example of While Loop--")
while(x< = 10) {
println(x)
x++
}
}
The above piece of code yields the following output in the browser.
Example of While Loop--
0
1
2
3
4
5
6
7
8
9
10
Kotlin also has another loop called Do-While loop, where the loop body will be executed once, only then the condition will be checked. The following example shows the usage of the Do-while loop.
fun main(args: Array<String>) {
var x:Int = 0
do {
x = x + 10
println("I am inside Do block---"+x)
} while(x <= 50)
}
The above piece of code yields the following output in the browser. In the above code, Kotlin compiler will execute the DO block, then it will go for condition checking in while block.
I am inside Do block---10
I am inside Do block---20
I am inside Do block---30
I am inside Do block---40
I am inside Do block---50
I am inside Do block---60
If you are familiar with any programming language, then you must have an idea of different keywords that help us implement good control flow in the application. Following are the different keywords that can be used to control the loops or any other types of control flow.
Return − Return is a keyword that returns some value to the calling function from the called function. In the following example, we will implement this scenario using our Kotlin coding ground.
fun main(args: Array<String>) {
var x:Int = 10
println("The value of X is--"+doubleMe(x))
}
fun doubleMe(x:Int):Int {
return 2*x;
}
In the above piece of code, we are calling another function and multiplying the input with 2, and returning the resultant value to the called function that is our main function. Kotlin defines the function in a different manner that we will look at in a subsequent chapter. For now, it is enough to understand that the above code will generate the following output in the browser.
The value of X is--20
Continue & Break − Continue and break are the most vital part of a logical problem. The “break” keyword terminates the controller flow if some condition has failed and “continue” does the opposite. All this operation happens with immediate visibility. Kotlin is smarter than other programming languages, wherein the developer can apply more than one label as visibility. The following piece of code shows how we are implementing this label in Kotlin.
fun main(args: Array<String>) {
println("Example of Break and Continue")
myLabel@ for(x in 1..10) { // appling the custom label
if(x = = 5) {
println("I am inside if block with value"+x+"\n-- hence it will close the operation")
break@myLabel //specifing the label
} else {
println("I am inside else block with value"+x)
continue@myLabel
}
}
}
The above piece of code yields the following output in the browser.
Example of Break and Continue
I am inside else block with value1
I am inside else block with value2
I am inside else block with value3
I am inside else block with value4
I am inside if block with value5
-- hence it will close the operation
As you can see, the controller continues the loop, until and unless the value of x is 5. Once the value of x reaches 5, it starts executing the if block and once the break statement is reached, the entire control flow terminates the program execution.
In this chapter, we will learn the basics of Object-Oriented Programming (OOP) using Kotlin. We will learn about class and its object and how to play with that object. By definition of OOP, a class is a blueprint of a runtime entity and object is its state, which includes both its behavior and state. In Kotlin, class declaration consists of a class header and a class body surrounded by curly braces, similar to Java.
Class myClass { // class Header
// class Body
}
Like Java, Kotlin also allows to create several objects of a class and you are free to include its class members and functions. We can control the visibility of the class members variables using different keywords that we will learn in Chapter 10 – Visibility Control. In the following example, we will create one class and its object through which we will access different data members of that class.
class myClass {
// property (data member)
private var name: String = "Tutorials.point"
// member function
fun printMe() {
print("You are at the best Learning website Named-"+name)
}
}
fun main(args: Array<String>) {
val obj = myClass() // create obj object of myClass class
obj.printMe()
}
The above piece of code will yield the following output in the browser, where we are calling printMe() of myClass using its own object.
You are at the best Learning website Named- Tutorials.point
By definition, when a class has been created inside another class, then it is called as a nested class. In Kotlin, nested class is by default static, hence, it can be accessed without creating any object of that class. In the following example, we will see how Kotlin interprets our nested class.
fun main(args: Array<String>) {
val demo = Outer.Nested().foo() // calling nested class method
print(demo)
}
class Outer {
class Nested {
fun foo() = "Welcome to The TutorialsPoint.com"
}
}
The above piece of code will yield the following output in the browser.
Welcome to The TutorialsPoint.com
When a nested class is marked as a “inner”, then it will be called as an Inner class. An inner class can be accessed by the data member of the outer class. In the following example, we will be accessing the data member of the outer class.
fun main(args: Array<String>) {
val demo = Outer().Nested().foo() // calling nested class method
print(demo)
}
class Outer {
private val welcomeMessage: String = "Welcome to the TutorialsPoint.com"
inner class Nested {
fun foo() = welcomeMessage
}
}
The above piece of code will yield the following output in the browser, where we are calling the nested class using the default constructor provided by Kotlin compilers at the time of compiling.
Welcome to the TutorialsPoint.com
Anonymous inner class is a pretty good concept that makes the life of a programmer very easy. Whenever we are implementing an interface, the concept of anonymous inner block comes into picture. The concept of creating an object of interface using runtime object reference is known as anonymous class. In the following example, we will create an interface and we will create an object of that interface using Anonymous Inner class mechanism.
fun main(args: Array<String>) {
var programmer :Human = object:Human // creating an instance of the interface {
override fun think() { // overriding the think method
print("I am an example of Anonymous Inner Class ")
}
}
programmer.think()
}
interface Human {
fun think()
}
The above piece of code will yield the following output in the browser.
I am an example of Anonymous Inner Class
Type aliases are a property of Kotlin compiler. It provides the flexibility of creating a new name of an existing type, it does not create a new type. If the type name is too long, you can easily introduce a shorter name and use the same for future usage. Type aliases is really helpful for complex type. In the latest version, Kotlin revoked the support for type aliases, however, if you are using an old version of Kotlin you may have use it like the following −
typealias NodeSet = Set<Network.Node>
typealias FileTable<K> = MutableMap<K, MutableList<File>>
In this chapter, we will learn about constructors in Kotlin. Kotlin has two types of constructor - one is the primary constructor and the other is the secondary constructor. One Kotlin class can have one primary constructor, and one or more secondary constructor. Java constructor initializes the member variables, however, in Kotlin the primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the same. The primary constructor can be declared at class header level as shown in the following example.
class Person(val firstName: String, var age: Int) {
// class body
}
In the above example, we have declared the primary constructor inside the parenthesis. Among the two fields, first name is read-only as it is declared as “val”, while the field age can be edited. In the following example, we will use the primary constructor.
fun main(args: Array<String>) {
val person1 = Person("TutorialsPoint.com", 15)
println("First Name = ${person1.firstName}")
println("Age = ${person1.age}")
}
class Person(val firstName: String, var age: Int) {
}
The above piece of code will automatically initialize the two variables and provide the following output in the browser.
First Name = TutorialsPoint.com
Age = 15
As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the “constructor” keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class. Take a look at the following example, where we have created a secondary constructor and are using the above example to implement the same.
fun main(args: Array<String>) {
val HUman = HUman("TutorialsPoint.com", 25)
print("${HUman.message}"+"${HUman.firstName}"+
"Welcome to the example of Secondary constructor, Your Age is-${HUman.age}")
}
class HUman(val firstName: String, var age: Int) {
val message:String = "Hey!!!"
constructor(name : String , age :Int ,message :String):this(name,age) {
}
}
Note − Any number of secondary constructors can be created, however, all of those constructors should call the primary constructor directly or indirectly.
The above piece of code will yield the following output in the browser.
Hey!!! TutorialsPoint.comWelcome to the example of Secondary constructor, Your Age is- 25
In this chapter, we will learn about inheritance. By definition, we all know that inheritance means accruing some properties of the mother class into the child class. In Kotlin, the base class is named as “Any”, which is the super class of the ‘any’ default class declared in Kotlin. Like all other OOPS, Kotlin also provides this functionality using one keyword known as “:”.
Everything in Kotlin is by default final, hence, we need to use the keyword “open” in front of the class declaration to make it allowable to inherit. Take a look at the following example of inheritance.
import java.util.Arrays
open class ABC {
fun think () {
print("Hey!! i am thiking ")
}
}
class BCD: ABC(){ // inheritence happend using default constructor
}
fun main(args: Array<String>) {
var a = BCD()
a.think()
}
The above piece of code will yield the following output in the browser.
Hey!! i am thiking
Now, what if we want to override the think() method in the child class. Then, we need to consider the following example where we are creating two classes and override one of its function into the child class.
import java.util.Arrays
open class ABC {
open fun think () {
print("Hey!! i am thinking ")
}
}
class BCD: ABC() { // inheritance happens using default constructor
override fun think() {
print("I Am from Child")
}
}
fun main(args: Array<String>) {
var a = BCD()
a.think()
}
The above piece of code will call the child class inherited method and it will yield the following output in the browser. Like Java, Kotlin too doesn’t allow multiple inheritances.
I Am from Child
In this chapter, we will learn about the interface in Kotlin. In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality. We have already introduced an example with an interface in Chapter 6 - section “anonymous inner class”. In this chapter, we will learn more about it. The keyword “interface” is used to define an interface in Kotlin as shown in the following piece of code.
interface ExampleInterface {
var myVar: String // abstract property
fun absMethod() // abstract method
fun sayHello() = "Hello there" // method with default implementation
}
In the above example, we have created one interface named as “ExampleInterface” and inside that we have a couple of abstract properties and methods all together. Look at the function named “sayHello()”, which is an implemented method.
In the following example, we will be implementing the above interface in a class.
interface ExampleInterface {
var myVar: Int // abstract property
fun absMethod():String // abstract method
fun hello() {
println("Hello there, Welcome to TutorialsPoint.Com!")
}
}
class InterfaceImp : ExampleInterface {
override var myVar: Int = 25
override fun absMethod() = "Happy Learning "
}
fun main(args: Array<String>) {
val obj = InterfaceImp()
println("My Variable Value is = ${obj.myVar}")
print("Calling hello(): ")
obj.hello()
print("Message from the Website-- ")
println(obj.absMethod())
}
The above piece of code will yield the following output in the browser.
My Variable Value is = 25
Calling hello(): Hello there, Welcome to TutorialsPoint.Com!
Message from the Website-- Happy Learning
As mentioned earlier, Kotlin doesn’t support multiple inheritances, however, the same thing can be achieved by implementing more than two interfaces at a time.
In the following example, we will create two interfaces and later we will implement both the interfaces into a class.
interface A {
fun printMe() {
println(" method of interface A")
}
}
interface B {
fun printMeToo() {
println("I am another Method from interface B")
}
}
// implements two interfaces A and B
class multipleInterfaceExample: A, B
fun main(args: Array<String>) {
val obj = multipleInterfaceExample()
obj.printMe()
obj.printMeToo()
}
In the above example, we have created two sample interfaces A, B and in the class named “multipleInterfaceExample” we have implemented two interfaces declared earlier. The above piece of code will yield the following output in the browser.
method of interface A
I am another Method from interface B
In this chapter, we will learn about different modifiers available in Kotlin language. Access modifier is used to restrict the usage of the variables, methods and class used in the application. Like other OOP programming language, this modifier is applicable at multiple places such as in the class header or method declaration. There are four access modifiers available in Kotlin.
The classes, methods, and packages can be declared with a private modifier. Once anything is declared as private, then it will be accessible within its immediate scope. For instance, a private package can be accessible within that specific file. A private class or interface can be accessible only by its data members, etc.
private class privateExample {
private val i = 1
private val doSomething() {
}
}
In the above example, the class “privateExample” and the variable i both can be accessible only in the same Kotlin file, where its mentioned as they all are declared as private in the declaration block.
Protected is another access modifier for Kotlin, which is currently not available for top level declaration like any package cannot be protected. A protected class or interface is visible to its subclass only.
class A() {
protected val i = 1
}
class B : A() {
fun getValue() : Int {
return i
}
}
In the above example, the variable “i” is declared as protected, hence, it is only visible to its subclass.
Internal is a newly added modifier introduced in Kotlin. If anything is marked as internal, then that specific field will be in the internal field. An Internal package is visible only inside the module under which it is implemented. An internal class interface is visible only by other class present inside the same package or the module. In the following example, we will see how to implement an internal method.
class internalExample {
internal val i = 1
internal fun doSomething() {
}
}
In the above example, the method named “doSomething” and the variable is mentioned as internal, hence, these two fields can be accessible only inside the package under which it is declared.
Public modifier is accessible from anywhere in the project workspace. If no access modifier is specified, then by default it will be in the public scope. In all our previous examples, we have not mentioned any modifier, hence, all of them are in the public scope. Following is an example to understand more on how to declare a public variable or method.
class publicExample {
val i = 1
fun doSomething() {
}
}
In the above example, we have not mentioned any modifier, thus all these methods and variables are by default public.
In this chapter, we will learn about another new feature of Kotlin named “Extension”. Using extension, we will be able to add or remove some method functionality even without inheriting or modifying them. Extensions are resolved statistically. It does not actually modify the existing class, but it creates a callable function that can be called with a dot operation.
In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level.
class Alien {
var skills : String = "null"
fun printMySkills() {
print(skills)
}
}
fun main(args: Array<String>) {
var a1 = Alien()
a1.skills = "JAVA"
//a1.printMySkills()
var a2 = Alien()
a2.skills = "SQL"
//a2.printMySkills()
var a3 = Alien()
a3.skills = a1.addMySkills(a2)
a3.printMySkills()
}
fun Alien.addMySkills(a:Alien):String{
var a4 = Alien()
a4.skills = this.skills + " " +a.skills
return a4.skills
}
In the above example, we don’t have any method inside “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension.
The above piece of code will generate the following output in the browser.
JAVA SQL
Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the keyword “companion object”. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name. In the following example, we will create a “companion object”.
fun main(args: Array<String>) {
println("Heyyy!!!"+A.show())
}
class A {
companion object {
fun show():String {
return("You are learning Kotlin from TutorialsPoint.com")
}
}
}
The above piece of code will yield the following output in the browser.
Heyyy!!! You are learning Kotlin from TutorialsPoint.com
The above example seems like static in Java, however, in real-time we are creating an object as a member variable of that same class. This is why it is also included under extension property and can be alternatively called as an object extension. You are basically extending the object of the same class to use some of the member functions.
In this chapter, we will learn more about Data classes of Kotlin programming language. A class can be marked as a Data class whenever it is marked as ”data”. This type of class can be used to hold the basic data apart. Other than this, it does not provide any other functionality.
All the data classes need to have one primary constructor and all the primary constructor should have at least one parameter. Whenever a class is marked as data, we can use some of the inbuilt function of that data class such as “toString()”,”hashCode()”, etc. Any data class cannot have a modifier like abstract and open or internal. Data class can be extended to other classes too. In the following example, we will create one data class.
fun main(args: Array<String>) {
val book: Book = Book("Kotlin", "TutorialPoint.com", 5)
println("Name of the Book is--"+book.name) // "Kotlin"
println("Puclisher Name--"+book.publisher) // "TutorialPoint.com"
println("Review of the book is--"+book.reviewScore) // 5
book.reviewScore = 7
println("Printing all the info all together--"+book.toString())
//using inbuilt function of the data class
println("Example of the hashCode function--"+book.hashCode())
}
data class Book(val name: String, val publisher: String, var reviewScore: Int)
The above piece of code will yield the following output in the browser, where we have created one data class to hold some of the data, and from the main function we have accessed all of its data members.
Name of the Book is--"Kotlin"
Puclisher Name--"TutorialPoint.com"
Review of the book is--5
Printing all the info all together--(name-Kotlin, publisher-TutorialPoint.com, reviewScore-7)
Example of the hashCode function---1753517245
In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class.
sealed class MyExample {
class OP1 : MyExample() // MyExmaple class can be of two types only
class OP2 : MyExample()
}
fun main(args: Array<String>) {
val obj: MyExample = MyExample.OP2()
val output = when (obj) { // defining the object of the class depending on the inuputs
is MyExample.OP1 -> "Option One has been chosen"
is MyExample.OP2 -> "option Two has been chosen"
}
println(output)
}
In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output.
In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser.
option Two has been chosen
Like Java, Kotlin provides higher order of variable typing called as Generics. In this chapter, we will learn how Kotlin implements Generics and how as a developer we can use those functionalities provided inside the generics library. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer.
In Kotlin, a class and a type are totally different concepts. As per the example, List is a class in Kotlin, whereas List<String> is a type in Kotlin. The following example depicts how generics is implemented in Kotlin.
fun main(args: Array<String>) {
val integer: Int = 1
val number: Number = integer
print(number)
}
In the above code, we have declared one “integer” and later we have assigned that variable to a number variable. This is possible because “Int” is a subclass of Number class, hence the type conversion happens automatically at runtime and produces the output as “1”.
Let us learn something more about generics in Kotlin. It is better to go for generic data type whenever we are not sure about the data type we are going to use in the application. Generally, in Kotlin generics is defined by <T> where “T” stands for template, which can be determined dynamically by Kotlin complier. In the following example, we will see how to use generic data types in Kotlin programming language.
fun main(args: Array<String>) {
var objet = genericsExample<String>("JAVA")
var objet1 = genericsExample<Int>(10)
}
class genericsExample<T>(input:T) {
init {
println("I am getting called with the value "+input)
}
}
In the above piece of code, we are creating one class with generic return type, which is represented as <T>. Take a look at the main method, where we have dynamically defined its value at the run by proving the value type, while creating the object of this class. This is how generics is interpreted by Kotlin compiler. We will get the following output in the browser, once we run this code in our coding ground.
I am getting called with the value JAVA
I am getting called with the value 10
When we want to assign the generic type to any of its super type, then we need to use “out” keyword, and when we want to assign the generic type to any of its sub-type, then we need to use “in” keyword. In the following example, we will use “out” keyword. Similarly, you can try using “in” keyword.
fun main(args: Array<String>) {
var objet1 = genericsExample<Int>(10)
var object2 = genericsExample<Double>(10.00)
println(objet1)
println(object2)
}
class genericsExample<out T>(input:T) {
init {
println("I am getting called with the value "+input)
}
}
The above code will yield the following output in the browser.
I am getting called with the value 10
I am getting called with the value 10.0
genericsExample@28d93b30
genericsExample@1b6d3586
Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin.
interface Base {
fun printMe() //abstract method
}
class BaseImpl(val x: Int) : Base {
override fun printMe() { println(x) } //implementation of the method
}
class Derived(b: Base) : Base by b // delegating the public method on the object b
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).printMe() // prints 10 :: accessing the printMe() method
}
In the example, we have one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()” and later from another class we are using this implementation using “by” keyword.
The above piece of code will yield the following output in the browser.
10
In the previous section, we have learned about the delegation design pattern using “by” keyword. In this section, we will learn about delegation of properties using some standard methods mentioned in Kotlin library.
Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them. In the following examples, we will use some standard delegation methodology provided by Kotlin and some standard library function while implementing delegation in our examples.
Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. Let us take a look at the following to understand how it works.
val myVar: String by lazy {
"Hello"
}
fun main(args: Array<String>) {
println(myVar +" My dear friend")
}
In the above piece of code, we are passing a variable “myVar” to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser.
Hello My dear friend
Observable() takes two arguments to initialize the object and returns the same to the called function. In the following example, we will see how to use Observable() method in order to implement delegation.
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("Welcome to Tutorialspoint.com") {
prop, old, new ->
println("$old -> $new")
}
}
fun main(args: Array<String>) {
val user = User()
user.name = "first"
user.name = "second"
}
The above piece of code will yield the following output in the browser.
first -> second
In general, the syntax is the expression after the “by” keyword is delegated. The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class.
class Example {
var p: String by Delegate()
}
For the above piece of code, following is the delegate class that we need to generate in order to assign the value in the variable p.
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name} in $thisRef.'")
}
}
While reading, getValue() method will be called and while setting the variable setValue() method will be called.
Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout the examples. Function is declared with the keyword “fun”. Like any other OOP, it also needs a return type and an option argument list.
In the following example, we are defining a function called MyFunction and from the main function we are calling this function and passing some argument.
fun main(args: Array<String>) {
println(MyFunction("tutorialsPoint.com"))
}
fun MyFunction(x: String): String {
var c:String = "Hey!! Welcome To ---"
return (c+x)
}
The above piece of code will yield the following output in the browser.
Hey!! Welcome To ---tutorialsPoint.com
The function should be declared as follows −
fun <nameOfFunction>(<argument>:<argumentType>):<ReturnType>
Following are some of the different types of function available in Kotlin.
Lambda is a high level function that drastically reduces the boiler plate code while declaring a function and defining the same. Kotlin allows you to define your own lambda. In Kotlin, you can declare your lambda and pass that lambda to a function.
Take a look at the following example.
fun main(args: Array<String>) {
val mylambda :(String)->Unit = {s:String->print(s)}
val v:String = "TutorialsPoint.com"
mylambda(v)
}
In the above code, we have created our own lambda known as “mylambda” and we have passed one variable to this lambda, which is of type String and contains a value “TutorialsPoint.com”.
The above piece of code will yield the following output in the browser.
TutorialsPoint.com
The above example shows the basic of the lambda expression that we can use in Kotlin application. Now, we can pass a lambda to another function to get our output which makes the calling function an inline function.
Take a look at the following example.
fun main(args: Array<String>) {
val mylambda:(String)->Unit = {s:String->print(s)}
val v:String = "TutorialsPoint.com"
myFun(v,mylambda) //passing lambda as a parameter of another function
}
fun myFun(a :String, action: (String)->Unit) { //passing lambda
print("Heyyy!!!")
action(a)// call to lambda function
}
The above piece of code will yield the following output in the browser. Using inline function, we have passed a lambda as a parameter. Any other function can be made an inline function using the “inline” keyword.
Heyyy!!!TutorialsPoint.com
Kotlin contains many features of other programming languages. It allows you to declare multiple variables at once. This technique is called Destructuring declaration.
Following is the basic syntax of the destructuring declaration.
val (name, age) = person
In the above syntax, we have created an object and defined all of them together in a single statement. Later, we can use them as follows.
println(name)
println(age)
Now, let us see how we can use the same in our real-life application. Consider the following example where we are creating one Student class with some attributes and later we will be using them to print the object values.
fun main(args: Array<String>) {
val s = Student("TutorialsPoint.com","Kotlin")
val (name,subject) = s
println("You are learning "+subject+" from "+name)
}
data class Student( val a :String,val b: String ){
var name:String = a
var subject:String = b
}
The above piece of code will yield the following output in the browser.
You are learning Kotlin from TutorialsPoint.com
Exception handling is a very important part of a programming language. This technique restricts our application from generating the wrong output at runtime. In this chapter, we will learn how to handle runtime exception in Kotlin. The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin.
fun main(args: Array<String>) {
try {
val myVar:Int = 12;
val v:String = "Tutorialspoint.com";
v.toInt();
} catch(e:Exception) {
e.printStackTrace();
} finally {
println("Exception Handeling in Kotlin");
}
}
In the above piece of code, we have declared a String and later tied that string into the integer, which is actually a runtime exception. Hence, we will get the following output in the browser.
val myVar:Int = 12;
Exception Handeling in Kotlin
Note − Like Java, Kotlin also executes the finally block after executing the catch block.
|
[
{
"code": null,
"e": 2814,
"s": 2559,
"text": "Kotlin is a new open source programming language like Java, JavaScript, etc. It is a high level strongly statically typed language that combines functional and technical part in a same place. Currently, Kotlin targets Java and JavaScript. It runs on JVM."
},
{
"code": null,
"e": 3181,
"s": 2814,
"text": "Kotlin is influenced by other programming languages such as Java, Scala, Groovy, Gosu, etc. The syntax of Kotlin may not be exactly similar to JAVA, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world."
},
{
"code": null,
"e": 3268,
"s": 3181,
"text": "Following are some of the advantages of using Kotlin for your application development."
},
{
"code": null,
"e": 3501,
"s": 3268,
"text": "Easy Language − Kotlin is a functional language and very easy to learn. The syntax is pretty much similar to Java, hence it is very easy to remember. Kotlin is more expressive, which makes your code more readable and understandable."
},
{
"code": null,
"e": 3646,
"s": 3501,
"text": "Concise − Kotlin is based on JVM and it is a functional language. Thus, it reduce lots of boiler plate code used in other programming languages."
},
{
"code": null,
"e": 3710,
"s": 3646,
"text": "Runtime and Performance − Better performance and small runtime."
},
{
"code": null,
"e": 3817,
"s": 3710,
"text": "Interoperability − Kotlin is mature enough to build an interoperable application in a less complex manner."
},
{
"code": null,
"e": 4104,
"s": 3817,
"text": "Brand New − Kotlin is a brand new language that gives developers a fresh start. It is not a replacement of Java, though it is developed over JVM. It is accepted as the first official language of android development. Kotlin can be defined as - Kotlin = JAVA + extra updated new features."
},
{
"code": null,
"e": 4155,
"s": 4104,
"text": "Following are some of the disadvantages of Kotlin."
},
{
"code": null,
"e": 4393,
"s": 4155,
"text": "Namespace declaration − Kotlin allows developers to declare the functions at the top level. However, whenever the same function is declared in many places of your application, then it is hard to understand which function is being called."
},
{
"code": null,
"e": 4545,
"s": 4393,
"text": "No Static Declaration − Kotlin does not have usual static handling modifier like Java, which can cause some problem to the conventional Java developer."
},
{
"code": null,
"e": 4696,
"s": 4545,
"text": "However, if you still want to use Kotlin offline in your local system, then you need to execute the following steps to configure your local workspace."
},
{
"code": null,
"e": 4726,
"s": 4696,
"text": "Step 1 − Java 8 installation."
},
{
"code": null,
"e": 5186,
"s": 4726,
"text": "Kotlin runs on JVM, hence. it is really necessary to use JDK 8 for your local Kotlin development. Please refer to the official website of oracle to download and install JDK 8 or an above version. You might have to set the environment variable for JAVA such that it can work properly. To verify your installation in Windows operating system, hit “java –version” in the command prompt and as an output it will show you the java version installed in your system."
},
{
"code": null,
"e": 5213,
"s": 5186,
"text": "Step 2 − IDE installation."
},
{
"code": null,
"e": 5372,
"s": 5213,
"text": "There are a number of IDE available over the internet. You can use any of your choice. You can find the download link of different IDE in the following table."
},
{
"code": null,
"e": 5470,
"s": 5372,
"text": "It is always recommended to use the recent software version to drag out maximum facility from it."
},
{
"code": null,
"e": 5500,
"s": 5470,
"text": "Step 3 − Configuring Eclipse."
},
{
"code": null,
"e": 5583,
"s": 5500,
"text": "Open Eclipse and go to “Eclipse Market Place”. You will find the following screen."
},
{
"code": null,
"e": 5792,
"s": 5583,
"text": "Search for Kotlin in the search box and install the same in your local system. It might take some time depending on the internet speed. You may have to restart your Eclipse, once it is successfully installed."
},
{
"code": null,
"e": 5817,
"s": 5792,
"text": "Step 4 − Kotlin Project."
},
{
"code": null,
"e": 6006,
"s": 5817,
"text": "Once Eclipse is successfully restarted and Kotlin is installed, you will be able to create a Kotlin project on the fly. Go to File → New → Others and select “Kotlin project” from the list."
},
{
"code": null,
"e": 6311,
"s": 6006,
"text": "Once the project setup is done, you can create a Kotlin file under “SRC” folder. Left-click on the “Src” folder and hit “new”. You will get an option for Kotlin file, otherwise you may have to search from the “others”. Once the new file is created, your project directory will be look like the following."
},
{
"code": null,
"e": 6423,
"s": 6311,
"text": "Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file."
},
{
"code": null,
"e": 6485,
"s": 6423,
"text": "fun main(args: Array<String>) {\n println(\"Hello, World!\")\n}"
},
{
"code": null,
"e": 6672,
"s": 6485,
"text": "Run it as a Kotlin application and see the output in the console as shown in the following screenshot. For better understanding and availability, we will be using our coding ground tool."
},
{
"code": null,
"e": 6687,
"s": 6672,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 6985,
"s": 6687,
"text": "Kotlin is a programming language and has its own architecture to allocate memory and produce a quality output to the end user. Following are the different scenarios where Kotlin compiler will work differently, whenever it is targeting different other kind of languages such as Java and JavaScript."
},
{
"code": null,
"e": 7294,
"s": 6985,
"text": "Kotlin compiler creates a byte code and that byte code can run on the JVM, which is exactly equal to the byte code generated by the Java .class file. Whenever two byte coded file runs on the JVM, they can communicate with each other and this is how an interoperable feature is established in Kotlin for Java."
},
{
"code": null,
"e": 7512,
"s": 7294,
"text": "Whenever Kotlin targets JavaScript, the Kotlin compiler converts the .kt file into ES5.1 and generates a compatible code for JavaScript. Kotlin compiler is capable of creating platform basis compatible codes via LLVM."
},
{
"code": null,
"e": 7612,
"s": 7512,
"text": "In this chapter, we will learn about the basic data types available in Kotlin programming language."
},
{
"code": null,
"e": 7827,
"s": 7612,
"text": "The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not allow internal conversion of different data types. Following table lists different variable lengths for different numbers."
},
{
"code": null,
"e": 7970,
"s": 7827,
"text": "In the following example, we will see how Kotlin works with different data types. Please enter the following set of code in our coding ground."
},
{
"code": null,
"e": 8376,
"s": 7970,
"text": "fun main(args: Array<String>) {\n val a: Int = 10000\n val d: Double = 100.00\n val f: Float = 100.00f\n val l: Long = 1000000004\n val s: Short = 10\n val b: Byte = 1\n \n println(\"Your Int Value is \"+a);\n println(\"Your Double Value is \"+d);\n println(\"Your Float Value is \"+f);\n println(\"Your Long Value is \"+l);\n println(\"Your Short Value is \"+s);\n println(\"Your Byte Value is \"+b);\n}"
},
{
"code": null,
"e": 8493,
"s": 8376,
"text": "When you run the above piece of code in the coding ground, it will generate the following output in the web console."
},
{
"code": null,
"e": 8646,
"s": 8493,
"text": "Your Int Value is 10000\nYour Double Value is 100.0\nYour Float Value is 100.0\nYour Long Value is 1000000004\nYour Short Value is 10\nYour Byte Value is 1\n"
},
{
"code": null,
"e": 8998,
"s": 8646,
"text": "Kotlin represents character using char. Character should be declared in a single quote like ‘c’. Please enter the following code in our coding ground and see how Kotlin interprets the character variable. Character variable cannot be declared like number variables. Kotlin variable can be declared in two ways - one using “var” and another using “val”."
},
{
"code": null,
"e": 9152,
"s": 8998,
"text": "fun main(args: Array<String>) {\n val letter: Char // defining a variable \n letter = 'A' // Assigning a value to it \n println(\"$letter\")\n}"
},
{
"code": null,
"e": 9238,
"s": 9152,
"text": "The above piece of code will yield the following output in the browser output window."
},
{
"code": null,
"e": 9241,
"s": 9238,
"text": "A\n"
},
{
"code": null,
"e": 9427,
"s": 9241,
"text": "Boolean is very simple like other programming languages. We have only two values for Boolean – either true or false. In the following example, we will see how Kotlin interprets Boolean."
},
{
"code": null,
"e": 9612,
"s": 9427,
"text": "fun main(args: Array<String>) {\n val letter: Boolean // defining a variable \n letter = true // Assinging a value to it \n println(\"Your character value is \"+\"$letter\")\n}"
},
{
"code": null,
"e": 9684,
"s": 9612,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 9714,
"s": 9684,
"text": "Your character value is true\n"
},
{
"code": null,
"e": 9959,
"s": 9714,
"text": "Strings are character arrays. Like Java, they are immutable in nature. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. In the following example, we will make use of these strings."
},
{
"code": null,
"e": 10170,
"s": 9959,
"text": "fun main(args: Array<String>) {\n var rawString :String = \"I am Raw String!\"\n val escapedString : String = \"I am escaped String!\\n\"\n \n println(\"Hello!\"+escapedString)\n println(\"Hey!!\"+rawString) \n}"
},
{
"code": null,
"e": 10319,
"s": 10170,
"text": "The above example of escaped String allows to provide extra line space after the first print statement. Following will be the output in the browser."
},
{
"code": null,
"e": 10370,
"s": 10319,
"text": "Hello!I am escaped String!\n\nHey!!I am Raw String!\n"
},
{
"code": null,
"e": 10538,
"s": 10370,
"text": "Arrays are a collection of homogeneous data. Like Java, Kotlin supports arrays of different data types. In the following example, we will make use of different arrays."
},
{
"code": null,
"e": 10675,
"s": 10538,
"text": "fun main(args: Array<String>) {\n val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)\n println(\"Hey!! I am array Example\"+numbers[2])\n}"
},
{
"code": null,
"e": 10860,
"s": 10675,
"text": "The above piece of code yields the following output. The indexing of the array is similar to other programming languages. Here, we are searching for a second index, whose value is “3”."
},
{
"code": null,
"e": 10887,
"s": 10860,
"text": "Hey!! I am array Example3\n"
},
{
"code": null,
"e": 11355,
"s": 10887,
"text": "Collection is a very important part of the data structure, which makes the software development easy for engineers. Kotlin has two types of collection - one is immutable collection (which means lists, maps and sets that cannot be editable) and another is mutable collection (this type of collection is editable). It is very important to keep in mind the type of collection used in your application, as Kotlin system does not represent any specific difference in them."
},
{
"code": null,
"e": 11817,
"s": 11355,
"text": "fun main(args: Array<String>) { \n val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //mutable List \n val readOnlyView: List<Int> = numbers // immutable list \n println(\"my mutable list--\"+numbers) // prints \"[1, 2, 3]\" \n numbers.add(4) \n println(\"my mutable list after addition --\"+numbers) // prints \"[1, 2, 3, 4]\" \n println(readOnlyView) \n readOnlyView.clear() // ⇒ does not compile \n// gives error \n}"
},
{
"code": null,
"e": 11960,
"s": 11817,
"text": "The above piece of code will yield the following output in the browser. It gives an error when we try to clear the mutable list of collection."
},
{
"code": null,
"e": 12081,
"s": 11960,
"text": "main.kt:9:18: error: unresolved reference: clear\n readOnlyView.clear() // -> does not compile \n ^\n"
},
{
"code": null,
"e": 12399,
"s": 12081,
"text": "In collection, Kotlin provides some useful methods such as first(), last(), filter(), etc. All these methods are self-descriptive and easy to implement. Moreover, Kotlin follows the same structure such as Java while implementing collection. You are free to implement any collection of your choice such as Map and Set."
},
{
"code": null,
"e": 12491,
"s": 12399,
"text": "In the following example, we have implemented Map and Set using different built-in methods."
},
{
"code": null,
"e": 12971,
"s": 12491,
"text": "fun main(args: Array<String>) {\n val items = listOf(1, 2, 3, 4)\n println(\"First Element of our list----\"+items.first())\n println(\"Last Element of our list----\"+items.last())\n println(\"Even Numbers of our List----\"+items.\n filter { it % 2 = = 0 }) // returns [2, 4]\n \n val readWriteMap = hashMapOf(\"foo\" to 1, \"bar\" to 2)\n println(readWriteMap[\"foo\"]) // prints \"1\"\n \n val strings = hashSetOf(\"a\", \"b\", \"c\", \"c\")\n println(\"My Set Values are\"+strings)\n}"
},
{
"code": null,
"e": 13039,
"s": 12971,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 13165,
"s": 13039,
"text": "First Element of our list----1\nLast Element of our list----4\nEven Numbers of our List----[2, 4]\n1\nMy Set Values are[a, b, c]\n"
},
{
"code": null,
"e": 13372,
"s": 13165,
"text": "Ranges is another unique characteristic of Kotlin. Like Haskell, it provides an operator that helps you iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..)."
},
{
"code": null,
"e": 13453,
"s": 13372,
"text": "In the following example, we will see how Kotlin interprets this range operator."
},
{
"code": null,
"e": 13664,
"s": 13453,
"text": "fun main(args: Array<String>) {\n val i:Int = 2\n for (j in 1..4) \n print(j) // prints \"1234\"\n \n if (i in 1..10) { // equivalent of 1 < = i && i < = 10\n println(\"we found your number --\"+i)\n }\n}"
},
{
"code": null,
"e": 13732,
"s": 13664,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 13762,
"s": 13732,
"text": "1234we found your number --2\n"
},
{
"code": null,
"e": 13966,
"s": 13762,
"text": "In the previous chapter we have learned about different types of data types available in Kotlin system. In this chapter, we will discuss different types of control flow mechanism available in the Kotlin."
},
{
"code": null,
"e": 14352,
"s": 13966,
"text": "Kotlin is a functional language hence like every functional language in Kotlin “if” is an expression, it is not a keyword. The expression “if” will return a value whenever necessary. Like other programming language, “if-else” block is used as an initial conditional checking operator. In the following example, we will compare two variables and provide the required output accordingly."
},
{
"code": null,
"e": 14599,
"s": 14352,
"text": "fun main(args: Array<String>) {\n val a:Int = 5\n val b:Int = 2\n var max: Int\n \n if (a > b) {\n max = a\n } else {\n max = b\n }\n print(\"Maximum of a or b is \" +max)\n \n // As expression \n // val max = if (a > b) a else b\n}"
},
{
"code": null,
"e": 14785,
"s": 14599,
"text": "The above piece of code yields the following output as a result in the browser. Our example also contains another line of code, which depicts how to use “If” statement as an expression."
},
{
"code": null,
"e": 14809,
"s": 14785,
"text": "Maximum of a or b is 5\n"
},
{
"code": null,
"e": 15265,
"s": 14809,
"text": "If you are familiar with other programming languages, then you might have heard of the term switch statement, which is basically a conditional operator when multiple conditions can be applied on a particular variable. “when” operator matches the variable value against the branch conditions. If it is satisfying the branch condition then it will execute the statement inside that scope. In the following example, we will learn more about “when” in Kotlin."
},
{
"code": null,
"e": 15479,
"s": 15265,
"text": "fun main(args: Array<String>) {\n val x:Int = 5\n when (x) {\n 1 -> print(\"x = = 1\")\n 2 -> print(\"x = = 2\")\n \n else -> { // Note the block\n print(\"x is neither 1 nor 2\")\n }\n }\n}"
},
{
"code": null,
"e": 15547,
"s": 15479,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 15569,
"s": 15547,
"text": "x is neither 1 nor 2\n"
},
{
"code": null,
"e": 15987,
"s": 15569,
"text": "In the above example, Kotlin compiler matches the value of x with the given branches. If it is not matching any of the branches, then it will execute the else part. Practically, when is equivalent to multiple if block. Kotlin provides another flexibility to the developer, where the developer can provide multiple checks in the same line by providing “,” inside the checks. Let us modify the above example as follows."
},
{
"code": null,
"e": 16190,
"s": 15987,
"text": "fun main(args: Array<String>) {\n val x:Int = 5\n when (x) {\n 1,2 -> print(\" Value of X either 1,2\")\n \n else -> { // Note the block\n print(\"x is neither 1 nor 2\")\n }\n }\n}"
},
{
"code": null,
"e": 16273,
"s": 16190,
"text": "Run the same in the browser, which will yield the following output in the browser."
},
{
"code": null,
"e": 16295,
"s": 16273,
"text": "x is neither 1 nor 2\n"
},
{
"code": null,
"e": 16698,
"s": 16295,
"text": "Loop is such an invention that provides the flexibility to iterate through any kind of data structure. Like other programming languages, Kotlin also provides many kinds of Looping methodology, however, among them “For” is the most successful one. The implementation and use of For loop is conceptually similar to Java for loop. The following example shows how we can use the same in real-life examples."
},
{
"code": null,
"e": 16819,
"s": 16698,
"text": "fun main(args: Array<String>) {\n val items = listOf(1, 2, 3, 4)\n for (i in items) println(\"values of the array\"+i)\n}"
},
{
"code": null,
"e": 17016,
"s": 16819,
"text": "In the above piece of code, we have declared one list named as “items” and using for loop we are iterating through that defined list and printing its value in the browser. Following is the output."
},
{
"code": null,
"e": 17101,
"s": 17016,
"text": "values of the array1\nvalues of the array2\nvalues of the array3\nvalues of the array4\n"
},
{
"code": null,
"e": 17234,
"s": 17101,
"text": "Following is another example of code, where we are using some library function to make our development work easier than ever before."
},
{
"code": null,
"e": 17409,
"s": 17234,
"text": "fun main(args: Array<String>) {\n val items = listOf(1, 22, 83, 4)\n \n for ((index, value) in items.withIndex()) {\n println(\"the element at $index is $value\")\n }\n}"
},
{
"code": null,
"e": 17534,
"s": 17409,
"text": "Once we compile and execute the above piece of code in our coding ground, it will yield the following output in the browser."
},
{
"code": null,
"e": 17625,
"s": 17534,
"text": "the element at 0 is 1\nthe element at 1 is 22\nthe element at 2 is 83\nthe element at 3 is 4\n"
},
{
"code": null,
"e": 17902,
"s": 17625,
"text": "While and Do-While work exactly in a similar way like they do in other programming languages. The only difference between these two loops is, in case of Do-while loop the condition will be tested at the end of the loop. The following example shows the usage of the While loop."
},
{
"code": null,
"e": 18048,
"s": 17902,
"text": "fun main(args: Array<String>) {\n var x:Int = 0\n println(\"Example of While Loop--\")\n \n while(x< = 10) {\n println(x)\n x++\n } \n}"
},
{
"code": null,
"e": 18116,
"s": 18048,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 18164,
"s": 18116,
"text": "Example of While Loop--\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"
},
{
"code": null,
"e": 18359,
"s": 18164,
"text": "Kotlin also has another loop called Do-While loop, where the loop body will be executed once, only then the condition will be checked. The following example shows the usage of the Do-while loop."
},
{
"code": null,
"e": 18498,
"s": 18359,
"text": "fun main(args: Array<String>) {\n var x:Int = 0\n do {\n x = x + 10\n println(\"I am inside Do block---\"+x)\n } while(x <= 50)\n}"
},
{
"code": null,
"e": 18683,
"s": 18498,
"text": "The above piece of code yields the following output in the browser. In the above code, Kotlin compiler will execute the DO block, then it will go for condition checking in while block."
},
{
"code": null,
"e": 18840,
"s": 18683,
"text": "I am inside Do block---10\nI am inside Do block---20\nI am inside Do block---30\nI am inside Do block---40\nI am inside Do block---50\nI am inside Do block---60\n"
},
{
"code": null,
"e": 19112,
"s": 18840,
"text": "If you are familiar with any programming language, then you must have an idea of different keywords that help us implement good control flow in the application. Following are the different keywords that can be used to control the loops or any other types of control flow."
},
{
"code": null,
"e": 19305,
"s": 19112,
"text": "Return − Return is a keyword that returns some value to the calling function from the called function. In the following example, we will implement this scenario using our Kotlin coding ground."
},
{
"code": null,
"e": 19446,
"s": 19305,
"text": "fun main(args: Array<String>) {\n var x:Int = 10\n println(\"The value of X is--\"+doubleMe(x))\n}\nfun doubleMe(x:Int):Int {\n return 2*x;\n}"
},
{
"code": null,
"e": 19827,
"s": 19446,
"text": "In the above piece of code, we are calling another function and multiplying the input with 2, and returning the resultant value to the called function that is our main function. Kotlin defines the function in a different manner that we will look at in a subsequent chapter. For now, it is enough to understand that the above code will generate the following output in the browser."
},
{
"code": null,
"e": 19850,
"s": 19827,
"text": "The value of X is--20\n"
},
{
"code": null,
"e": 20301,
"s": 19850,
"text": "Continue & Break − Continue and break are the most vital part of a logical problem. The “break” keyword terminates the controller flow if some condition has failed and “continue” does the opposite. All this operation happens with immediate visibility. Kotlin is smarter than other programming languages, wherein the developer can apply more than one label as visibility. The following piece of code shows how we are implementing this label in Kotlin."
},
{
"code": null,
"e": 20707,
"s": 20301,
"text": "fun main(args: Array<String>) {\n println(\"Example of Break and Continue\")\n myLabel@ for(x in 1..10) { // appling the custom label\n if(x = = 5) {\n println(\"I am inside if block with value\"+x+\"\\n-- hence it will close the operation\")\n break@myLabel //specifing the label\n } else {\n println(\"I am inside else block with value\"+x)\n continue@myLabel\n }\n }\n}"
},
{
"code": null,
"e": 20775,
"s": 20707,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 21016,
"s": 20775,
"text": "Example of Break and Continue\nI am inside else block with value1\nI am inside else block with value2\nI am inside else block with value3\nI am inside else block with value4\nI am inside if block with value5\n-- hence it will close the operation\n"
},
{
"code": null,
"e": 21268,
"s": 21016,
"text": "As you can see, the controller continues the loop, until and unless the value of x is 5. Once the value of x reaches 5, it starts executing the if block and once the break statement is reached, the entire control flow terminates the program execution."
},
{
"code": null,
"e": 21688,
"s": 21268,
"text": "In this chapter, we will learn the basics of Object-Oriented Programming (OOP) using Kotlin. We will learn about class and its object and how to play with that object. By definition of OOP, a class is a blueprint of a runtime entity and object is its state, which includes both its behavior and state. In Kotlin, class declaration consists of a class header and a class body surrounded by curly braces, similar to Java."
},
{
"code": null,
"e": 21741,
"s": 21688,
"text": "Class myClass { // class Header \n\n // class Body\n}"
},
{
"code": null,
"e": 22143,
"s": 21741,
"text": "Like Java, Kotlin also allows to create several objects of a class and you are free to include its class members and functions. We can control the visibility of the class members variables using different keywords that we will learn in Chapter 10 – Visibility Control. In the following example, we will create one class and its object through which we will access different data members of that class."
},
{
"code": null,
"e": 22464,
"s": 22143,
"text": "class myClass {\n // property (data member)\n private var name: String = \"Tutorials.point\"\n \n // member function\n fun printMe() {\n print(\"You are at the best Learning website Named-\"+name)\n }\n}\nfun main(args: Array<String>) {\n val obj = myClass() // create obj object of myClass class\n obj.printMe()\n}"
},
{
"code": null,
"e": 22600,
"s": 22464,
"text": "The above piece of code will yield the following output in the browser, where we are calling printMe() of myClass using its own object."
},
{
"code": null,
"e": 22661,
"s": 22600,
"text": "You are at the best Learning website Named- Tutorials.point\n"
},
{
"code": null,
"e": 22958,
"s": 22661,
"text": "By definition, when a class has been created inside another class, then it is called as a nested class. In Kotlin, nested class is by default static, hence, it can be accessed without creating any object of that class. In the following example, we will see how Kotlin interprets our nested class."
},
{
"code": null,
"e": 23166,
"s": 22958,
"text": "fun main(args: Array<String>) {\n val demo = Outer.Nested().foo() // calling nested class method\n print(demo)\n}\nclass Outer {\n class Nested {\n fun foo() = \"Welcome to The TutorialsPoint.com\"\n }\n}"
},
{
"code": null,
"e": 23238,
"s": 23166,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 23273,
"s": 23238,
"text": "Welcome to The TutorialsPoint.com\n"
},
{
"code": null,
"e": 23512,
"s": 23273,
"text": "When a nested class is marked as a “inner”, then it will be called as an Inner class. An inner class can be accessed by the data member of the outer class. In the following example, we will be accessing the data member of the outer class."
},
{
"code": null,
"e": 23783,
"s": 23512,
"text": "fun main(args: Array<String>) {\n val demo = Outer().Nested().foo() // calling nested class method\n print(demo)\n}\nclass Outer {\n private val welcomeMessage: String = \"Welcome to the TutorialsPoint.com\"\n inner class Nested {\n fun foo() = welcomeMessage\n }\n}"
},
{
"code": null,
"e": 23978,
"s": 23783,
"text": "The above piece of code will yield the following output in the browser, where we are calling the nested class using the default constructor provided by Kotlin compilers at the time of compiling."
},
{
"code": null,
"e": 24013,
"s": 23978,
"text": "Welcome to the TutorialsPoint.com\n"
},
{
"code": null,
"e": 24454,
"s": 24013,
"text": "Anonymous inner class is a pretty good concept that makes the life of a programmer very easy. Whenever we are implementing an interface, the concept of anonymous inner block comes into picture. The concept of creating an object of interface using runtime object reference is known as anonymous class. In the following example, we will create an interface and we will create an object of that interface using Anonymous Inner class mechanism."
},
{
"code": null,
"e": 24761,
"s": 24454,
"text": "fun main(args: Array<String>) {\n var programmer :Human = object:Human // creating an instance of the interface {\n override fun think() { // overriding the think method\n print(\"I am an example of Anonymous Inner Class \")\n }\n }\n programmer.think()\n}\ninterface Human {\n fun think()\n}"
},
{
"code": null,
"e": 24833,
"s": 24761,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 24876,
"s": 24833,
"text": "I am an example of Anonymous Inner Class \n"
},
{
"code": null,
"e": 25341,
"s": 24876,
"text": "Type aliases are a property of Kotlin compiler. It provides the flexibility of creating a new name of an existing type, it does not create a new type. If the type name is too long, you can easily introduce a shorter name and use the same for future usage. Type aliases is really helpful for complex type. In the latest version, Kotlin revoked the support for type aliases, however, if you are using an old version of Kotlin you may have use it like the following −"
},
{
"code": null,
"e": 25437,
"s": 25341,
"text": "typealias NodeSet = Set<Network.Node>\ntypealias FileTable<K> = MutableMap<K, MutableList<File>>"
},
{
"code": null,
"e": 26012,
"s": 25437,
"text": "In this chapter, we will learn about constructors in Kotlin. Kotlin has two types of constructor - one is the primary constructor and the other is the secondary constructor. One Kotlin class can have one primary constructor, and one or more secondary constructor. Java constructor initializes the member variables, however, in Kotlin the primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the same. The primary constructor can be declared at class header level as shown in the following example."
},
{
"code": null,
"e": 26083,
"s": 26012,
"text": "class Person(val firstName: String, var age: Int) {\n // class body\n}"
},
{
"code": null,
"e": 26342,
"s": 26083,
"text": "In the above example, we have declared the primary constructor inside the parenthesis. Among the two fields, first name is read-only as it is declared as “val”, while the field age can be edited. In the following example, we will use the primary constructor."
},
{
"code": null,
"e": 26563,
"s": 26342,
"text": "fun main(args: Array<String>) {\n val person1 = Person(\"TutorialsPoint.com\", 15)\n println(\"First Name = ${person1.firstName}\")\n println(\"Age = ${person1.age}\")\n}\nclass Person(val firstName: String, var age: Int) {\n}"
},
{
"code": null,
"e": 26684,
"s": 26563,
"text": "The above piece of code will automatically initialize the two variables and provide the following output in the browser."
},
{
"code": null,
"e": 26726,
"s": 26684,
"text": "First Name = TutorialsPoint.com\nAge = 15\n"
},
{
"code": null,
"e": 27272,
"s": 26726,
"text": "As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the “constructor” keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class. Take a look at the following example, where we have created a secondary constructor and are using the above example to implement the same."
},
{
"code": null,
"e": 27652,
"s": 27272,
"text": "fun main(args: Array<String>) {\n val HUman = HUman(\"TutorialsPoint.com\", 25)\n print(\"${HUman.message}\"+\"${HUman.firstName}\"+\n \"Welcome to the example of Secondary constructor, Your Age is-${HUman.age}\")\n}\nclass HUman(val firstName: String, var age: Int) {\n val message:String = \"Hey!!!\"\n\tconstructor(name : String , age :Int ,message :String):this(name,age) {\n }\n}"
},
{
"code": null,
"e": 27807,
"s": 27652,
"text": "Note − Any number of secondary constructors can be created, however, all of those constructors should call the primary constructor directly or indirectly."
},
{
"code": null,
"e": 27879,
"s": 27807,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 27971,
"s": 27879,
"text": "Hey!!! TutorialsPoint.comWelcome to the example of Secondary constructor, Your Age is- 25\n"
},
{
"code": null,
"e": 28348,
"s": 27971,
"text": "In this chapter, we will learn about inheritance. By definition, we all know that inheritance means accruing some properties of the mother class into the child class. In Kotlin, the base class is named as “Any”, which is the super class of the ‘any’ default class declared in Kotlin. Like all other OOPS, Kotlin also provides this functionality using one keyword known as “:”."
},
{
"code": null,
"e": 28551,
"s": 28348,
"text": "Everything in Kotlin is by default final, hence, we need to use the keyword “open” in front of the class declaration to make it allowable to inherit. Take a look at the following example of inheritance."
},
{
"code": null,
"e": 28789,
"s": 28551,
"text": "import java.util.Arrays\n\nopen class ABC {\n fun think () {\n print(\"Hey!! i am thiking \")\n }\n}\nclass BCD: ABC(){ // inheritence happend using default constructor \n}\n\nfun main(args: Array<String>) {\n var a = BCD()\n a.think()\n}"
},
{
"code": null,
"e": 28861,
"s": 28789,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 28882,
"s": 28861,
"text": "Hey!! i am thiking \n"
},
{
"code": null,
"e": 29091,
"s": 28882,
"text": "Now, what if we want to override the think() method in the child class. Then, we need to consider the following example where we are creating two classes and override one of its function into the child class."
},
{
"code": null,
"e": 29397,
"s": 29091,
"text": "import java.util.Arrays\n\nopen class ABC {\n open fun think () {\n print(\"Hey!! i am thinking \")\n }\n}\nclass BCD: ABC() { // inheritance happens using default constructor \n override fun think() {\n print(\"I Am from Child\")\n }\n}\nfun main(args: Array<String>) {\n var a = BCD()\n a.think()\n}"
},
{
"code": null,
"e": 29578,
"s": 29397,
"text": "The above piece of code will call the child class inherited method and it will yield the following output in the browser. Like Java, Kotlin too doesn’t allow multiple inheritances."
},
{
"code": null,
"e": 29596,
"s": 29578,
"text": "I Am from Child \n"
},
{
"code": null,
"e": 30150,
"s": 29596,
"text": "In this chapter, we will learn about the interface in Kotlin. In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality. We have already introduced an example with an interface in Chapter 6 - section “anonymous inner class”. In this chapter, we will learn more about it. The keyword “interface” is used to define an interface in Kotlin as shown in the following piece of code."
},
{
"code": null,
"e": 30343,
"s": 30150,
"text": "interface ExampleInterface {\n var myVar: String // abstract property\n fun absMethod() // abstract method\n fun sayHello() = \"Hello there\" // method with default implementation\n}"
},
{
"code": null,
"e": 30578,
"s": 30343,
"text": "In the above example, we have created one interface named as “ExampleInterface” and inside that we have a couple of abstract properties and methods all together. Look at the function named “sayHello()”, which is an implemented method."
},
{
"code": null,
"e": 30660,
"s": 30578,
"text": "In the following example, we will be implementing the above interface in a class."
},
{
"code": null,
"e": 31228,
"s": 30660,
"text": "interface ExampleInterface {\n var myVar: Int // abstract property\n fun absMethod():String // abstract method\n \n fun hello() {\n println(\"Hello there, Welcome to TutorialsPoint.Com!\")\n }\n}\nclass InterfaceImp : ExampleInterface {\n override var myVar: Int = 25\n override fun absMethod() = \"Happy Learning \"\n}\nfun main(args: Array<String>) {\n val obj = InterfaceImp()\n println(\"My Variable Value is = ${obj.myVar}\")\n print(\"Calling hello(): \")\n obj.hello()\n \n print(\"Message from the Website-- \")\n println(obj.absMethod())\n}"
},
{
"code": null,
"e": 31300,
"s": 31228,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 31431,
"s": 31300,
"text": "My Variable Value is = 25\nCalling hello(): Hello there, Welcome to TutorialsPoint.Com!\nMessage from the Website-- Happy Learning \n"
},
{
"code": null,
"e": 31591,
"s": 31431,
"text": "As mentioned earlier, Kotlin doesn’t support multiple inheritances, however, the same thing can be achieved by implementing more than two interfaces at a time."
},
{
"code": null,
"e": 31709,
"s": 31591,
"text": "In the following example, we will create two interfaces and later we will implement both the interfaces into a class."
},
{
"code": null,
"e": 32074,
"s": 31709,
"text": "interface A {\n fun printMe() {\n println(\" method of interface A\")\n }\n}\ninterface B {\n fun printMeToo() {\n println(\"I am another Method from interface B\")\n }\n}\n\n// implements two interfaces A and B\nclass multipleInterfaceExample: A, B\n\nfun main(args: Array<String>) {\n val obj = multipleInterfaceExample()\n obj.printMe()\n obj.printMeToo()\n}"
},
{
"code": null,
"e": 32314,
"s": 32074,
"text": "In the above example, we have created two sample interfaces A, B and in the class named “multipleInterfaceExample” we have implemented two interfaces declared earlier. The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 32374,
"s": 32314,
"text": "method of interface A\nI am another Method from interface B\n"
},
{
"code": null,
"e": 32756,
"s": 32374,
"text": "In this chapter, we will learn about different modifiers available in Kotlin language. Access modifier is used to restrict the usage of the variables, methods and class used in the application. Like other OOP programming language, this modifier is applicable at multiple places such as in the class header or method declaration. There are four access modifiers available in Kotlin."
},
{
"code": null,
"e": 33080,
"s": 32756,
"text": "The classes, methods, and packages can be declared with a private modifier. Once anything is declared as private, then it will be accessible within its immediate scope. For instance, a private package can be accessible within that specific file. A private class or interface can be accessible only by its data members, etc."
},
{
"code": null,
"e": 33170,
"s": 33080,
"text": "private class privateExample {\n private val i = 1\n private val doSomething() {\n }\n}"
},
{
"code": null,
"e": 33373,
"s": 33170,
"text": "In the above example, the class “privateExample” and the variable i both can be accessible only in the same Kotlin file, where its mentioned as they all are declared as private in the declaration block."
},
{
"code": null,
"e": 33583,
"s": 33373,
"text": "Protected is another access modifier for Kotlin, which is currently not available for top level declaration like any package cannot be protected. A protected class or interface is visible to its subclass only."
},
{
"code": null,
"e": 33684,
"s": 33583,
"text": "class A() {\n protected val i = 1\n}\nclass B : A() {\n fun getValue() : Int {\n return i\n }\n}"
},
{
"code": null,
"e": 33792,
"s": 33684,
"text": "In the above example, the variable “i” is declared as protected, hence, it is only visible to its subclass."
},
{
"code": null,
"e": 34206,
"s": 33792,
"text": "Internal is a newly added modifier introduced in Kotlin. If anything is marked as internal, then that specific field will be in the internal field. An Internal package is visible only inside the module under which it is implemented. An internal class interface is visible only by other class present inside the same package or the module. In the following example, we will see how to implement an internal method."
},
{
"code": null,
"e": 34291,
"s": 34206,
"text": "class internalExample {\n internal val i = 1\n internal fun doSomething() {\n }\n}"
},
{
"code": null,
"e": 34481,
"s": 34291,
"text": "In the above example, the method named “doSomething” and the variable is mentioned as internal, hence, these two fields can be accessible only inside the package under which it is declared."
},
{
"code": null,
"e": 34835,
"s": 34481,
"text": "Public modifier is accessible from anywhere in the project workspace. If no access modifier is specified, then by default it will be in the public scope. In all our previous examples, we have not mentioned any modifier, hence, all of them are in the public scope. Following is an example to understand more on how to declare a public variable or method."
},
{
"code": null,
"e": 34900,
"s": 34835,
"text": "class publicExample {\n val i = 1\n fun doSomething() {\n }\n}"
},
{
"code": null,
"e": 35018,
"s": 34900,
"text": "In the above example, we have not mentioned any modifier, thus all these methods and variables are by default public."
},
{
"code": null,
"e": 35386,
"s": 35018,
"text": "In this chapter, we will learn about another new feature of Kotlin named “Extension”. Using extension, we will be able to add or remove some method functionality even without inheriting or modifying them. Extensions are resolved statistically. It does not actually modify the existing class, but it creates a callable function that can be called with a dot operation."
},
{
"code": null,
"e": 35565,
"s": 35386,
"text": "In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level."
},
{
"code": null,
"e": 36039,
"s": 35565,
"text": "class Alien {\n var skills : String = \"null\"\n\t\n fun printMySkills() {\n print(skills)\n }\t\t\n}\nfun main(args: Array<String>) {\n var a1 = Alien()\n a1.skills = \"JAVA\"\n //a1.printMySkills()\n\t\n var a2 = Alien()\n a2.skills = \"SQL\"\n //a2.printMySkills()\n\t\n var a3 = Alien()\n a3.skills = a1.addMySkills(a2)\n a3.printMySkills()\n}\nfun Alien.addMySkills(a:Alien):String{\n var a4 = Alien()\n a4.skills = this.skills + \" \" +a.skills\n return a4.skills\n}"
},
{
"code": null,
"e": 36253,
"s": 36039,
"text": "In the above example, we don’t have any method inside “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension."
},
{
"code": null,
"e": 36328,
"s": 36253,
"text": "The above piece of code will generate the following output in the browser."
},
{
"code": null,
"e": 36338,
"s": 36328,
"text": "JAVA SQL\n"
},
{
"code": null,
"e": 36697,
"s": 36338,
"text": "Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the keyword “companion object”. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name. In the following example, we will create a “companion object”."
},
{
"code": null,
"e": 36903,
"s": 36697,
"text": "fun main(args: Array<String>) {\n println(\"Heyyy!!!\"+A.show())\n}\nclass A {\n companion object {\n fun show():String {\n return(\"You are learning Kotlin from TutorialsPoint.com\")\n }\n }\n}"
},
{
"code": null,
"e": 36975,
"s": 36903,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 37033,
"s": 36975,
"text": "Heyyy!!! You are learning Kotlin from TutorialsPoint.com\n"
},
{
"code": null,
"e": 37374,
"s": 37033,
"text": "The above example seems like static in Java, however, in real-time we are creating an object as a member variable of that same class. This is why it is also included under extension property and can be alternatively called as an object extension. You are basically extending the object of the same class to use some of the member functions."
},
{
"code": null,
"e": 37655,
"s": 37374,
"text": "In this chapter, we will learn more about Data classes of Kotlin programming language. A class can be marked as a Data class whenever it is marked as ”data”. This type of class can be used to hold the basic data apart. Other than this, it does not provide any other functionality."
},
{
"code": null,
"e": 38096,
"s": 37655,
"text": "All the data classes need to have one primary constructor and all the primary constructor should have at least one parameter. Whenever a class is marked as data, we can use some of the inbuilt function of that data class such as “toString()”,”hashCode()”, etc. Any data class cannot have a modifier like abstract and open or internal. Data class can be extended to other classes too. In the following example, we will create one data class."
},
{
"code": null,
"e": 38664,
"s": 38096,
"text": "fun main(args: Array<String>) {\n val book: Book = Book(\"Kotlin\", \"TutorialPoint.com\", 5)\n println(\"Name of the Book is--\"+book.name) // \"Kotlin\"\n println(\"Puclisher Name--\"+book.publisher) // \"TutorialPoint.com\"\n println(\"Review of the book is--\"+book.reviewScore) // 5\n book.reviewScore = 7\n println(\"Printing all the info all together--\"+book.toString()) \n //using inbuilt function of the data class \n \n println(\"Example of the hashCode function--\"+book.hashCode())\n}\n\ndata class Book(val name: String, val publisher: String, var reviewScore: Int)"
},
{
"code": null,
"e": 38868,
"s": 38664,
"text": "The above piece of code will yield the following output in the browser, where we have created one data class to hold some of the data, and from the main function we have accessed all of its data members."
},
{
"code": null,
"e": 39100,
"s": 38868,
"text": "Name of the Book is--\"Kotlin\"\nPuclisher Name--\"TutorialPoint.com\"\nReview of the book is--5\nPrinting all the info all together--(name-Kotlin, publisher-TutorialPoint.com, reviewScore-7)\nExample of the hashCode function---1753517245\n"
},
{
"code": null,
"e": 39621,
"s": 39100,
"text": "In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class."
},
{
"code": null,
"e": 40054,
"s": 39621,
"text": "sealed class MyExample {\n class OP1 : MyExample() // MyExmaple class can be of two types only\n class OP2 : MyExample()\n}\nfun main(args: Array<String>) {\n val obj: MyExample = MyExample.OP2() \n \n val output = when (obj) { // defining the object of the class depending on the inuputs \n is MyExample.OP1 -> \"Option One has been chosen\"\n is MyExample.OP2 -> \"option Two has been chosen\"\n }\n \n println(output)\n}"
},
{
"code": null,
"e": 40401,
"s": 40054,
"text": "In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output."
},
{
"code": null,
"e": 40564,
"s": 40401,
"text": "In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 40592,
"s": 40564,
"text": "option Two has been chosen\n"
},
{
"code": null,
"e": 41014,
"s": 40592,
"text": "Like Java, Kotlin provides higher order of variable typing called as Generics. In this chapter, we will learn how Kotlin implements Generics and how as a developer we can use those functionalities provided inside the generics library. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer."
},
{
"code": null,
"e": 41234,
"s": 41014,
"text": "In Kotlin, a class and a type are totally different concepts. As per the example, List is a class in Kotlin, whereas List<String> is a type in Kotlin. The following example depicts how generics is implemented in Kotlin."
},
{
"code": null,
"e": 41341,
"s": 41234,
"text": "fun main(args: Array<String>) {\n val integer: Int = 1\n val number: Number = integer\n print(number)\n}"
},
{
"code": null,
"e": 41607,
"s": 41341,
"text": "In the above code, we have declared one “integer” and later we have assigned that variable to a number variable. This is possible because “Int” is a subclass of Number class, hence the type conversion happens automatically at runtime and produces the output as “1”."
},
{
"code": null,
"e": 42022,
"s": 41607,
"text": "Let us learn something more about generics in Kotlin. It is better to go for generic data type whenever we are not sure about the data type we are going to use in the application. Generally, in Kotlin generics is defined by <T> where “T” stands for template, which can be determined dynamically by Kotlin complier. In the following example, we will see how to use generic data types in Kotlin programming language."
},
{
"code": null,
"e": 42256,
"s": 42022,
"text": "fun main(args: Array<String>) {\n var objet = genericsExample<String>(\"JAVA\")\n var objet1 = genericsExample<Int>(10)\n}\nclass genericsExample<T>(input:T) {\n init {\n println(\"I am getting called with the value \"+input)\n }\n}"
},
{
"code": null,
"e": 42669,
"s": 42256,
"text": "In the above piece of code, we are creating one class with generic return type, which is represented as <T>. Take a look at the main method, where we have dynamically defined its value at the run by proving the value type, while creating the object of this class. This is how generics is interpreted by Kotlin compiler. We will get the following output in the browser, once we run this code in our coding ground."
},
{
"code": null,
"e": 42748,
"s": 42669,
"text": "I am getting called with the value JAVA\nI am getting called with the value 10\n"
},
{
"code": null,
"e": 43047,
"s": 42748,
"text": "When we want to assign the generic type to any of its super type, then we need to use “out” keyword, and when we want to assign the generic type to any of its sub-type, then we need to use “in” keyword. In the following example, we will use “out” keyword. Similarly, you can try using “in” keyword."
},
{
"code": null,
"e": 43325,
"s": 43047,
"text": "fun main(args: Array<String>) {\n var objet1 = genericsExample<Int>(10)\n var object2 = genericsExample<Double>(10.00)\n println(objet1)\n println(object2)\n}\nclass genericsExample<out T>(input:T) {\n init {\n println(\"I am getting called with the value \"+input)\n }\n}"
},
{
"code": null,
"e": 43388,
"s": 43325,
"text": "The above code will yield the following output in the browser."
},
{
"code": null,
"e": 43517,
"s": 43388,
"text": "I am getting called with the value 10\nI am getting called with the value 10.0\ngenericsExample@28d93b30\ngenericsExample@1b6d3586\n"
},
{
"code": null,
"e": 43825,
"s": 43517,
"text": "Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin."
},
{
"code": null,
"e": 44206,
"s": 43825,
"text": "interface Base {\n fun printMe() //abstract method\n}\nclass BaseImpl(val x: Int) : Base {\n override fun printMe() { println(x) } //implementation of the method\n}\nclass Derived(b: Base) : Base by b // delegating the public method on the object b\n\nfun main(args: Array<String>) {\n val b = BaseImpl(10)\n Derived(b).printMe() // prints 10 :: accessing the printMe() method \n}"
},
{
"code": null,
"e": 44437,
"s": 44206,
"text": "In the example, we have one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()” and later from another class we are using this implementation using “by” keyword."
},
{
"code": null,
"e": 44509,
"s": 44437,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 44513,
"s": 44509,
"text": "10\n"
},
{
"code": null,
"e": 44729,
"s": 44513,
"text": "In the previous section, we have learned about the delegation design pattern using “by” keyword. In this section, we will learn about delegation of properties using some standard methods mentioned in Kotlin library."
},
{
"code": null,
"e": 45085,
"s": 44729,
"text": "Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them. In the following examples, we will use some standard delegation methodology provided by Kotlin and some standard library function while implementing delegation in our examples."
},
{
"code": null,
"e": 45317,
"s": 45085,
"text": "Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. Let us take a look at the following to understand how it works."
},
{
"code": null,
"e": 45429,
"s": 45317,
"text": "val myVar: String by lazy {\n \"Hello\"\n}\nfun main(args: Array<String>) {\n println(myVar +\" My dear friend\")\n}"
},
{
"code": null,
"e": 45644,
"s": 45429,
"text": "In the above piece of code, we are passing a variable “myVar” to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser."
},
{
"code": null,
"e": 45666,
"s": 45644,
"text": "Hello My dear friend\n"
},
{
"code": null,
"e": 45872,
"s": 45666,
"text": "Observable() takes two arguments to initialize the object and returns the same to the called function. In the following example, we will see how to use Observable() method in order to implement delegation."
},
{
"code": null,
"e": 46162,
"s": 45872,
"text": "import kotlin.properties.Delegates\nclass User {\n var name: String by Delegates.observable(\"Welcome to Tutorialspoint.com\") {\n prop, old, new ->\n println(\"$old -> $new\")\n }\n}\nfun main(args: Array<String>) {\n val user = User()\n user.name = \"first\"\n user.name = \"second\"\n}"
},
{
"code": null,
"e": 46234,
"s": 46162,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 46251,
"s": 46234,
"text": "first -> second\n"
},
{
"code": null,
"e": 46465,
"s": 46251,
"text": "In general, the syntax is the expression after the “by” keyword is delegated. The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class."
},
{
"code": null,
"e": 46514,
"s": 46465,
"text": "class Example {\n var p: String by Delegate()\n}"
},
{
"code": null,
"e": 46648,
"s": 46514,
"text": "For the above piece of code, following is the delegate class that we need to generate in order to assign the value in the variable p."
},
{
"code": null,
"e": 46985,
"s": 46648,
"text": "class Delegate {\n operator fun getValue(thisRef: Any?, property: KProperty<*>): String {\n return \"$thisRef, thank you for delegating '${property.name}' to me!\"\n }\n operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {\n println(\"$value has been assigned to '${property.name} in $thisRef.'\")\n }\n}"
},
{
"code": null,
"e": 47098,
"s": 46985,
"text": "While reading, getValue() method will be called and while setting the variable setValue() method will be called."
},
{
"code": null,
"e": 47389,
"s": 47098,
"text": "Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout the examples. Function is declared with the keyword “fun”. Like any other OOP, it also needs a return type and an option argument list."
},
{
"code": null,
"e": 47543,
"s": 47389,
"text": "In the following example, we are defining a function called MyFunction and from the main function we are calling this function and passing some argument."
},
{
"code": null,
"e": 47718,
"s": 47543,
"text": "fun main(args: Array<String>) {\n println(MyFunction(\"tutorialsPoint.com\"))\n}\nfun MyFunction(x: String): String {\n var c:String = \"Hey!! Welcome To ---\"\n return (c+x)\n}"
},
{
"code": null,
"e": 47790,
"s": 47718,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 47830,
"s": 47790,
"text": "Hey!! Welcome To ---tutorialsPoint.com\n"
},
{
"code": null,
"e": 47875,
"s": 47830,
"text": "The function should be declared as follows −"
},
{
"code": null,
"e": 47936,
"s": 47875,
"text": "fun <nameOfFunction>(<argument>:<argumentType>):<ReturnType>"
},
{
"code": null,
"e": 48011,
"s": 47936,
"text": "Following are some of the different types of function available in Kotlin."
},
{
"code": null,
"e": 48260,
"s": 48011,
"text": "Lambda is a high level function that drastically reduces the boiler plate code while declaring a function and defining the same. Kotlin allows you to define your own lambda. In Kotlin, you can declare your lambda and pass that lambda to a function."
},
{
"code": null,
"e": 48298,
"s": 48260,
"text": "Take a look at the following example."
},
{
"code": null,
"e": 48442,
"s": 48298,
"text": "fun main(args: Array<String>) {\n val mylambda :(String)->Unit = {s:String->print(s)}\n val v:String = \"TutorialsPoint.com\"\n mylambda(v)\n}"
},
{
"code": null,
"e": 48627,
"s": 48442,
"text": "In the above code, we have created our own lambda known as “mylambda” and we have passed one variable to this lambda, which is of type String and contains a value “TutorialsPoint.com”."
},
{
"code": null,
"e": 48699,
"s": 48627,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 48719,
"s": 48699,
"text": "TutorialsPoint.com\n"
},
{
"code": null,
"e": 48934,
"s": 48719,
"text": "The above example shows the basic of the lambda expression that we can use in Kotlin application. Now, we can pass a lambda to another function to get our output which makes the calling function an inline function."
},
{
"code": null,
"e": 48972,
"s": 48934,
"text": "Take a look at the following example."
},
{
"code": null,
"e": 49301,
"s": 48972,
"text": "fun main(args: Array<String>) {\n val mylambda:(String)->Unit = {s:String->print(s)}\n val v:String = \"TutorialsPoint.com\"\n myFun(v,mylambda) //passing lambda as a parameter of another function \n}\nfun myFun(a :String, action: (String)->Unit) { //passing lambda \n print(\"Heyyy!!!\")\n action(a)// call to lambda function\n}"
},
{
"code": null,
"e": 49514,
"s": 49301,
"text": "The above piece of code will yield the following output in the browser. Using inline function, we have passed a lambda as a parameter. Any other function can be made an inline function using the “inline” keyword."
},
{
"code": null,
"e": 49542,
"s": 49514,
"text": "Heyyy!!!TutorialsPoint.com\n"
},
{
"code": null,
"e": 49709,
"s": 49542,
"text": "Kotlin contains many features of other programming languages. It allows you to declare multiple variables at once. This technique is called Destructuring declaration."
},
{
"code": null,
"e": 49773,
"s": 49709,
"text": "Following is the basic syntax of the destructuring declaration."
},
{
"code": null,
"e": 49799,
"s": 49773,
"text": "val (name, age) = person\n"
},
{
"code": null,
"e": 49937,
"s": 49799,
"text": "In the above syntax, we have created an object and defined all of them together in a single statement. Later, we can use them as follows."
},
{
"code": null,
"e": 49964,
"s": 49937,
"text": "println(name)\nprintln(age)"
},
{
"code": null,
"e": 50186,
"s": 49964,
"text": "Now, let us see how we can use the same in our real-life application. Consider the following example where we are creating one Student class with some attributes and later we will be using them to print the object values."
},
{
"code": null,
"e": 50452,
"s": 50186,
"text": "fun main(args: Array<String>) {\n val s = Student(\"TutorialsPoint.com\",\"Kotlin\")\n val (name,subject) = s\n println(\"You are learning \"+subject+\" from \"+name)\n}\ndata class Student( val a :String,val b: String ){\n var name:String = a\n var subject:String = b\n}"
},
{
"code": null,
"e": 50524,
"s": 50452,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 50573,
"s": 50524,
"text": "You are learning Kotlin from TutorialsPoint.com\n"
},
{
"code": null,
"e": 51010,
"s": 50573,
"text": "Exception handling is a very important part of a programming language. This technique restricts our application from generating the wrong output at runtime. In this chapter, we will learn how to handle runtime exception in Kotlin. The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin."
},
{
"code": null,
"e": 51260,
"s": 51010,
"text": "fun main(args: Array<String>) {\n try {\n val myVar:Int = 12;\n val v:String = \"Tutorialspoint.com\";\n v.toInt();\n } catch(e:Exception) {\n e.printStackTrace();\n } finally {\n println(\"Exception Handeling in Kotlin\");\n }\n}"
},
{
"code": null,
"e": 51454,
"s": 51260,
"text": "In the above piece of code, we have declared a String and later tied that string into the integer, which is actually a runtime exception. Hence, we will get the following output in the browser."
},
{
"code": null,
"e": 51505,
"s": 51454,
"text": "val myVar:Int = 12;\nException Handeling in Kotlin\n"
}
] |
How to Remove Time from Date/Timestamp in Excel?
|
20 May, 2021
Timestamp stores a combined Date and Time value. In this article, we will look at how we can create Timestamp and remove Time from Date in Excel.
To do so follow the steps below:
Step 1: Formatting data to create a timestamp.
Select the cell, right-click on it choose Format Cells...
Step 2: Then in the Formal Cells box select Custom in Category and in the type select dd-mm-yyyy hh:mm, and then click Ok.
Then, we will enter our date with time in the cell.
Step 1: Highlight the cells to remove time from date.
Step 2: Then right-click on it and choose Format Cells...
Step 3:-Then in the Format Cells box select Date in Category and select *14-03-2012 in Type, and then click Ok.
After that time is removed from the date.
Step 1: Highlight the cells to remove time from date.
Step 2: Then, click to Home on the Ribbon. In the Editing group, click Find & Select.
Step 3: In the resulting menu click Replace...
Step 4: Then in Find and Replace box enter the space bar and * in Find what box and leave a blank in Replace with box, then click Replace All.
After that time is removed from the date.
Step 1: Highlight the cells to remove time from date.
Step 2: Press Alt + F11 then a Microsoft Visual Basic for Applications window will be displayed and then click Insert.
Step 3: Then in the resulting menu click Module.
Step 4: In the Module write the following code.
Step 5: Then, click on the red marked button as shown below to run the code.
Step 6: In the KutoolsforExcel box select the range from which we want to remove time and then click Ok.
After that time is removed from the date.
Step 1: Visit on the given link below to install Kutools for Excel
https://www.extendoffice.com/download/kutools-for-excel.html
Step 2: Then, click to Kutools on the Ribbon. In the Formula group, click Formula Helper.
Step 3: In the resulting menu click Formula Helper...
Step 4:- In the Formulas Helper box select Date in Formula Type then choose Remove time from data in choose a formula box then select the range from which we want to remove date in Date time box and then click Ok.
After that time is removed from the date.
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 Get Length of Array in Excel VBA?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Macros in Excel
Introduction to Excel Spreadsheet
How to Extract the Last Word From a Cell in Excel?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 201,
"s": 54,
"text": "Timestamp stores a combined Date and Time value. In this article, we will look at how we can create Timestamp and remove Time from Date in Excel. "
},
{
"code": null,
"e": 234,
"s": 201,
"text": "To do so follow the steps below:"
},
{
"code": null,
"e": 281,
"s": 234,
"text": "Step 1: Formatting data to create a timestamp."
},
{
"code": null,
"e": 339,
"s": 281,
"text": "Select the cell, right-click on it choose Format Cells..."
},
{
"code": null,
"e": 462,
"s": 339,
"text": "Step 2: Then in the Formal Cells box select Custom in Category and in the type select dd-mm-yyyy hh:mm, and then click Ok."
},
{
"code": null,
"e": 514,
"s": 462,
"text": "Then, we will enter our date with time in the cell."
},
{
"code": null,
"e": 568,
"s": 514,
"text": "Step 1: Highlight the cells to remove time from date."
},
{
"code": null,
"e": 626,
"s": 568,
"text": "Step 2: Then right-click on it and choose Format Cells..."
},
{
"code": null,
"e": 738,
"s": 626,
"text": "Step 3:-Then in the Format Cells box select Date in Category and select *14-03-2012 in Type, and then click Ok."
},
{
"code": null,
"e": 780,
"s": 738,
"text": "After that time is removed from the date."
},
{
"code": null,
"e": 834,
"s": 780,
"text": "Step 1: Highlight the cells to remove time from date."
},
{
"code": null,
"e": 920,
"s": 834,
"text": "Step 2: Then, click to Home on the Ribbon. In the Editing group, click Find & Select."
},
{
"code": null,
"e": 967,
"s": 920,
"text": "Step 3: In the resulting menu click Replace..."
},
{
"code": null,
"e": 1110,
"s": 967,
"text": "Step 4: Then in Find and Replace box enter the space bar and * in Find what box and leave a blank in Replace with box, then click Replace All."
},
{
"code": null,
"e": 1152,
"s": 1110,
"text": "After that time is removed from the date."
},
{
"code": null,
"e": 1206,
"s": 1152,
"text": "Step 1: Highlight the cells to remove time from date."
},
{
"code": null,
"e": 1326,
"s": 1206,
"text": "Step 2: Press Alt + F11 then a Microsoft Visual Basic for Applications window will be displayed and then click Insert."
},
{
"code": null,
"e": 1375,
"s": 1326,
"text": "Step 3: Then in the resulting menu click Module."
},
{
"code": null,
"e": 1423,
"s": 1375,
"text": "Step 4: In the Module write the following code."
},
{
"code": null,
"e": 1500,
"s": 1423,
"text": "Step 5: Then, click on the red marked button as shown below to run the code."
},
{
"code": null,
"e": 1605,
"s": 1500,
"text": "Step 6: In the KutoolsforExcel box select the range from which we want to remove time and then click Ok."
},
{
"code": null,
"e": 1647,
"s": 1605,
"text": "After that time is removed from the date."
},
{
"code": null,
"e": 1714,
"s": 1647,
"text": "Step 1: Visit on the given link below to install Kutools for Excel"
},
{
"code": null,
"e": 1775,
"s": 1714,
"text": "https://www.extendoffice.com/download/kutools-for-excel.html"
},
{
"code": null,
"e": 1865,
"s": 1775,
"text": "Step 2: Then, click to Kutools on the Ribbon. In the Formula group, click Formula Helper."
},
{
"code": null,
"e": 1919,
"s": 1865,
"text": "Step 3: In the resulting menu click Formula Helper..."
},
{
"code": null,
"e": 2133,
"s": 1919,
"text": "Step 4:- In the Formulas Helper box select Date in Formula Type then choose Remove time from data in choose a formula box then select the range from which we want to remove date in Date time box and then click Ok."
},
{
"code": null,
"e": 2175,
"s": 2133,
"text": "After that time is removed from the date."
},
{
"code": null,
"e": 2182,
"s": 2175,
"text": "Picked"
},
{
"code": null,
"e": 2188,
"s": 2182,
"text": "Excel"
},
{
"code": null,
"e": 2286,
"s": 2188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2324,
"s": 2286,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 2365,
"s": 2324,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 2397,
"s": 2365,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 2452,
"s": 2397,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 2480,
"s": 2452,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 2520,
"s": 2480,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 2578,
"s": 2520,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 2594,
"s": 2578,
"text": "Macros in Excel"
},
{
"code": null,
"e": 2628,
"s": 2594,
"text": "Introduction to Excel Spreadsheet"
}
] |
Fix Error 1136: Column count doesn't match value count at row 1?
|
You may get tis value, if you are missing the value for auto_increment column. The error is as follows −
mysql> insert into DemoTable1353 values('Chris',23);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
You need to provide the value for auto_increment or leave it to automatic generation.
Let us see an example and create a table −
mysql> create table DemoTable1353
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(20),
-> Age int,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command. We haven’t inserted auto increment value and it will generate on its own −
mysql> insert into DemoTable1353(Name,Age) values('Chris',23);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable1353(Name,Age) values('David',21);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1353(Name,Age) values('Bob',24);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1353(Name,Age) values('John',47);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1353;
This will produce the following output −
+----+-------+------+
| Id | Name | Age |
+----+-------+------+
| 1 | Chris | 23 |
| 2 | David | 21 |
| 3 | Bob | 24 |
| 4 | John | 47 |
+----+-------+------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1292,
"s": 1187,
"text": "You may get tis value, if you are missing the value for auto_increment column. The error is as follows −"
},
{
"code": null,
"e": 1413,
"s": 1292,
"text": "mysql> insert into DemoTable1353 values('Chris',23);\nERROR 1136 (21S01): Column count doesn't match value count at row 1"
},
{
"code": null,
"e": 1499,
"s": 1413,
"text": "You need to provide the value for auto_increment or leave it to automatic generation."
},
{
"code": null,
"e": 1542,
"s": 1499,
"text": "Let us see an example and create a table −"
},
{
"code": null,
"e": 1735,
"s": 1542,
"text": "mysql> create table DemoTable1353\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(20),\n -> Age int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1865,
"s": 1735,
"text": "Insert some records in the table using insert command. We haven’t inserted auto increment value and it will generate on its own −"
},
{
"code": null,
"e": 2258,
"s": 1865,
"text": "mysql> insert into DemoTable1353(Name,Age) values('Chris',23);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable1353(Name,Age) values('David',21);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1353(Name,Age) values('Bob',24);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1353(Name,Age) values('John',47);\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 2318,
"s": 2258,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2354,
"s": 2318,
"text": "mysql> select * from DemoTable1353;"
},
{
"code": null,
"e": 2395,
"s": 2354,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2596,
"s": 2395,
"text": "+----+-------+------+\n| Id | Name | Age |\n+----+-------+------+\n| 1 | Chris | 23 |\n| 2 | David | 21 |\n| 3 | Bob | 24 |\n| 4 | John | 47 |\n+----+-------+------+\n4 rows in set (0.00 sec)"
}
] |
strftime() function in C/C++
|
16 Apr, 2021
strftime() is a function in C which is used to format date and time. It comes under the header file time.h, which also contains a structure named struct tm which is used to hold the time and date. The syntax of strftime() is as shown below :
size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);
strftime() function formats the broken-down time tm according to the formatting rules specified in format and store it in character array s.Some format specifiers for strftime() are shown as follows : %x = Preferred date representation %I = Hour as a decimal number (12-hour clock). %M = Minutes in decimal ranging from 00 to 59. %p = Either “AM” or “PM” according to the given time value, etc. %a = Abbreviated weekday name
%^a = Abbreviated weekday name in capital letters%A = Full weekday name %b = Abbreviated month name
%^b = Abbreviated month name in capital letters%B = Full month name March %c = Date and time representation %d = Day of the month (01-31) %H = Hour in 24h format (00-23) %I = Hour in 12h format (01-12) %j = Day of the year (001-366) %m = Month as a decimal number (01-12) %M = Minute (00-59)Structure struct tm is defined in time.h as follows :
struct tm
{
int tm_sec; // seconds
int tm_min; // minutes
int tm_hour; // hours
int tm_mday; // day of the month
int tm_mon; // month
int tm_year; // The number of years since 1900
int tm_wday; // day of the week
int tm_yday; // day in the year
int tm_isdst; // daylight saving time
};
C
// C program to demonstrate the// working of strftime()#include <stdlib.h>#include <stdio.h>#include <time.h>#define Size 50 int main (){ time_t t ; struct tm *tmp ; char MY_TIME[Size]; time( &t ); //localtime() uses the time pointed by t , // to fill a tm structure with the // values that represent the // corresponding local time. tmp = localtime( &t ); // using strftime to display time strftime(MY_TIME, sizeof(MY_TIME), "%x - %I:%M%p", tmp); printf("Formatted date & time : %s\n", MY_TIME ); return(0);}
Formatted date & time : 03/20/17 - 02:55PM
Why and when do we use strftime() ?
When we are making a software/application which will output the current time and most important in many different formats on the user’s demand. Then in that case we will use this function. Its specialty is that we can display date and time in many different formats.Reference: http://man7.org/linux/man-pages/man3/strftime.3.html>Linux Man PageThis article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shramithg97
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 296,
"s": 52,
"text": "strftime() is a function in C which is used to format date and time. It comes under the header file time.h, which also contains a structure named struct tm which is used to hold the time and date. The syntax of strftime() is as shown below : "
},
{
"code": null,
"e": 419,
"s": 296,
"text": "size_t strftime(char *s, size_t max, const char *format, \n const struct tm *tm); "
},
{
"code": null,
"e": 845,
"s": 419,
"text": "strftime() function formats the broken-down time tm according to the formatting rules specified in format and store it in character array s.Some format specifiers for strftime() are shown as follows : %x = Preferred date representation %I = Hour as a decimal number (12-hour clock). %M = Minutes in decimal ranging from 00 to 59. %p = Either “AM” or “PM” according to the given time value, etc. %a = Abbreviated weekday name "
},
{
"code": null,
"e": 946,
"s": 845,
"text": "%^a = Abbreviated weekday name in capital letters%A = Full weekday name %b = Abbreviated month name "
},
{
"code": null,
"e": 1293,
"s": 946,
"text": "%^b = Abbreviated month name in capital letters%B = Full month name March %c = Date and time representation %d = Day of the month (01-31) %H = Hour in 24h format (00-23) %I = Hour in 12h format (01-12) %j = Day of the year (001-366) %m = Month as a decimal number (01-12) %M = Minute (00-59)Structure struct tm is defined in time.h as follows : "
},
{
"code": null,
"e": 1676,
"s": 1293,
"text": "struct tm \n{\n int tm_sec; // seconds\n int tm_min; // minutes\n int tm_hour; // hours\n int tm_mday; // day of the month\n int tm_mon; // month\n int tm_year; // The number of years since 1900\n int tm_wday; // day of the week\n int tm_yday; // day in the year\n int tm_isdst; // daylight saving time \n};"
},
{
"code": null,
"e": 1680,
"s": 1678,
"text": "C"
},
{
"code": "// C program to demonstrate the// working of strftime()#include <stdlib.h>#include <stdio.h>#include <time.h>#define Size 50 int main (){ time_t t ; struct tm *tmp ; char MY_TIME[Size]; time( &t ); //localtime() uses the time pointed by t , // to fill a tm structure with the // values that represent the // corresponding local time. tmp = localtime( &t ); // using strftime to display time strftime(MY_TIME, sizeof(MY_TIME), \"%x - %I:%M%p\", tmp); printf(\"Formatted date & time : %s\\n\", MY_TIME ); return(0);}",
"e": 2249,
"s": 1680,
"text": null
},
{
"code": null,
"e": 2292,
"s": 2249,
"text": "Formatted date & time : 03/20/17 - 02:55PM"
},
{
"code": null,
"e": 2328,
"s": 2292,
"text": "Why and when do we use strftime() ?"
},
{
"code": null,
"e": 3101,
"s": 2328,
"text": "When we are making a software/application which will output the current time and most important in many different formats on the user’s demand. Then in that case we will use this function. Its specialty is that we can display date and time in many different formats.Reference: http://man7.org/linux/man-pages/man3/strftime.3.html>Linux Man PageThis article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3113,
"s": 3101,
"text": "shramithg97"
},
{
"code": null,
"e": 3125,
"s": 3113,
"text": "CPP-Library"
},
{
"code": null,
"e": 3136,
"s": 3125,
"text": "C Language"
},
{
"code": null,
"e": 3140,
"s": 3136,
"text": "C++"
},
{
"code": null,
"e": 3144,
"s": 3140,
"text": "CPP"
}
] |
Program to convert IP address to hexadecimal
|
02 Dec, 2021
Given an IP Address and task is to change the IP address equivalent the hexadecimal value.Examples:
Input : 127.0.0.1
Output : 0x7f000001
Input : 172.31.0.2
Output : 0xac1f0002
Explanationusing the Library function to convert the IP address to convert into the hexadecimal value we use ” arpa/inet.h “ header file. The inet_addr() function shall convert the string in the standard IPv4 dotted decimal notation, to an integer value suitable for use as an Internet address.
// C++ program for IP to// hexadecimal conversion#include <arpa/inet.h>#include <iostream>#include <string.h>using namespace std; // function for reverse hexadecimal numbervoid reverse(char* str){ // l for swap with index 2 int l = 2; int r = strlen(str) - 2; // swap with in two-2 pair while (l < r) { swap(str[l++], str[r++]); swap(str[l++], str[r]); r = r - 3; }} // function to conversion and print// the hexadecimal valuevoid ipToHexa(int addr){ char str[15]; // convert integer to string for reverse sprintf(str, "0x%08x", addr); // reverse for get actual hexadecimal // number without reverse it will // print 0x0100007f for 127.0.0.1 reverse(str); // print string cout << str << "\n";} // Driver codeint main(){ // The inet_addr() function convert string // in to standard IPv4 dotted decimal notation int addr = inet_addr("127.0.0.1"); ipToHexa(addr); return 0;}
Output:-
0x7f000001
gulshankumarar231
C-String
C++ Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Different ways to print elements of vector
Dynamic _Cast in C++
How to convert a Vector to Set in C++
Why it is important to write "using namespace std" in C++ program?
string::npos in C++ with Examples
Maximum value of long long int in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "Given an IP Address and task is to change the IP address equivalent the hexadecimal value.Examples:"
},
{
"code": null,
"e": 236,
"s": 154,
"text": "Input : 127.0.0.1\nOutput : 0x7f000001\n\nInput : 172.31.0.2\nOutput : 0xac1f0002\n\n"
},
{
"code": null,
"e": 531,
"s": 236,
"text": "Explanationusing the Library function to convert the IP address to convert into the hexadecimal value we use ” arpa/inet.h “ header file. The inet_addr() function shall convert the string in the standard IPv4 dotted decimal notation, to an integer value suitable for use as an Internet address."
},
{
"code": "// C++ program for IP to// hexadecimal conversion#include <arpa/inet.h>#include <iostream>#include <string.h>using namespace std; // function for reverse hexadecimal numbervoid reverse(char* str){ // l for swap with index 2 int l = 2; int r = strlen(str) - 2; // swap with in two-2 pair while (l < r) { swap(str[l++], str[r++]); swap(str[l++], str[r]); r = r - 3; }} // function to conversion and print// the hexadecimal valuevoid ipToHexa(int addr){ char str[15]; // convert integer to string for reverse sprintf(str, \"0x%08x\", addr); // reverse for get actual hexadecimal // number without reverse it will // print 0x0100007f for 127.0.0.1 reverse(str); // print string cout << str << \"\\n\";} // Driver codeint main(){ // The inet_addr() function convert string // in to standard IPv4 dotted decimal notation int addr = inet_addr(\"127.0.0.1\"); ipToHexa(addr); return 0;}",
"e": 1501,
"s": 531,
"text": null
},
{
"code": null,
"e": 1510,
"s": 1501,
"text": "Output:-"
},
{
"code": null,
"e": 1522,
"s": 1510,
"text": "0x7f000001\n"
},
{
"code": null,
"e": 1540,
"s": 1522,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 1549,
"s": 1540,
"text": "C-String"
},
{
"code": null,
"e": 1562,
"s": 1549,
"text": "C++ Programs"
},
{
"code": null,
"e": 1581,
"s": 1562,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1679,
"s": 1581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1720,
"s": 1679,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 1779,
"s": 1720,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 1800,
"s": 1779,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 1812,
"s": 1800,
"text": "cout in C++"
},
{
"code": null,
"e": 1855,
"s": 1812,
"text": "Different ways to print elements of vector"
},
{
"code": null,
"e": 1876,
"s": 1855,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 1914,
"s": 1876,
"text": "How to convert a Vector to Set in C++"
},
{
"code": null,
"e": 1981,
"s": 1914,
"text": "Why it is important to write \"using namespace std\" in C++ program?"
},
{
"code": null,
"e": 2015,
"s": 1981,
"text": "string::npos in C++ with Examples"
}
] |
list pop_back() function in C++ STL
|
13 Jun, 2022
The list::pop_back() is a built-in function in C++ STL which is used to remove an element from the back of a list container. That is, this function deletes the last element of a list container. This function thus decreases the size of the container by 1 as it deletes an element from the end of list. Syntax:
list_name.pop_back();
Parameters: The function does not accept any parameter. Return Value: This function does not returns anything. Below program illustrate the list::pop_back() function in C++ STL:
CPP
// CPP program to illustrate the// list::pop_back() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Adding elements to the list // using push_back() demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // Initial List: cout << "Initial List: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; // removing an element from the end of List // using pop_back demoList.pop_back(); // List after removing element from end cout << "\n\nList after removing an element from end: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; return 0;}
Initial List: 10 20 30 40
List after removing an element from end: 10 20 30
Time Complexity: O(1)
Auxiliary Space: O(1)
utkarshgupta110092
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
Substring in C++
C++ Classes and Objects
Object Oriented Programming in C++
Sorting a vector in C++
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 362,
"s": 53,
"text": "The list::pop_back() is a built-in function in C++ STL which is used to remove an element from the back of a list container. That is, this function deletes the last element of a list container. This function thus decreases the size of the container by 1 as it deletes an element from the end of list. Syntax:"
},
{
"code": null,
"e": 384,
"s": 362,
"text": "list_name.pop_back();"
},
{
"code": null,
"e": 563,
"s": 384,
"text": "Parameters: The function does not accept any parameter. Return Value: This function does not returns anything. Below program illustrate the list::pop_back() function in C++ STL: "
},
{
"code": null,
"e": 567,
"s": 563,
"text": "CPP"
},
{
"code": "// CPP program to illustrate the// list::pop_back() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Adding elements to the list // using push_back() demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // Initial List: cout << \"Initial List: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << \" \"; // removing an element from the end of List // using pop_back demoList.pop_back(); // List after removing element from end cout << \"\\n\\nList after removing an element from end: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << \" \"; return 0;}",
"e": 1282,
"s": 567,
"text": null
},
{
"code": null,
"e": 1360,
"s": 1282,
"text": "Initial List: 10 20 30 40 \n\nList after removing an element from end: 10 20 30"
},
{
"code": null,
"e": 1382,
"s": 1360,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 1404,
"s": 1382,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1423,
"s": 1404,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 1437,
"s": 1423,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1446,
"s": 1437,
"text": "cpp-list"
},
{
"code": null,
"e": 1450,
"s": 1446,
"text": "STL"
},
{
"code": null,
"e": 1454,
"s": 1450,
"text": "C++"
},
{
"code": null,
"e": 1458,
"s": 1454,
"text": "STL"
},
{
"code": null,
"e": 1462,
"s": 1458,
"text": "CPP"
},
{
"code": null,
"e": 1560,
"s": 1462,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1587,
"s": 1560,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1630,
"s": 1587,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1664,
"s": 1630,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1689,
"s": 1664,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1708,
"s": 1689,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 1762,
"s": 1708,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1779,
"s": 1762,
"text": "Substring in C++"
},
{
"code": null,
"e": 1803,
"s": 1779,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 1838,
"s": 1803,
"text": "Object Oriented Programming in C++"
}
] |
Rakuten India Interview Experience | On-Campus 2021 - GeeksforGeeks
|
23 Feb, 2021
Basic Information about the Process
Rakuten India visited our campus for the recruitment process, two times in one placement season. First time in the month of November 2020 and the second time in January 2021. I was part of the process that happened in January. They came for a Technical Intern position with performance-based conversion (PPO).
First Round (Test on HackerEarth): First round consists of 30 MCQ Aptitude questions (moderate level) along with 4 Coding Questions. 2 questions were leetcode easy, 1 was medium and 1 was hard.
Print the square for each test case. You are given a 4X4 matrix with elements in the range [0,15] denoting the initial configuration. 0 denotes an empty cell You can shift the elements that are adjacent to the empty cell into the empty cell Write a program to check if you can reach a final configuration from the initial configuration by shifting the adjacent elements of the initial configuration one at a time to 0.Final Configuration:1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0 Input Format: First line- T.The number of test cases. Each test case consists of a 4X4 matrix.Output Format: Print YES if you can reach a final configuration from the initial configuration, else print NO You are given N positive numbers A1... A2... An and you have to calculate the total sum of the floor(Ai/Aj) for each pair of Indices i and j. where (1 < i, j<=N)There are N types of books and an array A. Each element of that array i.e. A[i] denotes the number of books in each type. All books of all types are of equal thickness The books have to be stacked in such a manner that each stack has one specific kind of book and an equal number of those books.Write a program to print the maximum number of books that can be placed in each stack such that each stack has the same height and same kind of book. Input Format First line- N Second line N space-separated integers (denoting books of each type) Output format: Print the maximum number of books in each stack such that each stack will have the same height.
Print the square for each test case.
You are given a 4X4 matrix with elements in the range [0,15] denoting the initial configuration. 0 denotes an empty cell You can shift the elements that are adjacent to the empty cell into the empty cell Write a program to check if you can reach a final configuration from the initial configuration by shifting the adjacent elements of the initial configuration one at a time to 0.Final Configuration:1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0 Input Format: First line- T.The number of test cases. Each test case consists of a 4X4 matrix.Output Format: Print YES if you can reach a final configuration from the initial configuration, else print NO
Final Configuration:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
Input Format:
First line- T.
The number of test cases. Each test case consists of a 4X4 matrix.
Output Format: Print YES if you can reach a final configuration from the initial configuration, else print NO
You are given N positive numbers A1... A2... An and you have to calculate the total sum of the floor(Ai/Aj) for each pair of Indices i and j. where (1 < i, j<=N)
There are N types of books and an array A. Each element of that array i.e. A[i] denotes the number of books in each type. All books of all types are of equal thickness The books have to be stacked in such a manner that each stack has one specific kind of book and an equal number of those books.Write a program to print the maximum number of books that can be placed in each stack such that each stack has the same height and same kind of book. Input Format First line- N Second line N space-separated integers (denoting books of each type) Output format: Print the maximum number of books in each stack such that each stack will have the same height.
Write a program to print the maximum number of books that can be placed in each stack such that each stack has the same height and same kind of book.
Input Format
First line- N
Second line N space-separated integers (denoting books of each type)
Output format: Print the maximum number of books in each stack such that each stack will have the same height.
Note: You need to solve a minimum of 3 questions out of 4 to qualify for the next round.
Second Round (Interview-1 Technical Round on Zoom): It was a panel of two members, the interview was of 45 minutes. It started with the introduction of the candidate, followed by further questions. Questions were asked from Object-Oriented Programming (Abstraction, Multiple Inheritance in Java, Encapsulation and Collection Framework (List, Maps, and Set)0, followed by a few more questions from Summer Internship, and personal projects related questions. A few more questions from data structures, testing-related questions, how testing happens in Software Designing, and one or two real-life questions to create test cases for real-world machines).
Note: Well research about the post, and panel you’re going to interact with. Read about it in detail. Answer in a lighter mood with full confidence. Prepare everything you wrote in your resume.
Third Round (Interview-II Technical & HR Round Mixed on Zoom): It was again with the panel of two members (different from the 1st Round), It was taken by the Manager/Senior Technical Lead. It was of 40 minutes. Started with basic light conversations, the place I belong to, extra-curricular activities, and so on. The manager will ask you the questions related to the profile you were applying for and the expertise you mentioned in your resume. He asked me about a few testing and SDLC-related questions, gave a real-world problem and I have to design the test cases for it. Then he asked me to share my screen and to code on Eclipse. He gave me two problems, one was to find the elements of the duplicate characters in a string with multiple added tricky layers. And another question was to find the sub-array sum to a target sum. Both the code ran completely with one or two little mistakes.
Note: Try solving problems as much as possible on LeetCode and HackerRank. Use GeekforGeeks for DS-related questions.
Final Result: Selected for 6 months Internship.
Marketing
On-Campus
Rakuten
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1(Off-Campus)
Zoho Interview | Set 1 (On-Campus)
Infosys DSE Interview Experience 2021
|
[
{
"code": null,
"e": 25150,
"s": 25122,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 25186,
"s": 25150,
"text": "Basic Information about the Process"
},
{
"code": null,
"e": 25499,
"s": 25186,
"text": "Rakuten India visited our campus for the recruitment process, two times in one placement season. First time in the month of November 2020 and the second time in January 2021. I was part of the process that happened in January. They came for a Technical Intern position with performance-based conversion (PPO). "
},
{
"code": null,
"e": 25694,
"s": 25499,
"text": "First Round (Test on HackerEarth): First round consists of 30 MCQ Aptitude questions (moderate level) along with 4 Coding Questions. 2 questions were leetcode easy, 1 was medium and 1 was hard. "
},
{
"code": null,
"e": 27205,
"s": 25694,
"text": "Print the square for each test case. You are given a 4X4 matrix with elements in the range [0,15] denoting the initial configuration. 0 denotes an empty cell You can shift the elements that are adjacent to the empty cell into the empty cell Write a program to check if you can reach a final configuration from the initial configuration by shifting the adjacent elements of the initial configuration one at a time to 0.Final Configuration:1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 0 Input Format: First line- T.The number of test cases. Each test case consists of a 4X4 matrix.Output Format: Print YES if you can reach a final configuration from the initial configuration, else print NO You are given N positive numbers A1... A2... An and you have to calculate the total sum of the floor(Ai/Aj) for each pair of Indices i and j. where (1 < i, j<=N)There are N types of books and an array A. Each element of that array i.e. A[i] denotes the number of books in each type. All books of all types are of equal thickness The books have to be stacked in such a manner that each stack has one specific kind of book and an equal number of those books.Write a program to print the maximum number of books that can be placed in each stack such that each stack has the same height and same kind of book. Input Format First line- N Second line N space-separated integers (denoting books of each type) Output format: Print the maximum number of books in each stack such that each stack will have the same height."
},
{
"code": null,
"e": 27243,
"s": 27205,
"text": "Print the square for each test case. "
},
{
"code": null,
"e": 27901,
"s": 27243,
"text": "You are given a 4X4 matrix with elements in the range [0,15] denoting the initial configuration. 0 denotes an empty cell You can shift the elements that are adjacent to the empty cell into the empty cell Write a program to check if you can reach a final configuration from the initial configuration by shifting the adjacent elements of the initial configuration one at a time to 0.Final Configuration:1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 0 Input Format: First line- T.The number of test cases. Each test case consists of a 4X4 matrix.Output Format: Print YES if you can reach a final configuration from the initial configuration, else print NO "
},
{
"code": null,
"e": 27922,
"s": 27901,
"text": "Final Configuration:"
},
{
"code": null,
"e": 27974,
"s": 27922,
"text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 0 "
},
{
"code": null,
"e": 27989,
"s": 27974,
"text": "Input Format: "
},
{
"code": null,
"e": 28004,
"s": 27989,
"text": "First line- T."
},
{
"code": null,
"e": 28071,
"s": 28004,
"text": "The number of test cases. Each test case consists of a 4X4 matrix."
},
{
"code": null,
"e": 28183,
"s": 28071,
"text": "Output Format: Print YES if you can reach a final configuration from the initial configuration, else print NO "
},
{
"code": null,
"e": 28345,
"s": 28183,
"text": "You are given N positive numbers A1... A2... An and you have to calculate the total sum of the floor(Ai/Aj) for each pair of Indices i and j. where (1 < i, j<=N)"
},
{
"code": null,
"e": 29001,
"s": 28345,
"text": "There are N types of books and an array A. Each element of that array i.e. A[i] denotes the number of books in each type. All books of all types are of equal thickness The books have to be stacked in such a manner that each stack has one specific kind of book and an equal number of those books.Write a program to print the maximum number of books that can be placed in each stack such that each stack has the same height and same kind of book. Input Format First line- N Second line N space-separated integers (denoting books of each type) Output format: Print the maximum number of books in each stack such that each stack will have the same height."
},
{
"code": null,
"e": 29153,
"s": 29001,
"text": "Write a program to print the maximum number of books that can be placed in each stack such that each stack has the same height and same kind of book. "
},
{
"code": null,
"e": 29168,
"s": 29153,
"text": "Input Format "
},
{
"code": null,
"e": 29184,
"s": 29168,
"text": "First line- N "
},
{
"code": null,
"e": 29255,
"s": 29184,
"text": "Second line N space-separated integers (denoting books of each type) "
},
{
"code": null,
"e": 29366,
"s": 29255,
"text": "Output format: Print the maximum number of books in each stack such that each stack will have the same height."
},
{
"code": null,
"e": 29456,
"s": 29366,
"text": "Note: You need to solve a minimum of 3 questions out of 4 to qualify for the next round. "
},
{
"code": null,
"e": 30108,
"s": 29456,
"text": "Second Round (Interview-1 Technical Round on Zoom): It was a panel of two members, the interview was of 45 minutes. It started with the introduction of the candidate, followed by further questions. Questions were asked from Object-Oriented Programming (Abstraction, Multiple Inheritance in Java, Encapsulation and Collection Framework (List, Maps, and Set)0, followed by a few more questions from Summer Internship, and personal projects related questions. A few more questions from data structures, testing-related questions, how testing happens in Software Designing, and one or two real-life questions to create test cases for real-world machines)."
},
{
"code": null,
"e": 30302,
"s": 30108,
"text": "Note: Well research about the post, and panel you’re going to interact with. Read about it in detail. Answer in a lighter mood with full confidence. Prepare everything you wrote in your resume."
},
{
"code": null,
"e": 31198,
"s": 30302,
"text": "Third Round (Interview-II Technical & HR Round Mixed on Zoom): It was again with the panel of two members (different from the 1st Round), It was taken by the Manager/Senior Technical Lead. It was of 40 minutes. Started with basic light conversations, the place I belong to, extra-curricular activities, and so on. The manager will ask you the questions related to the profile you were applying for and the expertise you mentioned in your resume. He asked me about a few testing and SDLC-related questions, gave a real-world problem and I have to design the test cases for it. Then he asked me to share my screen and to code on Eclipse. He gave me two problems, one was to find the elements of the duplicate characters in a string with multiple added tricky layers. And another question was to find the sub-array sum to a target sum. Both the code ran completely with one or two little mistakes. "
},
{
"code": null,
"e": 31317,
"s": 31198,
"text": "Note: Try solving problems as much as possible on LeetCode and HackerRank. Use GeekforGeeks for DS-related questions. "
},
{
"code": null,
"e": 31366,
"s": 31317,
"text": "Final Result: Selected for 6 months Internship. "
},
{
"code": null,
"e": 31376,
"s": 31366,
"text": "Marketing"
},
{
"code": null,
"e": 31386,
"s": 31376,
"text": "On-Campus"
},
{
"code": null,
"e": 31394,
"s": 31386,
"text": "Rakuten"
},
{
"code": null,
"e": 31416,
"s": 31394,
"text": "Interview Experiences"
},
{
"code": null,
"e": 31514,
"s": 31416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31523,
"s": 31514,
"text": "Comments"
},
{
"code": null,
"e": 31536,
"s": 31523,
"text": "Old Comments"
},
{
"code": null,
"e": 31586,
"s": 31536,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 31622,
"s": 31586,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 31660,
"s": 31622,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 31698,
"s": 31660,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 31744,
"s": 31698,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 31809,
"s": 31744,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 31868,
"s": 31809,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 31918,
"s": 31868,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
},
{
"code": null,
"e": 31953,
"s": 31918,
"text": "Zoho Interview | Set 1 (On-Campus)"
}
] |
Enchanced Tabular Data Visualization (Pandas) | by Elena Kosourova | Towards Data Science
|
In this article, we’ll discuss some useful options and functions to efficiently visualize dataframes as a set of tabular data in pandas. Let’s start with creating a dataframe for our further experiments:
import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(20, 40))# Renaming columnsdf.columns = [x for x in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN']# Adding some missing values df.iloc[3,4] = np.nandf.iloc[2,0] = np.nandf.iloc[4,5] = np.nandf.iloc[0,6] = np.nandf.head()
Attention: the code from this article was run in pandas version 1.3.2. Some of the functions are quite new and will throw an error in the older versions.
Looking at the dataframe above, we might want to fix 2 things:
Display all the columns of the dataframe. For now, the columns from k to D inclusive are hidden.Limit the precision of float values.
Display all the columns of the dataframe. For now, the columns from k to D inclusive are hidden.
Limit the precision of float values.
Let’s check the default values for the number of columns displayed and the float precision:
print(pd.options.display.max_columns)print(pd.options.display.precision)Output:206
We want to display all the columns (len(df.columns)) and have a precision of 2 decimal points, so we have to re-assign both options:We want to display all the columns (len(df.columns)) and have a precision of 2 decimal points, so we have to re-assign both options:
pd.options.display.max_columns = len(df.columns)pd.options.display.precision = 2print(pd.options.display.max_columns)print(pd.options.display.precision)df.head()Output:402
Now that we can see the values in all the columns and in a more digestible form, another issue appeared: some float numbers are displayed in scientific notation (e.g. 7.85e-1 instead of 0.785). To fix it, we should explicitly assign the necessary format (in our case — 2 decimal points) to the float_format attribute:
pd.options.display.float_format = '{:.2f}'.formatdf.head()
For our next experiments, let’s slice out a smaller dataframe (df1) from the main one (df):
df1 = df.iloc[:5,:8]df1
We can want to hide the index or header (or both) from the dataframe. For this purpose, we should create an instance of the Styler class by using DataFrame.style attribute and apply to it the methods hide_index() or hide_columns(), correspondingly. We'll use this attribute for all our next experiments.
df1.style.hide_index()
df1.style.hide_columns()
Chaining these methods (df1.style.hide_index().hide_columns()) will hide both the index and header. We can also notice that NaN values are displayed as nan when using DataFrame.style attribute.
In some other cases, we might want, just the opposite, to always keep visible the index (or the header) when scrolling through the dataframe. It’s especially convenient for large dataframes, so let’s return to our original df. The method to use here is set_sticky(). Depending on what we want to stick, we should pass in axis='index' or axis='columns':
df.style.set_sticky(axis='index')
df.style.set_sticky(axis='columns')
To highlight null values, we can use a built-in function highlight_null():
df1.style.highlight_null()
The default color is red, but we can change it by passing in an optional parameter null_color. Also, it's possible to visualize the null values of only one or several selected columns (or rows). We use the subset parameter for it, passing in the name of the column (or the row index) or a list of names (indices):
df1.style.highlight_null(null_color='lime', subset=['e', 'g'])
To highlight minimum and maximum values in each column of the dataframe, we can apply the methods highlight_min() and highlight_max():
df1.style.highlight_min()
df1.style.highlight_max()
The default color can be changed by passing in an optional parameter color. Also here we can use the subset parameter to select only one or several columns to visualize minimum or maximum values. And of course, we can chain both methods:
df1.style.highlight_min(color='cyan', subset='d').highlight_max(color='magenta', subset='d')
By default, the minimum and maximum values are displayed by column. If we need such information by row, we have to specify axis='columns':
df1.style.highlight_min(axis='columns')
In this case, if we want to select only one or several rows instead of the whole dataframe, we should pass in the corresponding value for subset: the row index or indices.
Finally, it’s possible to highlight the values from a selected range using the highlight_between() method. Apart from the already familiar parameters color and subset, we have to assign the left and/or right parameters and, optionally, inclusive, which is 'both' by default (other possible values are 'neither', 'left', or 'right'):
df1.style.highlight_between(left=-0.1, right=0.1, inclusive='neither')
There are two curious methods for highlighting the cells or the text inside them in a gradient, heatmap-like style, based on a numeric scale of their values: background_gradient() and text_gradient(). Both methods require the installation of matplotlib (not necessarily import).
df1.style.background_gradient()
df1.style.text_gradient()
Apart from subset, we can tune the following parameters:
cmap — a matplotlib colormap ('PuBu' by default),
axis — coloring the values column-wise (axis='index'), row-wise (axis='columns'), or the whole dataframe (by default),
low, high — extending the range of the gradient at the low/high ends based on the corresponding fraction of the original data-based range,
vmin, vmax — defining a data value that corresponds to the colormap minimum/maximum value (by default, it will be the min/max data value),
text_color_threshold — only used in background_gradient(), determines light/dark change of text color to enchance text visibility across cell background colors (by default, 0.408).
Let’s try to adjust some of these parameters:
df1.style.text_gradient(cmap='cool', subset=3, axis='columns', vmin=-2)
There are many other ways to flexibly customize table visualization in Python: applying a more advanced text formatting, controlling data slicing, changing text font, modifying cell boundary properties, assigning hover effects, etc. In general, it’s possible to apply whatever function we need with any custom logic and, when using the DataFrame.style attribute, use a great variety of CSS styling elements. In this article, we considered some of the most common tasks, which, being used more often than others, resulted in creating built-in functions for these purposes, with a simple and clear syntax yet highly customizable outputs.
Thanks for reading!
You can find interesting also these articles:
|
[
{
"code": null,
"e": 376,
"s": 172,
"text": "In this article, we’ll discuss some useful options and functions to efficiently visualize dataframes as a set of tabular data in pandas. Let’s start with creating a dataframe for our further experiments:"
},
{
"code": null,
"e": 664,
"s": 376,
"text": "import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(20, 40))# Renaming columnsdf.columns = [x for x in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN']# Adding some missing values df.iloc[3,4] = np.nandf.iloc[2,0] = np.nandf.iloc[4,5] = np.nandf.iloc[0,6] = np.nandf.head()"
},
{
"code": null,
"e": 818,
"s": 664,
"text": "Attention: the code from this article was run in pandas version 1.3.2. Some of the functions are quite new and will throw an error in the older versions."
},
{
"code": null,
"e": 881,
"s": 818,
"text": "Looking at the dataframe above, we might want to fix 2 things:"
},
{
"code": null,
"e": 1014,
"s": 881,
"text": "Display all the columns of the dataframe. For now, the columns from k to D inclusive are hidden.Limit the precision of float values."
},
{
"code": null,
"e": 1111,
"s": 1014,
"text": "Display all the columns of the dataframe. For now, the columns from k to D inclusive are hidden."
},
{
"code": null,
"e": 1148,
"s": 1111,
"text": "Limit the precision of float values."
},
{
"code": null,
"e": 1240,
"s": 1148,
"text": "Let’s check the default values for the number of columns displayed and the float precision:"
},
{
"code": null,
"e": 1323,
"s": 1240,
"text": "print(pd.options.display.max_columns)print(pd.options.display.precision)Output:206"
},
{
"code": null,
"e": 1588,
"s": 1323,
"text": "We want to display all the columns (len(df.columns)) and have a precision of 2 decimal points, so we have to re-assign both options:We want to display all the columns (len(df.columns)) and have a precision of 2 decimal points, so we have to re-assign both options:"
},
{
"code": null,
"e": 1760,
"s": 1588,
"text": "pd.options.display.max_columns = len(df.columns)pd.options.display.precision = 2print(pd.options.display.max_columns)print(pd.options.display.precision)df.head()Output:402"
},
{
"code": null,
"e": 2078,
"s": 1760,
"text": "Now that we can see the values in all the columns and in a more digestible form, another issue appeared: some float numbers are displayed in scientific notation (e.g. 7.85e-1 instead of 0.785). To fix it, we should explicitly assign the necessary format (in our case — 2 decimal points) to the float_format attribute:"
},
{
"code": null,
"e": 2137,
"s": 2078,
"text": "pd.options.display.float_format = '{:.2f}'.formatdf.head()"
},
{
"code": null,
"e": 2229,
"s": 2137,
"text": "For our next experiments, let’s slice out a smaller dataframe (df1) from the main one (df):"
},
{
"code": null,
"e": 2253,
"s": 2229,
"text": "df1 = df.iloc[:5,:8]df1"
},
{
"code": null,
"e": 2557,
"s": 2253,
"text": "We can want to hide the index or header (or both) from the dataframe. For this purpose, we should create an instance of the Styler class by using DataFrame.style attribute and apply to it the methods hide_index() or hide_columns(), correspondingly. We'll use this attribute for all our next experiments."
},
{
"code": null,
"e": 2580,
"s": 2557,
"text": "df1.style.hide_index()"
},
{
"code": null,
"e": 2605,
"s": 2580,
"text": "df1.style.hide_columns()"
},
{
"code": null,
"e": 2799,
"s": 2605,
"text": "Chaining these methods (df1.style.hide_index().hide_columns()) will hide both the index and header. We can also notice that NaN values are displayed as nan when using DataFrame.style attribute."
},
{
"code": null,
"e": 3152,
"s": 2799,
"text": "In some other cases, we might want, just the opposite, to always keep visible the index (or the header) when scrolling through the dataframe. It’s especially convenient for large dataframes, so let’s return to our original df. The method to use here is set_sticky(). Depending on what we want to stick, we should pass in axis='index' or axis='columns':"
},
{
"code": null,
"e": 3186,
"s": 3152,
"text": "df.style.set_sticky(axis='index')"
},
{
"code": null,
"e": 3222,
"s": 3186,
"text": "df.style.set_sticky(axis='columns')"
},
{
"code": null,
"e": 3297,
"s": 3222,
"text": "To highlight null values, we can use a built-in function highlight_null():"
},
{
"code": null,
"e": 3324,
"s": 3297,
"text": "df1.style.highlight_null()"
},
{
"code": null,
"e": 3638,
"s": 3324,
"text": "The default color is red, but we can change it by passing in an optional parameter null_color. Also, it's possible to visualize the null values of only one or several selected columns (or rows). We use the subset parameter for it, passing in the name of the column (or the row index) or a list of names (indices):"
},
{
"code": null,
"e": 3701,
"s": 3638,
"text": "df1.style.highlight_null(null_color='lime', subset=['e', 'g'])"
},
{
"code": null,
"e": 3836,
"s": 3701,
"text": "To highlight minimum and maximum values in each column of the dataframe, we can apply the methods highlight_min() and highlight_max():"
},
{
"code": null,
"e": 3862,
"s": 3836,
"text": "df1.style.highlight_min()"
},
{
"code": null,
"e": 3888,
"s": 3862,
"text": "df1.style.highlight_max()"
},
{
"code": null,
"e": 4126,
"s": 3888,
"text": "The default color can be changed by passing in an optional parameter color. Also here we can use the subset parameter to select only one or several columns to visualize minimum or maximum values. And of course, we can chain both methods:"
},
{
"code": null,
"e": 4219,
"s": 4126,
"text": "df1.style.highlight_min(color='cyan', subset='d').highlight_max(color='magenta', subset='d')"
},
{
"code": null,
"e": 4358,
"s": 4219,
"text": "By default, the minimum and maximum values are displayed by column. If we need such information by row, we have to specify axis='columns':"
},
{
"code": null,
"e": 4398,
"s": 4358,
"text": "df1.style.highlight_min(axis='columns')"
},
{
"code": null,
"e": 4570,
"s": 4398,
"text": "In this case, if we want to select only one or several rows instead of the whole dataframe, we should pass in the corresponding value for subset: the row index or indices."
},
{
"code": null,
"e": 4903,
"s": 4570,
"text": "Finally, it’s possible to highlight the values from a selected range using the highlight_between() method. Apart from the already familiar parameters color and subset, we have to assign the left and/or right parameters and, optionally, inclusive, which is 'both' by default (other possible values are 'neither', 'left', or 'right'):"
},
{
"code": null,
"e": 4974,
"s": 4903,
"text": "df1.style.highlight_between(left=-0.1, right=0.1, inclusive='neither')"
},
{
"code": null,
"e": 5253,
"s": 4974,
"text": "There are two curious methods for highlighting the cells or the text inside them in a gradient, heatmap-like style, based on a numeric scale of their values: background_gradient() and text_gradient(). Both methods require the installation of matplotlib (not necessarily import)."
},
{
"code": null,
"e": 5285,
"s": 5253,
"text": "df1.style.background_gradient()"
},
{
"code": null,
"e": 5311,
"s": 5285,
"text": "df1.style.text_gradient()"
},
{
"code": null,
"e": 5368,
"s": 5311,
"text": "Apart from subset, we can tune the following parameters:"
},
{
"code": null,
"e": 5418,
"s": 5368,
"text": "cmap — a matplotlib colormap ('PuBu' by default),"
},
{
"code": null,
"e": 5537,
"s": 5418,
"text": "axis — coloring the values column-wise (axis='index'), row-wise (axis='columns'), or the whole dataframe (by default),"
},
{
"code": null,
"e": 5676,
"s": 5537,
"text": "low, high — extending the range of the gradient at the low/high ends based on the corresponding fraction of the original data-based range,"
},
{
"code": null,
"e": 5815,
"s": 5676,
"text": "vmin, vmax — defining a data value that corresponds to the colormap minimum/maximum value (by default, it will be the min/max data value),"
},
{
"code": null,
"e": 5996,
"s": 5815,
"text": "text_color_threshold — only used in background_gradient(), determines light/dark change of text color to enchance text visibility across cell background colors (by default, 0.408)."
},
{
"code": null,
"e": 6042,
"s": 5996,
"text": "Let’s try to adjust some of these parameters:"
},
{
"code": null,
"e": 6114,
"s": 6042,
"text": "df1.style.text_gradient(cmap='cool', subset=3, axis='columns', vmin=-2)"
},
{
"code": null,
"e": 6750,
"s": 6114,
"text": "There are many other ways to flexibly customize table visualization in Python: applying a more advanced text formatting, controlling data slicing, changing text font, modifying cell boundary properties, assigning hover effects, etc. In general, it’s possible to apply whatever function we need with any custom logic and, when using the DataFrame.style attribute, use a great variety of CSS styling elements. In this article, we considered some of the most common tasks, which, being used more often than others, resulted in creating built-in functions for these purposes, with a simple and clear syntax yet highly customizable outputs."
},
{
"code": null,
"e": 6770,
"s": 6750,
"text": "Thanks for reading!"
}
] |
How to add a paragraph in HTML?
|
Use the HTML <p> tag to add a paragraph in HTML. You can try to run the following code to implement <p> tag in HTML −
<!DOCTYPE html>
<html>
<head>
<title>HTML p Tag</title>
</head>
<body>
<p>This is demo text.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Use the HTML <p> tag to add a paragraph in HTML. You can try to run the following code to implement <p> tag in HTML −"
},
{
"code": null,
"e": 1317,
"s": 1180,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML p Tag</title>\n </head>\n <body>\n <p>This is demo text.</p>\n </body>\n</html>"
}
] |
What is $(window).load() method in jQuery?
|
The code which gets included inside $( window ).on( "load", function() { ... }) runs only once the entire page is ready (not only DOM).
Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.
You can try to run the following code to learn how to use $(window).load() method in jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("Image successfully loaded.");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/tutor_connect_home.jpg" alt="Tutor" width="280" height="236">
<p><strong>Note:</strong> The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1198,
"s": 1062,
"text": "The code which gets included inside $( window ).on( \"load\", function() { ... }) runs only once the entire page is ready (not only DOM)."
},
{
"code": null,
"e": 1357,
"s": 1198,
"text": "Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0."
},
{
"code": null,
"e": 1451,
"s": 1357,
"text": "You can try to run the following code to learn how to use $(window).load() method in jQuery −"
},
{
"code": null,
"e": 1461,
"s": 1451,
"text": "Live Demo"
},
{
"code": null,
"e": 2023,
"s": 1461,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"img\").load(function(){\n alert(\"Image successfully loaded.\");\n });\n});\n</script>\n</head>\n<body>\n\n<img src=\"/videotutorials/images/tutor_connect_home.jpg\" alt=\"Tutor\" width=\"280\" height=\"236\">\n\n<p><strong>Note:</strong> The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.</p>\n\n</body>\n</html>"
}
] |
Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix - GeeksforGeeks
|
31 Mar, 2022
Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples:
Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the absolute values of elements of row 1 except the diagonal element is 3 more than abs(arr[0][0]). 1 more than abs(arr[1][1]) in the second row and 1 more than abs(arr[2][2]) in the third row. Hence, 3 + 1 + 1 = 5Input: mat[][] = {{1, 2, 4, 0}, {1, 3, 4, 2}, {3, 3, 4, 2}, {-1, 0, 1, 4}} Output: 13
Approach:
A square matrix is said to be diagonally dominant matrix if for every row of the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum of the magnitudes of all the other (non-diagonal) entries in that row.
The minimum number of steps required to convert a given matrix into the diagonally dominant matrix can be calculated depending upon two case: If the sum of the absolute value of all elements of a row except diagonal element is greater than the absolute value of diagonal element then the difference between these two values will be added to the result.Else no need to add anything in the result as in that case row satisfies the condition for a diagonally dominant matrix.
If the sum of the absolute value of all elements of a row except diagonal element is greater than the absolute value of diagonal element then the difference between these two values will be added to the result.Else no need to add anything in the result as in that case row satisfies the condition for a diagonally dominant matrix.
If the sum of the absolute value of all elements of a row except diagonal element is greater than the absolute value of diagonal element then the difference between these two values will be added to the result.
Else no need to add anything in the result as in that case row satisfies the condition for a diagonally dominant matrix.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 3 // Function to return the minimum steps// required to convert the given matrix// to a Diagonally Dominant Matrixint findStepsForDDM(int arr[][N]){ int result = 0; // For each row for (int i = 0; i < N; i++) { // To store the sum of the current row int sum = 0; for (int j = 0; j < N; j++) sum += abs(arr[i][j]); // Remove the element of the current row // which lies on the main diagonal sum -= abs(arr[i][i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (abs(arr[i][i]) < abs(sum)) result += abs(abs(arr[i][i]) - abs(sum)); } return result;} // Driven codeint main(){ int arr[N][N] = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; cout << findStepsForDDM(arr); return 0;}
// Java implementation of the approachclass GFG{ final static int N = 3 ; // Function to return the minimum steps // required to convert the given matrix // to a Diagonally Dominant Matrix static int findStepsForDDM(int arr[][]) { int result = 0; // For each row for (int i = 0; i < N; i++) { // To store the sum of the current row int sum = 0; for (int j = 0; j < N; j++) sum += Math.abs(arr[i][j]); // Remove the element of the current row // which lies on the main diagonal sum -= Math.abs(arr[i][i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (Math.abs(arr[i][i]) < Math.abs(sum)) result += Math.abs(Math.abs(arr[i][i]) - Math.abs(sum)); } return result; } // Driven code public static void main (String[] args) { int arr[][] = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; System.out.println(findStepsForDDM(arr)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach N = 3 # Function to return the minimum steps# required to convert the given matrix# to a Diagonally Dominant Matrixdef findStepsForDDM(arr): result = 0 # For each row for i in range(N): # To store the sum of the current row sum = 0 for j in range(N): sum += abs(arr[i][j]) # Remove the element of the current row # which lies on the main diagonal sum -= abs(arr[i][i]) # Checking if the diagonal element is less # than the sum of non-diagonal element # then add their difference to the result if (abs(arr[i][i]) < abs(sum)): result += abs(abs(arr[i][i]) - abs(sum)) return result # Driver code arr= [ [ 3, -2, 1 ], [ 1, -3, 2 ], [ -1, 2, 4 ] ] print(findStepsForDDM(arr)) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{ static int N = 3 ; // Function to return the minimum steps // required to convert the given matrix // to a Diagonally Dominant Matrix static int findStepsForDDM(int [,]arr) { int result = 0; // For each row for (int i = 0; i < N; i++) { // To store the sum of the current row int sum = 0; for (int j = 0; j < N; j++) sum += Math.Abs(arr[i,j]); // Remove the element of the current row // which lies on the main diagonal sum -= Math.Abs(arr[i,i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (Math.Abs(arr[i,i]) < Math.Abs(sum)) result += Math.Abs(Math.Abs(arr[i,i]) - Math.Abs(sum)); } return result; } // Driven code static public void Main () { int [,]arr = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; Console.WriteLine(findStepsForDDM(arr)); }} // This code is contributed by ajit.
<script>// Java script implementation of the approachlet N = 3 ; // Function to return the minimum steps // required to convert the given matrix // to a Diagonally Dominant Matrix function findStepsForDDM(arr) { let result = 0; // For each row for (let i = 0; i < N; i++) { // To store the sum of the current row let sum = 0; for (let j = 0; j < N; j++) sum += Math.abs(arr[i][j]); // Remove the element of the current row // which lies on the main diagonal sum -= Math.abs(arr[i][i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (Math.abs(arr[i][i]) < Math.abs(sum)) result += Math.abs(Math.abs(arr[i][i]) - Math.abs(sum)); } return result; } // Driven code let arr = [[ 3, -2, 1 ], [ 1, -3, 2 ], [ -1, 2, 4 ]]; document.write(findStepsForDDM(arr)); // This code is contributed by mohan pavan </script>
0
Time complexity: O(N2)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
jit_t
Akanksha_Rai
pulamolusaimohan
rohitkumarsinghcna
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to multiply two matrices
Multiplication of two Matrices in Single line using Numpy in Python
Min Cost Path | DP-6
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Sudoku | Backtracking-7
The Celebrity Problem
Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)
Unique paths in a Grid with Obstacles
Mathematics | L U Decomposition of a System of Linear Equations
Program to find transpose of a matrix
|
[
{
"code": null,
"e": 24877,
"s": 24849,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 25108,
"s": 24877,
"text": "Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples: "
},
{
"code": null,
"e": 25478,
"s": 25108,
"text": "Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the absolute values of elements of row 1 except the diagonal element is 3 more than abs(arr[0][0]). 1 more than abs(arr[1][1]) in the second row and 1 more than abs(arr[2][2]) in the third row. Hence, 3 + 1 + 1 = 5Input: mat[][] = {{1, 2, 4, 0}, {1, 3, 4, 2}, {3, 3, 4, 2}, {-1, 0, 1, 4}} Output: 13 "
},
{
"code": null,
"e": 25492,
"s": 25480,
"text": "Approach: "
},
{
"code": null,
"e": 25732,
"s": 25492,
"text": "A square matrix is said to be diagonally dominant matrix if for every row of the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum of the magnitudes of all the other (non-diagonal) entries in that row."
},
{
"code": null,
"e": 26205,
"s": 25732,
"text": "The minimum number of steps required to convert a given matrix into the diagonally dominant matrix can be calculated depending upon two case: If the sum of the absolute value of all elements of a row except diagonal element is greater than the absolute value of diagonal element then the difference between these two values will be added to the result.Else no need to add anything in the result as in that case row satisfies the condition for a diagonally dominant matrix."
},
{
"code": null,
"e": 26536,
"s": 26205,
"text": "If the sum of the absolute value of all elements of a row except diagonal element is greater than the absolute value of diagonal element then the difference between these two values will be added to the result.Else no need to add anything in the result as in that case row satisfies the condition for a diagonally dominant matrix."
},
{
"code": null,
"e": 26747,
"s": 26536,
"text": "If the sum of the absolute value of all elements of a row except diagonal element is greater than the absolute value of diagonal element then the difference between these two values will be added to the result."
},
{
"code": null,
"e": 26868,
"s": 26747,
"text": "Else no need to add anything in the result as in that case row satisfies the condition for a diagonally dominant matrix."
},
{
"code": null,
"e": 26921,
"s": 26868,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26925,
"s": 26921,
"text": "C++"
},
{
"code": null,
"e": 26930,
"s": 26925,
"text": "Java"
},
{
"code": null,
"e": 26938,
"s": 26930,
"text": "Python3"
},
{
"code": null,
"e": 26941,
"s": 26938,
"text": "C#"
},
{
"code": null,
"e": 26952,
"s": 26941,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 3 // Function to return the minimum steps// required to convert the given matrix// to a Diagonally Dominant Matrixint findStepsForDDM(int arr[][N]){ int result = 0; // For each row for (int i = 0; i < N; i++) { // To store the sum of the current row int sum = 0; for (int j = 0; j < N; j++) sum += abs(arr[i][j]); // Remove the element of the current row // which lies on the main diagonal sum -= abs(arr[i][i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (abs(arr[i][i]) < abs(sum)) result += abs(abs(arr[i][i]) - abs(sum)); } return result;} // Driven codeint main(){ int arr[N][N] = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; cout << findStepsForDDM(arr); return 0;}",
"e": 27968,
"s": 26952,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ final static int N = 3 ; // Function to return the minimum steps // required to convert the given matrix // to a Diagonally Dominant Matrix static int findStepsForDDM(int arr[][]) { int result = 0; // For each row for (int i = 0; i < N; i++) { // To store the sum of the current row int sum = 0; for (int j = 0; j < N; j++) sum += Math.abs(arr[i][j]); // Remove the element of the current row // which lies on the main diagonal sum -= Math.abs(arr[i][i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (Math.abs(arr[i][i]) < Math.abs(sum)) result += Math.abs(Math.abs(arr[i][i]) - Math.abs(sum)); } return result; } // Driven code public static void main (String[] args) { int arr[][] = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; System.out.println(findStepsForDDM(arr)); }} // This code is contributed by AnkitRai01",
"e": 29250,
"s": 27968,
"text": null
},
{
"code": "# Python3 implementation of the approach N = 3 # Function to return the minimum steps# required to convert the given matrix# to a Diagonally Dominant Matrixdef findStepsForDDM(arr): result = 0 # For each row for i in range(N): # To store the sum of the current row sum = 0 for j in range(N): sum += abs(arr[i][j]) # Remove the element of the current row # which lies on the main diagonal sum -= abs(arr[i][i]) # Checking if the diagonal element is less # than the sum of non-diagonal element # then add their difference to the result if (abs(arr[i][i]) < abs(sum)): result += abs(abs(arr[i][i]) - abs(sum)) return result # Driver code arr= [ [ 3, -2, 1 ], [ 1, -3, 2 ], [ -1, 2, 4 ] ] print(findStepsForDDM(arr)) # This code is contributed by mohit kumar 29",
"e": 30124,
"s": 29250,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int N = 3 ; // Function to return the minimum steps // required to convert the given matrix // to a Diagonally Dominant Matrix static int findStepsForDDM(int [,]arr) { int result = 0; // For each row for (int i = 0; i < N; i++) { // To store the sum of the current row int sum = 0; for (int j = 0; j < N; j++) sum += Math.Abs(arr[i,j]); // Remove the element of the current row // which lies on the main diagonal sum -= Math.Abs(arr[i,i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (Math.Abs(arr[i,i]) < Math.Abs(sum)) result += Math.Abs(Math.Abs(arr[i,i]) - Math.Abs(sum)); } return result; } // Driven code static public void Main () { int [,]arr = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; Console.WriteLine(findStepsForDDM(arr)); }} // This code is contributed by ajit.",
"e": 31387,
"s": 30124,
"text": null
},
{
"code": "<script>// Java script implementation of the approachlet N = 3 ; // Function to return the minimum steps // required to convert the given matrix // to a Diagonally Dominant Matrix function findStepsForDDM(arr) { let result = 0; // For each row for (let i = 0; i < N; i++) { // To store the sum of the current row let sum = 0; for (let j = 0; j < N; j++) sum += Math.abs(arr[i][j]); // Remove the element of the current row // which lies on the main diagonal sum -= Math.abs(arr[i][i]); // Checking if the diagonal element is less // than the sum of non-diagonal element // then add their difference to the result if (Math.abs(arr[i][i]) < Math.abs(sum)) result += Math.abs(Math.abs(arr[i][i]) - Math.abs(sum)); } return result; } // Driven code let arr = [[ 3, -2, 1 ], [ 1, -3, 2 ], [ -1, 2, 4 ]]; document.write(findStepsForDDM(arr)); // This code is contributed by mohan pavan </script>",
"e": 32580,
"s": 31387,
"text": null
},
{
"code": null,
"e": 32582,
"s": 32580,
"text": "0"
},
{
"code": null,
"e": 32607,
"s": 32584,
"text": "Time complexity: O(N2)"
},
{
"code": null,
"e": 32630,
"s": 32607,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32645,
"s": 32630,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32653,
"s": 32645,
"text": "ankthon"
},
{
"code": null,
"e": 32659,
"s": 32653,
"text": "jit_t"
},
{
"code": null,
"e": 32672,
"s": 32659,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32689,
"s": 32672,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 32708,
"s": 32689,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 32715,
"s": 32708,
"text": "Matrix"
},
{
"code": null,
"e": 32722,
"s": 32715,
"text": "Matrix"
},
{
"code": null,
"e": 32820,
"s": 32722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32829,
"s": 32820,
"text": "Comments"
},
{
"code": null,
"e": 32842,
"s": 32829,
"text": "Old Comments"
},
{
"code": null,
"e": 32875,
"s": 32842,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 32943,
"s": 32875,
"text": "Multiplication of two Matrices in Single line using Numpy in Python"
},
{
"code": null,
"e": 32964,
"s": 32943,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 33026,
"s": 32964,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 33050,
"s": 33026,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 33072,
"s": 33050,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 33149,
"s": 33072,
"text": "Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)"
},
{
"code": null,
"e": 33187,
"s": 33149,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 33251,
"s": 33187,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
}
] |
Differences between abstract class and concrete class in Java
|
In Java, abstraction is achieved using Abstract classes and interfaces. An abstract class contains abstract methods which a child class. Following are the important differences between abstract class and a concrete class.
public class JavaTester {
public static void main(String args[]) {
Cat lion = new Lion();
lion.eat();
}
}
abstract class Cat {
abstract public void eat();
}
class Lion extends Cat{
public void eat(){
System.out.println("Lion eats");
}
}
Lion eats
|
[
{
"code": null,
"e": 1284,
"s": 1062,
"text": "In Java, abstraction is achieved using Abstract classes and interfaces. An abstract class contains abstract methods which a child class. Following are the important differences between abstract class and a concrete class."
},
{
"code": null,
"e": 1554,
"s": 1284,
"text": "public class JavaTester {\n public static void main(String args[]) {\n Cat lion = new Lion();\n lion.eat();\n }\n}\nabstract class Cat {\n abstract public void eat();\n}\nclass Lion extends Cat{\n public void eat(){\n System.out.println(\"Lion eats\");\n }\n}"
},
{
"code": null,
"e": 1564,
"s": 1554,
"text": "Lion eats"
}
] |
Tryit Editor v3.7
|
Tryit: The universal (*) selector
|
[] |
How To Fix pandas.parser.CParserError: Error tokenizing data | Towards Data Science
|
Importing data from csv files is probably the most commonly used way of instantiating pandas DataFrames. However, many times this could be a little bit tricky especially when the data included in the file are not in the expected form. In these cases, pandas parser may raise an error similar to the one reported below:
pandas.errors.ParserError: Error tokenizing data. C error: Expected 5 fields in line 2, saw 6
In today’s short guide we will discuss why this error is being raised in the first place and additionally, we will discuss a few ways that could eventually help you deal with it.
First, let’s try to reproduce the error using a small dataset I have prepared as part of this tutorial.
Now if we attempt to read in the file using read_csv :
import pandas as pddf = pd.read_csv('test.txt')
we are going to get the following error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 4 fields in line 4, saw 6
The error is pretty clear as it indicates that on the 4th line instead of 4, 6 fields were observed (and by the way, the same issue occurs in the last line as well).
By default, read_csv uses comma (,) as the delimiter but clearly, two lines in the file have more separators than expected. The expected number in this occasion is actually 4, since our headers (i.e. the first line of the file) contains 4 fields separated by commas.
The most obvious solution to the problem, is to fix the data file manually by removing the extra separators in the lines causing us troubles. This is actually the best solution (assuming that you have specified the right delimiters, headers etc. when calling read_csv function). However, this may be quite tricky and painful when you need to deal with large files containing thousands of lines.
Another cause of this error may be related to some carriage returns (i.e. '\r’) in the data. In some occasions this is actually introduced by pandas.to_csv() method. When writing pandas DataFrames to CSV files, a carriage return is added to column names in which the method will then write the subsequent column names to the first column of the pandas DataFrame. And thus we’ll end up with different number of columns in the first rows.
If that’s the case, then you can explicitly specify the line terminator to '\n' using the corresponding parameter when calling read_csv():
import pandas as pd df = pd.read_csv('test.csv', lineterminator='\n')
The error may also be related to the delimiters and/or headers (not) specified when calling read_csv. Make sure to pass both the correct separator and headers.
For example, the arguments below specify that ; is the delimiter used to separate columns (by default commas are used as delimiters) and that the file does not contain any headers at all.
import pandas as pddf = pd.read_csv('test.csv', sep=';', header=None)
Skipping rows that are causing the error should be your last resort and I would personally discourage you from doing so, but I guess there are certain use cases where this may be acceptable.
If that’s the case, then you can do so by setting error_bad_lines to False when calling read_csv function:
import pandas as pd df = pd.read_csv('test.txt', error_bad_lines=False)print(df) colA colB colC colD0 1 A 100 1.01 2 B 121 2.12 4 D 164 3.13 5 E 55 4.5
As you can see from the output above, the lines that they were causing errors were actually skipped and we can now move on with whatever we’d like to do with our pandas DataFrame.
In today’s short guide, we discussed a few cases where pandas.errors.ParserError: Error tokenizing data is raised by the pandas parser when reading csv files into pandas DataFrames.
Additionally, we showcased how to deal with the error by fixing the errors or typos in the data file itself, or by specifying the appropriate line terminator. Finally, we also discussed how to skip lines causing errors but keep in mind that in most of the cases this should be avoided.
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
gmyrianthous.medium.com
You may also like
|
[
{
"code": null,
"e": 490,
"s": 171,
"text": "Importing data from csv files is probably the most commonly used way of instantiating pandas DataFrames. However, many times this could be a little bit tricky especially when the data included in the file are not in the expected form. In these cases, pandas parser may raise an error similar to the one reported below:"
},
{
"code": null,
"e": 584,
"s": 490,
"text": "pandas.errors.ParserError: Error tokenizing data. C error: Expected 5 fields in line 2, saw 6"
},
{
"code": null,
"e": 763,
"s": 584,
"text": "In today’s short guide we will discuss why this error is being raised in the first place and additionally, we will discuss a few ways that could eventually help you deal with it."
},
{
"code": null,
"e": 867,
"s": 763,
"text": "First, let’s try to reproduce the error using a small dataset I have prepared as part of this tutorial."
},
{
"code": null,
"e": 922,
"s": 867,
"text": "Now if we attempt to read in the file using read_csv :"
},
{
"code": null,
"e": 970,
"s": 922,
"text": "import pandas as pddf = pd.read_csv('test.txt')"
},
{
"code": null,
"e": 1010,
"s": 970,
"text": "we are going to get the following error"
},
{
"code": null,
"e": 1104,
"s": 1010,
"text": "pandas.errors.ParserError: Error tokenizing data. C error: Expected 4 fields in line 4, saw 6"
},
{
"code": null,
"e": 1270,
"s": 1104,
"text": "The error is pretty clear as it indicates that on the 4th line instead of 4, 6 fields were observed (and by the way, the same issue occurs in the last line as well)."
},
{
"code": null,
"e": 1537,
"s": 1270,
"text": "By default, read_csv uses comma (,) as the delimiter but clearly, two lines in the file have more separators than expected. The expected number in this occasion is actually 4, since our headers (i.e. the first line of the file) contains 4 fields separated by commas."
},
{
"code": null,
"e": 1932,
"s": 1537,
"text": "The most obvious solution to the problem, is to fix the data file manually by removing the extra separators in the lines causing us troubles. This is actually the best solution (assuming that you have specified the right delimiters, headers etc. when calling read_csv function). However, this may be quite tricky and painful when you need to deal with large files containing thousands of lines."
},
{
"code": null,
"e": 2369,
"s": 1932,
"text": "Another cause of this error may be related to some carriage returns (i.e. '\\r’) in the data. In some occasions this is actually introduced by pandas.to_csv() method. When writing pandas DataFrames to CSV files, a carriage return is added to column names in which the method will then write the subsequent column names to the first column of the pandas DataFrame. And thus we’ll end up with different number of columns in the first rows."
},
{
"code": null,
"e": 2508,
"s": 2369,
"text": "If that’s the case, then you can explicitly specify the line terminator to '\\n' using the corresponding parameter when calling read_csv():"
},
{
"code": null,
"e": 2578,
"s": 2508,
"text": "import pandas as pd df = pd.read_csv('test.csv', lineterminator='\\n')"
},
{
"code": null,
"e": 2738,
"s": 2578,
"text": "The error may also be related to the delimiters and/or headers (not) specified when calling read_csv. Make sure to pass both the correct separator and headers."
},
{
"code": null,
"e": 2926,
"s": 2738,
"text": "For example, the arguments below specify that ; is the delimiter used to separate columns (by default commas are used as delimiters) and that the file does not contain any headers at all."
},
{
"code": null,
"e": 2996,
"s": 2926,
"text": "import pandas as pddf = pd.read_csv('test.csv', sep=';', header=None)"
},
{
"code": null,
"e": 3187,
"s": 2996,
"text": "Skipping rows that are causing the error should be your last resort and I would personally discourage you from doing so, but I guess there are certain use cases where this may be acceptable."
},
{
"code": null,
"e": 3294,
"s": 3187,
"text": "If that’s the case, then you can do so by setting error_bad_lines to False when calling read_csv function:"
},
{
"code": null,
"e": 3495,
"s": 3294,
"text": "import pandas as pd df = pd.read_csv('test.txt', error_bad_lines=False)print(df) colA colB colC colD0 1 A 100 1.01 2 B 121 2.12 4 D 164 3.13 5 E 55 4.5"
},
{
"code": null,
"e": 3675,
"s": 3495,
"text": "As you can see from the output above, the lines that they were causing errors were actually skipped and we can now move on with whatever we’d like to do with our pandas DataFrame."
},
{
"code": null,
"e": 3857,
"s": 3675,
"text": "In today’s short guide, we discussed a few cases where pandas.errors.ParserError: Error tokenizing data is raised by the pandas parser when reading csv files into pandas DataFrames."
},
{
"code": null,
"e": 4143,
"s": 3857,
"text": "Additionally, we showcased how to deal with the error by fixing the errors or typos in the data file itself, or by specifying the appropriate line terminator. Finally, we also discussed how to skip lines causing errors but keep in mind that in most of the cases this should be avoided."
},
{
"code": null,
"e": 4314,
"s": 4143,
"text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium."
},
{
"code": null,
"e": 4338,
"s": 4314,
"text": "gmyrianthous.medium.com"
}
] |
User Defined Functions in Redshift | by Mandy Gu | Towards Data Science
|
Amazon Redshift is a cloud data warehouse with its own Redshift SQL dialect (a variant of PostgreSQL). The service has become increasingly popular due to its low cost and compatibility with other Amazon Web Services. My favourite Redshift integration is the ability to unload and copy data to and from S3.
In this article, we will focus on User Defined Functions (UDFs).
UDFs are scalar functions that can be customized and created from the Redshift data warehouse. Each function can accept a fixed number of arguments to return a single output. UDFs can be executed similarly to built in Redshift functions such as replace or lower.
Amazon recommends that all UDF names begin with f_. For instance, a UDF for calculating the number of business days between two dates could be named f_calculate_business_days . This will prevent conflicts between UDF names and new Redshift functions — the f_ prefix is specifically reserved for UDFs.
UDFs can be created using a SQL select statement or as a Python function. UDFs written in SQL are more performant, but Python UDFs come with the advantage of built in libraries. In addition to the Python Standard Library, Python UDFs support functions from pandas, scipy, numpy to name just a few. There is also an option to import additional Python libraries by creating a library from code saved in S3.
All UDFs are created using theCREATE FUNCTION command. Alternatively, we can use CREATE OR REPLACE FUNCTION to update existing UDFs.
There is a limit of 32 arguments for any UDF.
This is the structure of a SQL UDF:
create function f_sql_udf ([arg1 data type], ...) returns [return data type] stable as $$ select ...$$ language sql;
The UDF body is made up of one select statement. Arguments in a SQL UDF cannot be named. They must be referenced (in the order they are defined) as $1, $2 and so forth. Arguments can take on any Redshift data type.
This is the structure of a Python UDF:
create function f_python_udf (arg_name [arg1 data type], ...) returns [return data type] stable as $$ [Python code here]$$ language plpythonu;
Unlike SQL UDFs, Python UDFs require argument names. Installed libraries can also be imported as a part of the Python code. Refer to this page for supported Python UDF data types.
Consider a very simple UDF for cleaning a string. We want this UDF to convert the input to lowercase and replace underscores with a white space. Although these cleaning steps can be built into the SQL query itself, we can also use a UDF to make the queries more consistent and easier to read.
create function f_clean_text (varchar) returns varcharstable as $$select replace(lower($1), '_', ' ')$$ language sql;
create function f_clean_text (text varchar) returns varcharstable as $$return text.lower().replace('_', ' ')$$ language plpythonu;
We can test our new UDF using this statement.
select f_clean_text('eRROR_BAD_input')
We can apply this UDF to a column called error_messages
select f_clean_text(error_messages) from schema.table
To see the code used to create existing UDFs, query the pg_proc table
UDFs support the Python logging library, which allows us to log warnings and errors within our UDFs
Database Administrators can use GRANT and REVOKE to customize UDF privileges
To delete a UDF, rundrop function udf_name(arguments)
Here is a Coursera course for practicing and applying SQL.
click.linksynergy.com
If you enjoyed this article, consider buying me a coffee — every small contribution helps me find more time to work on this blog. Follow me on Medium for the latest updates. 😃
I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project.
Thank you again for reading! 📕
|
[
{
"code": null,
"e": 478,
"s": 172,
"text": "Amazon Redshift is a cloud data warehouse with its own Redshift SQL dialect (a variant of PostgreSQL). The service has become increasingly popular due to its low cost and compatibility with other Amazon Web Services. My favourite Redshift integration is the ability to unload and copy data to and from S3."
},
{
"code": null,
"e": 543,
"s": 478,
"text": "In this article, we will focus on User Defined Functions (UDFs)."
},
{
"code": null,
"e": 806,
"s": 543,
"text": "UDFs are scalar functions that can be customized and created from the Redshift data warehouse. Each function can accept a fixed number of arguments to return a single output. UDFs can be executed similarly to built in Redshift functions such as replace or lower."
},
{
"code": null,
"e": 1107,
"s": 806,
"text": "Amazon recommends that all UDF names begin with f_. For instance, a UDF for calculating the number of business days between two dates could be named f_calculate_business_days . This will prevent conflicts between UDF names and new Redshift functions — the f_ prefix is specifically reserved for UDFs."
},
{
"code": null,
"e": 1512,
"s": 1107,
"text": "UDFs can be created using a SQL select statement or as a Python function. UDFs written in SQL are more performant, but Python UDFs come with the advantage of built in libraries. In addition to the Python Standard Library, Python UDFs support functions from pandas, scipy, numpy to name just a few. There is also an option to import additional Python libraries by creating a library from code saved in S3."
},
{
"code": null,
"e": 1645,
"s": 1512,
"text": "All UDFs are created using theCREATE FUNCTION command. Alternatively, we can use CREATE OR REPLACE FUNCTION to update existing UDFs."
},
{
"code": null,
"e": 1691,
"s": 1645,
"text": "There is a limit of 32 arguments for any UDF."
},
{
"code": null,
"e": 1727,
"s": 1691,
"text": "This is the structure of a SQL UDF:"
},
{
"code": null,
"e": 1848,
"s": 1727,
"text": "create function f_sql_udf ([arg1 data type], ...) returns [return data type] stable as $$ select ...$$ language sql;"
},
{
"code": null,
"e": 2063,
"s": 1848,
"text": "The UDF body is made up of one select statement. Arguments in a SQL UDF cannot be named. They must be referenced (in the order they are defined) as $1, $2 and so forth. Arguments can take on any Redshift data type."
},
{
"code": null,
"e": 2102,
"s": 2063,
"text": "This is the structure of a Python UDF:"
},
{
"code": null,
"e": 2249,
"s": 2102,
"text": "create function f_python_udf (arg_name [arg1 data type], ...) returns [return data type] stable as $$ [Python code here]$$ language plpythonu;"
},
{
"code": null,
"e": 2429,
"s": 2249,
"text": "Unlike SQL UDFs, Python UDFs require argument names. Installed libraries can also be imported as a part of the Python code. Refer to this page for supported Python UDF data types."
},
{
"code": null,
"e": 2722,
"s": 2429,
"text": "Consider a very simple UDF for cleaning a string. We want this UDF to convert the input to lowercase and replace underscores with a white space. Although these cleaning steps can be built into the SQL query itself, we can also use a UDF to make the queries more consistent and easier to read."
},
{
"code": null,
"e": 2842,
"s": 2722,
"text": "create function f_clean_text (varchar) returns varcharstable as $$select replace(lower($1), '_', ' ')$$ language sql;"
},
{
"code": null,
"e": 2975,
"s": 2842,
"text": "create function f_clean_text (text varchar) returns varcharstable as $$return text.lower().replace('_', ' ')$$ language plpythonu;"
},
{
"code": null,
"e": 3021,
"s": 2975,
"text": "We can test our new UDF using this statement."
},
{
"code": null,
"e": 3060,
"s": 3021,
"text": "select f_clean_text('eRROR_BAD_input')"
},
{
"code": null,
"e": 3116,
"s": 3060,
"text": "We can apply this UDF to a column called error_messages"
},
{
"code": null,
"e": 3170,
"s": 3116,
"text": "select f_clean_text(error_messages) from schema.table"
},
{
"code": null,
"e": 3240,
"s": 3170,
"text": "To see the code used to create existing UDFs, query the pg_proc table"
},
{
"code": null,
"e": 3340,
"s": 3240,
"text": "UDFs support the Python logging library, which allows us to log warnings and errors within our UDFs"
},
{
"code": null,
"e": 3417,
"s": 3340,
"text": "Database Administrators can use GRANT and REVOKE to customize UDF privileges"
},
{
"code": null,
"e": 3471,
"s": 3417,
"text": "To delete a UDF, rundrop function udf_name(arguments)"
},
{
"code": null,
"e": 3530,
"s": 3471,
"text": "Here is a Coursera course for practicing and applying SQL."
},
{
"code": null,
"e": 3552,
"s": 3530,
"text": "click.linksynergy.com"
},
{
"code": null,
"e": 3728,
"s": 3552,
"text": "If you enjoyed this article, consider buying me a coffee — every small contribution helps me find more time to work on this blog. Follow me on Medium for the latest updates. 😃"
},
{
"code": null,
"e": 3863,
"s": 3728,
"text": "I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project."
}
] |
Roll Out Animation Effect with CSS
|
To create a rollout animation effect with CSS, you can try to run the following code −
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes rollOut {
0% {
opacity: 1;
-webkit-transform: translateX(0px) rotate(0deg);
}
100% {
opacity: 0;
-webkit-transform: translateX(100%) rotate(120deg);
}
}
@keyframes rollOut {
0% {
opacity: 1;
transform: translateX(0px) rotate(0deg);
}
100% {
opacity: 0;
transform: translateX(100%) rotate(120deg);
}
}
.rollOut {
-webkit-animation-name: rollOut;
animation-name: rollOut;
}
<style>
</head>
<body>
<div id = "animated-example" class = "animated rollOut"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To create a rollout animation effect with CSS, you can try to run the following code −"
},
{
"code": null,
"e": 2564,
"s": 1149,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n\n @-webkit-keyframes rollOut {\n 0% {\n opacity: 1;\n -webkit-transform: translateX(0px) rotate(0deg);\n }\n 100% {\n opacity: 0;\n -webkit-transform: translateX(100%) rotate(120deg);\n }\n }\n\n @keyframes rollOut {\n 0% {\n opacity: 1;\n transform: translateX(0px) rotate(0deg);\n }\n 100% {\n opacity: 0;\n transform: translateX(100%) rotate(120deg);\n }\n }\n\n .rollOut {\n -webkit-animation-name: rollOut;\n animation-name: rollOut;\n }\n <style>\n\n </head>\n <body>\n\n <div id = \"animated-example\" class = \"animated rollOut\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n\n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n </body>\n</html>"
}
] |
What is morphological gradient in image processing?
|
Erosion and dilation are the two basic morphological operations. As the name implies, morphological operations are the set of operations that process images
according to their shapes.
During dilation operation additional pixels are added to an image boundary and, during erosion operation, additional pixels are removed from image boundaries, The total number of pixels added during the dilation process depends on the dimensions of the structuring element used.
Morphological Gradient is the operation that is equal to the difference between dilation and erosion of an image. Each pixel value in the resulting image indicates the contrast intensity in the nearby pixels. This is used in edge detection, segmentation and to find the outline of an object.
Following Java example generates a window containing the Morphological gradient of the given image −
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class MorphologicalGradient extends Application {
public void start(Stage stage) throws IOException {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading image data
String file ="D:\\Images\\morph_input1.jpg";
Mat src = Imgcodecs.imread(file);
//Creating destination matrix
Mat dst = new Mat(src.rows(), src.cols(), src.type());
//Preparing the kernel matrix object
Mat kernel = Mat.ones(5,5, CvType.CV_32F);
//Applying dilate on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_GRADIENT, kernel);
//Converting matrix to JavaFX writable image
Image img = HighGui.toBufferedImage(dst);
WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
//Setting the image view
ImageView imageView = new ImageView(writableImage);
imageView.setX(10);
imageView.setY(10);
imageView.setFitWidth(575);
imageView.setPreserveRatio(true);
//Setting the Scene object
Group root = new Group(imageView);
Scene scene = new Scene(root, 595, 400);
stage.setTitle("Morphological Gradient");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "Erosion and dilation are the two basic morphological operations. As the name implies, morphological operations are the set of operations that process images\naccording to their shapes."
},
{
"code": null,
"e": 1525,
"s": 1246,
"text": "During dilation operation additional pixels are added to an image boundary and, during erosion operation, additional pixels are removed from image boundaries, The total number of pixels added during the dilation process depends on the dimensions of the structuring element used."
},
{
"code": null,
"e": 1817,
"s": 1525,
"text": "Morphological Gradient is the operation that is equal to the difference between dilation and erosion of an image. Each pixel value in the resulting image indicates the contrast intensity in the nearby pixels. This is used in edge detection, segmentation and to find the outline of an object."
},
{
"code": null,
"e": 1918,
"s": 1817,
"text": "Following Java example generates a window containing the Morphological gradient of the given image −"
},
{
"code": null,
"e": 3755,
"s": 1918,
"text": "import java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\nimport org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class MorphologicalGradient extends Application {\n public void start(Stage stage) throws IOException {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\morph_input1.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n //Preparing the kernel matrix object\n Mat kernel = Mat.ones(5,5, CvType.CV_32F);\n //Applying dilate on the Image\n Imgproc.morphologyEx(src, dst, Imgproc.MORPH_GRADIENT, kernel);\n //Converting matrix to JavaFX writable image\n Image img = HighGui.toBufferedImage(dst);\n WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);\n //Setting the image view\n ImageView imageView = new ImageView(writableImage);\n imageView.setX(10);\n imageView.setY(10);\n imageView.setFitWidth(575);\n imageView.setPreserveRatio(true);\n //Setting the Scene object\n Group root = new Group(imageView);\n Scene scene = new Scene(root, 595, 400);\n stage.setTitle(\"Morphological Gradient\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}"
}
] |
Java break statement with switch
|
Following is an example
Live Demo
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run the above program using various command line arguments. This will produce the following result −
Well done
Your grade is C
|
[
{
"code": null,
"e": 1086,
"s": 1062,
"text": "Following is an example"
},
{
"code": null,
"e": 1096,
"s": 1086,
"text": "Live Demo"
},
{
"code": null,
"e": 1730,
"s": 1096,
"text": "public class Test {\n\n public static void main(String args[]) {\n // char grade = args[0].charAt(0);\n char grade = 'C';\n\n switch(grade) {\n case 'A' :\n System.out.println(\"Excellent!\");\n break;\n case 'B' :\n case 'C' :\n System.out.println(\"Well done\");\n break;\n case 'D' :\n System.out.println(\"You passed\");\n case 'F' :\n System.out.println(\"Better try again\");\n break;\n default :\n System.out.println(\"Invalid grade\");\n }\n System.out.println(\"Your grade is \" + grade);\n }\n}"
},
{
"code": null,
"e": 1843,
"s": 1730,
"text": "Compile and run the above program using various command line arguments. This will produce the following result −"
},
{
"code": null,
"e": 1869,
"s": 1843,
"text": "Well done\nYour grade is C"
}
] |
How to Change Tkinter Button State? - GeeksforGeeks
|
17 Dec, 2020
Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python standard library. Tkinter has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. Tkinter is lightweight and relatively painless to use compared to other frameworks.
In this article, we are going to learn how we can change the state of a Button.
Let’s understand this with step-wise:
Step 1: First we are going to import the Tkinter module and some widgets that we need.
Python3
# importing tkinter module# along with some constants and Widgets from tkinter import Tkfrom tkinter.constants import DISABLED, NORMALfrom tkinter.ttk import Button, Label
If you are using Python2 then change tkinter to Tkinter and also tkinter.ttk will not also work so import widgets from Tkinter itself.
Step 2: Now we are going to create an App class that will contain all the Buttons and Labels.
Python3
# Creating App class which# will contain our overall Appclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating label self.label = Label(self.master, text = "Click Button2 to change Button1 State") self.label.pack(pady = 10) # Creating button1 # We will change the state of this Button # it has a initial state of "NORMAL" # i.e Button can be pressed self.button1 = Button(self.master, text = "Button1", state = NORMAL) self.button1.pack(pady = 20) # Creating another button # We will use this button to # change the State of first button self.button2 = Button(self.master, text = "Button2", command = self.changeState) self.button2.pack(pady = 20)
Step 3: As you can see in the above code, we have a function attached with Button2 i.e changeState function next we are going to implement this function. In this function, we will change the State of Button1.
Python3
# Helper function which will change the State of Button1def changeState(self) -> None: # Printing the State of # the Button before ALTERING it # This is optional print(self.button1['state']) # Checking if the STATE of the Button1 # If the STATE is NORMAL if (self.button1['state'] == NORMAL): # Change the state to DISABLED self.button1['state'] = DISABLED else: # Otherwise, change the state to NORMAL self.button1['state'] = NORMAL
Step 4: In this step, we will create the main function that will run this application. In the main function, we will set the application title and geometry and instantiate our App class.
Python3
if __name__ == "__main__": # Instantiating top level root = Tk() # Setting the title of the window root.title("Button State App") # Setting the geometry i.e Dimensions root.geometry("400x250") # Calling our App app = App(root) # Mainloop which will cause # this toplevel to run infinitely root.mainloop()
Below is the full implementation:
Python3
# importing tkinter module# along with some constants and Widgetsfrom tkinter import Tkfrom tkinter.constants import DISABLED, NORMALfrom tkinter.ttk import Button, Label # Creating App class# which will contain our overall Appclass App: def __init__(self, master) -> None: # Instantiating master # i.e toplevel Widget self.master = master # Creating label self.label = Label(self.master, text="Click Button2 to change Button1 State") self.label.pack(pady = 10) # Creating button1 # We will change the state of this Button # it has a initial state of # "NORMAL" i.e Button can be pressed self.button1 = Button(self.master, text = "Button1", state = NORMAL) self.button1.pack(pady = 20) # Creating another button # We will use this button # to change the State of first button self.button2 = Button(self.master, text = "Button2", command = self.changeState) self.button2.pack(pady = 20) # Helper function which will # change the State of Button1 def changeState(self) -> None: # Printing the State of # the Button before ALTERING it # This is optional print(self.button1['state']) # Checking if the STATE of the Button1 # If the STATE is NORMAL if (self.button1['state'] == NORMAL): # Change the state to DISABLED self.button1['state'] = DISABLED else: # Otherwise, change the state to NORMAL self.button1['state'] = NORMAL if __name__ == "__main__": # Instantiating top level root = Tk() # Setting the title of the window root.title("Button State App") # Setting the geometry i.e Dimensions root.geometry("400x250") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()
Output:
Picked
Python-tkinter
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
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
|
[
{
"code": null,
"e": 24503,
"s": 24475,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 24868,
"s": 24503,
"text": "Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python standard library. Tkinter has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. Tkinter is lightweight and relatively painless to use compared to other frameworks."
},
{
"code": null,
"e": 24948,
"s": 24868,
"text": "In this article, we are going to learn how we can change the state of a Button."
},
{
"code": null,
"e": 24986,
"s": 24948,
"text": "Let’s understand this with step-wise:"
},
{
"code": null,
"e": 25073,
"s": 24986,
"text": "Step 1: First we are going to import the Tkinter module and some widgets that we need."
},
{
"code": null,
"e": 25081,
"s": 25073,
"text": "Python3"
},
{
"code": "# importing tkinter module# along with some constants and Widgets from tkinter import Tkfrom tkinter.constants import DISABLED, NORMALfrom tkinter.ttk import Button, Label",
"e": 25254,
"s": 25081,
"text": null
},
{
"code": null,
"e": 25389,
"s": 25254,
"text": "If you are using Python2 then change tkinter to Tkinter and also tkinter.ttk will not also work so import widgets from Tkinter itself."
},
{
"code": null,
"e": 25483,
"s": 25389,
"text": "Step 2: Now we are going to create an App class that will contain all the Buttons and Labels."
},
{
"code": null,
"e": 25491,
"s": 25483,
"text": "Python3"
},
{
"code": "# Creating App class which# will contain our overall Appclass App: def __init__(self, master) -> None: # Instantiating master i.e toplevel Widget self.master = master # Creating label self.label = Label(self.master, text = \"Click Button2 to change Button1 State\") self.label.pack(pady = 10) # Creating button1 # We will change the state of this Button # it has a initial state of \"NORMAL\" # i.e Button can be pressed self.button1 = Button(self.master, text = \"Button1\", state = NORMAL) self.button1.pack(pady = 20) # Creating another button # We will use this button to # change the State of first button self.button2 = Button(self.master, text = \"Button2\", command = self.changeState) self.button2.pack(pady = 20)",
"e": 26492,
"s": 25491,
"text": null
},
{
"code": null,
"e": 26701,
"s": 26492,
"text": "Step 3: As you can see in the above code, we have a function attached with Button2 i.e changeState function next we are going to implement this function. In this function, we will change the State of Button1."
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Python3"
},
{
"code": "# Helper function which will change the State of Button1def changeState(self) -> None: # Printing the State of # the Button before ALTERING it # This is optional print(self.button1['state']) # Checking if the STATE of the Button1 # If the STATE is NORMAL if (self.button1['state'] == NORMAL): # Change the state to DISABLED self.button1['state'] = DISABLED else: # Otherwise, change the state to NORMAL self.button1['state'] = NORMAL",
"e": 27212,
"s": 26709,
"text": null
},
{
"code": null,
"e": 27399,
"s": 27212,
"text": "Step 4: In this step, we will create the main function that will run this application. In the main function, we will set the application title and geometry and instantiate our App class."
},
{
"code": null,
"e": 27407,
"s": 27399,
"text": "Python3"
},
{
"code": "if __name__ == \"__main__\": # Instantiating top level root = Tk() # Setting the title of the window root.title(\"Button State App\") # Setting the geometry i.e Dimensions root.geometry(\"400x250\") # Calling our App app = App(root) # Mainloop which will cause # this toplevel to run infinitely root.mainloop()",
"e": 27755,
"s": 27407,
"text": null
},
{
"code": null,
"e": 27789,
"s": 27755,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 27797,
"s": 27789,
"text": "Python3"
},
{
"code": "# importing tkinter module# along with some constants and Widgetsfrom tkinter import Tkfrom tkinter.constants import DISABLED, NORMALfrom tkinter.ttk import Button, Label # Creating App class# which will contain our overall Appclass App: def __init__(self, master) -> None: # Instantiating master # i.e toplevel Widget self.master = master # Creating label self.label = Label(self.master, text=\"Click Button2 to change Button1 State\") self.label.pack(pady = 10) # Creating button1 # We will change the state of this Button # it has a initial state of # \"NORMAL\" i.e Button can be pressed self.button1 = Button(self.master, text = \"Button1\", state = NORMAL) self.button1.pack(pady = 20) # Creating another button # We will use this button # to change the State of first button self.button2 = Button(self.master, text = \"Button2\", command = self.changeState) self.button2.pack(pady = 20) # Helper function which will # change the State of Button1 def changeState(self) -> None: # Printing the State of # the Button before ALTERING it # This is optional print(self.button1['state']) # Checking if the STATE of the Button1 # If the STATE is NORMAL if (self.button1['state'] == NORMAL): # Change the state to DISABLED self.button1['state'] = DISABLED else: # Otherwise, change the state to NORMAL self.button1['state'] = NORMAL if __name__ == \"__main__\": # Instantiating top level root = Tk() # Setting the title of the window root.title(\"Button State App\") # Setting the geometry i.e Dimensions root.geometry(\"400x250\") # Calling our App app = App(root) # Mainloop which will cause this toplevel # to run infinitely root.mainloop()",
"e": 29899,
"s": 27797,
"text": null
},
{
"code": null,
"e": 29907,
"s": 29899,
"text": "Output:"
},
{
"code": null,
"e": 29914,
"s": 29907,
"text": "Picked"
},
{
"code": null,
"e": 29929,
"s": 29914,
"text": "Python-tkinter"
},
{
"code": null,
"e": 29953,
"s": 29929,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29960,
"s": 29953,
"text": "Python"
},
{
"code": null,
"e": 29979,
"s": 29960,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30077,
"s": 29979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30086,
"s": 30077,
"text": "Comments"
},
{
"code": null,
"e": 30099,
"s": 30086,
"text": "Old Comments"
},
{
"code": null,
"e": 30117,
"s": 30099,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30139,
"s": 30117,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30171,
"s": 30139,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30213,
"s": 30171,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30238,
"s": 30213,
"text": "sum() function in Python"
},
{
"code": null,
"e": 30275,
"s": 30238,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30331,
"s": 30275,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30360,
"s": 30331,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30393,
"s": 30360,
"text": "Graph Plotting in Python | Set 1"
}
] |
Count total set bits | Practice | GeeksforGeeks
|
You are given a number N. Find the total count of set bits for all numbers from 1 to N(both inclusive).
Example 1:
Input: N = 4
Output: 5
Explanation:
For numbers from 1 to 4.
For 1: 0 0 1 = 1 set bits
For 2: 0 1 0 = 1 set bits
For 3: 0 1 1 = 2 set bits
For 4: 1 0 0 = 1 set bits
Therefore, the total set bits is 5.
Example 2:
Input: N = 17
Output: 35
Explanation: From numbers 1 to 17(both inclusive),
the total number of set bits is 35.
Your Task: The task is to complete the function countSetBits() that takes n as a parameter and returns the count of all bits.
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 108
0
atulharsh274Premium3 days ago
//c++ solution
int largestPowerOfTwo(int n){ int x=0; while((1<<x) <= n){ x++; } return x-1;}
int countSetBits(int n){ int x = largestPowerOfTwo(n); if(n==0) return 0; else return (1<<(x-1))*x + (n- (1<<x) +1 ) + countSetBits( n- (1<<x));}
0
amarrajsmart1971 week ago
C++ Solution>> Using Recursive call.
int powerless(int n) { int i=0; while(pow(2,i)<=n) { i++; } return (i-1); } int countSetBits(int n) { // Your logic here if(n<=1) return n; int x=powerless(n); return ((pow(2,x-1)*x)+(n-pow(2,x)+1)+countSetBits(n-pow(2,x))); }
0
khandelwalkusum2361 week ago
Whats is wrong in this , only 3500 something testcase passing
public static int countSetBits(int n){ // Your code here int count=0; if(n==0){ return 0; } for(int i=1;i<=n;i++){ int k=i; while(k>0){ k=k&(k-1); count++; } } return count; }
+3
dmmathpal7772 weeks ago
// Without Recursion
int set_n = 0; for (int i = 2; i <= n * 2; i = i * 2) { set_n = set_n + ((n / i) * (i / 2)); if (n % i != 0) if (n % i >= i/2) set_n = set_n + ((n % i) - i/2 + 1); } return set_n;
+1
vermaashitiit3 weeks ago
200 IQ solution!!
if(n==0) return 0; if(n%2==0) return countSetBits(n/2)+countSetBits((n-1)/2)+n/2; if(n%2!=0) return 2*countSetBits((n-1)/2)+(n-1)/2+1;
+1
adityagagtiwari4 weeks ago
Easy solution
class Solution{ //Function to return sum of count of set bits in the integers from 1 to n. public static int countSetBits(int n){ if(n==0) return 0; //formula for calculation //Solve(n)= pow(2,x-1)*x+(n-pow(2,x)+1)+Solve(n-pow(2,x)) //where x is the highest power of 2 such that pow(2,x)<=n //here we are calculating the power of 2 i.e. x int x = 0; while((1<<x)<=n) { x++; } // 1<<x represents 2 raised to power of x //here reducing x to cover for that extra power raised x = x-1; int bitsuptox = (1<<(x-1))*x; int setmsbofrest = n -(1<<x)+1; int rest = n-(1<<x); return bitsuptox + setmsbofrest + countSetBits(rest); }}
0
milindprajapatmst191 month ago
0.2/1.3
Time Complexity: O(log(n))
Space Complexity: O(1)
class Solution{
public:
int countSetBits(int n) {
int bit = n, k = 2, result = 0;
n++;
while (bit) {
int p = n / k;
result += p * (k >> 1);
result += max(0, (n % k) - (k >> 1));
k <<= 1;
bit >>= 1;
}
return result;
}
};
0
lawbindpandey01w1 month ago
C++ Solution where time complexity : theta(log n) and auxilary space complexity : theta(1);
int countSetBits(int n) { // Your logic here int nob = 0; int temp = n; while((temp = (temp >> 1))) nob++; //cout << nob+1 << "\n"; int count = 0; for(int i = 1; i <= int(pow(2,nob)); i *= 2){ count += n / (i * 2) * i; int tc = (n%(i*2)) -i + 1; if(tc > 0) count += tc; } return count; }
+1
siddharth191111 month ago
simple O(log n) recursive solution
int countSetBits(int n)
{
// Your logic here
if(n <= 1)
return n;
int x = log2(n);
int v = pow(2,x-1);
return v * x + (n - v * 2 + 1) + countSetBits(n-v*2);
}
+1
himanshukug19cs1 month ago
if(n==0) return 0; int x=lpowo2till(n); return x*(1<<(x-1))+(n-(1<<x)+1)+countSetBits(n-(1<<x)); } static int lpowo2till(int n){ int x=0; while((1<<x)<=n){ x++; } return x-1; }
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": 354,
"s": 238,
"text": "You are given a number N. Find the total count of set bits for all numbers from 1 to N(both inclusive).\n\nExample 1:"
},
{
"code": null,
"e": 556,
"s": 354,
"text": "Input: N = 4\nOutput: 5\nExplanation:\nFor numbers from 1 to 4.\nFor 1: 0 0 1 = 1 set bits\nFor 2: 0 1 0 = 1 set bits\nFor 3: 0 1 1 = 2 set bits\nFor 4: 1 0 0 = 1 set bits\nTherefore, the total set bits is 5.\n"
},
{
"code": null,
"e": 567,
"s": 556,
"text": "Example 2:"
},
{
"code": null,
"e": 680,
"s": 567,
"text": "Input: N = 17\nOutput: 35\nExplanation: From numbers 1 to 17(both inclusive), \nthe total number of set bits is 35."
},
{
"code": null,
"e": 902,
"s": 680,
"text": "\nYour Task: The task is to complete the function countSetBits() that takes n as a parameter and returns the count of all bits.\n\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1).\n\nConstraints:\n1 ≤ N ≤ 108"
},
{
"code": null,
"e": 904,
"s": 902,
"text": "0"
},
{
"code": null,
"e": 934,
"s": 904,
"text": "atulharsh274Premium3 days ago"
},
{
"code": null,
"e": 949,
"s": 934,
"text": "//c++ solution"
},
{
"code": null,
"e": 1052,
"s": 949,
"text": "int largestPowerOfTwo(int n){ int x=0; while((1<<x) <= n){ x++; } return x-1;}"
},
{
"code": null,
"e": 1212,
"s": 1052,
"text": "int countSetBits(int n){ int x = largestPowerOfTwo(n); if(n==0) return 0; else return (1<<(x-1))*x + (n- (1<<x) +1 ) + countSetBits( n- (1<<x));} "
},
{
"code": null,
"e": 1214,
"s": 1212,
"text": "0"
},
{
"code": null,
"e": 1240,
"s": 1214,
"text": "amarrajsmart1971 week ago"
},
{
"code": null,
"e": 1277,
"s": 1240,
"text": "C++ Solution>> Using Recursive call."
},
{
"code": null,
"e": 1592,
"s": 1277,
"text": " int powerless(int n) { int i=0; while(pow(2,i)<=n) { i++; } return (i-1); } int countSetBits(int n) { // Your logic here if(n<=1) return n; int x=powerless(n); return ((pow(2,x-1)*x)+(n-pow(2,x)+1)+countSetBits(n-pow(2,x))); }"
},
{
"code": null,
"e": 1594,
"s": 1592,
"text": "0"
},
{
"code": null,
"e": 1623,
"s": 1594,
"text": "khandelwalkusum2361 week ago"
},
{
"code": null,
"e": 1685,
"s": 1623,
"text": "Whats is wrong in this , only 3500 something testcase passing"
},
{
"code": null,
"e": 1985,
"s": 1687,
"text": "public static int countSetBits(int n){ // Your code here int count=0; if(n==0){ return 0; } for(int i=1;i<=n;i++){ int k=i; while(k>0){ k=k&(k-1); count++; } } return count; }"
},
{
"code": null,
"e": 1988,
"s": 1985,
"text": "+3"
},
{
"code": null,
"e": 2012,
"s": 1988,
"text": "dmmathpal7772 weeks ago"
},
{
"code": null,
"e": 2041,
"s": 2012,
"text": " // Without Recursion"
},
{
"code": null,
"e": 2303,
"s": 2041,
"text": " int set_n = 0; for (int i = 2; i <= n * 2; i = i * 2) { set_n = set_n + ((n / i) * (i / 2)); if (n % i != 0) if (n % i >= i/2) set_n = set_n + ((n % i) - i/2 + 1); } return set_n;"
},
{
"code": null,
"e": 2306,
"s": 2303,
"text": "+1"
},
{
"code": null,
"e": 2331,
"s": 2306,
"text": "vermaashitiit3 weeks ago"
},
{
"code": null,
"e": 2349,
"s": 2331,
"text": "200 IQ solution!!"
},
{
"code": null,
"e": 2485,
"s": 2349,
"text": " if(n==0) return 0; if(n%2==0) return countSetBits(n/2)+countSetBits((n-1)/2)+n/2; if(n%2!=0) return 2*countSetBits((n-1)/2)+(n-1)/2+1;"
},
{
"code": null,
"e": 2488,
"s": 2485,
"text": "+1"
},
{
"code": null,
"e": 2515,
"s": 2488,
"text": "adityagagtiwari4 weeks ago"
},
{
"code": null,
"e": 2530,
"s": 2515,
"text": "Easy solution "
},
{
"code": null,
"e": 3293,
"s": 2530,
"text": "class Solution{ //Function to return sum of count of set bits in the integers from 1 to n. public static int countSetBits(int n){ if(n==0) return 0; //formula for calculation //Solve(n)= pow(2,x-1)*x+(n-pow(2,x)+1)+Solve(n-pow(2,x)) //where x is the highest power of 2 such that pow(2,x)<=n //here we are calculating the power of 2 i.e. x int x = 0; while((1<<x)<=n) { x++; } // 1<<x represents 2 raised to power of x //here reducing x to cover for that extra power raised x = x-1; int bitsuptox = (1<<(x-1))*x; int setmsbofrest = n -(1<<x)+1; int rest = n-(1<<x); return bitsuptox + setmsbofrest + countSetBits(rest); }}"
},
{
"code": null,
"e": 3295,
"s": 3293,
"text": "0"
},
{
"code": null,
"e": 3326,
"s": 3295,
"text": "milindprajapatmst191 month ago"
},
{
"code": null,
"e": 3717,
"s": 3326,
"text": "0.2/1.3\nTime Complexity: O(log(n))\nSpace Complexity: O(1)\n\nclass Solution{\n public:\n int countSetBits(int n) {\n int bit = n, k = 2, result = 0;\n n++;\n while (bit) {\n int p = n / k;\n result += p * (k >> 1);\n result += max(0, (n % k) - (k >> 1));\n k <<= 1;\n bit >>= 1;\n }\n return result;\n }\n};"
},
{
"code": null,
"e": 3719,
"s": 3717,
"text": "0"
},
{
"code": null,
"e": 3747,
"s": 3719,
"text": "lawbindpandey01w1 month ago"
},
{
"code": null,
"e": 3839,
"s": 3747,
"text": "C++ Solution where time complexity : theta(log n) and auxilary space complexity : theta(1);"
},
{
"code": null,
"e": 4245,
"s": 3843,
"text": "int countSetBits(int n) { // Your logic here int nob = 0; int temp = n; while((temp = (temp >> 1))) nob++; //cout << nob+1 << \"\\n\"; int count = 0; for(int i = 1; i <= int(pow(2,nob)); i *= 2){ count += n / (i * 2) * i; int tc = (n%(i*2)) -i + 1; if(tc > 0) count += tc; } return count; }"
},
{
"code": null,
"e": 4248,
"s": 4245,
"text": "+1"
},
{
"code": null,
"e": 4274,
"s": 4248,
"text": "siddharth191111 month ago"
},
{
"code": null,
"e": 4309,
"s": 4274,
"text": "simple O(log n) recursive solution"
},
{
"code": null,
"e": 4528,
"s": 4309,
"text": "int countSetBits(int n)\n {\n // Your logic here\n if(n <= 1)\n return n;\n int x = log2(n);\n int v = pow(2,x-1);\n return v * x + (n - v * 2 + 1) + countSetBits(n-v*2);\n }"
},
{
"code": null,
"e": 4531,
"s": 4528,
"text": "+1"
},
{
"code": null,
"e": 4558,
"s": 4531,
"text": "himanshukug19cs1 month ago"
},
{
"code": null,
"e": 4803,
"s": 4558,
"text": " if(n==0) return 0; int x=lpowo2till(n); return x*(1<<(x-1))+(n-(1<<x)+1)+countSetBits(n-(1<<x)); } static int lpowo2till(int n){ int x=0; while((1<<x)<=n){ x++; } return x-1; }"
},
{
"code": null,
"e": 4949,
"s": 4803,
"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": 4985,
"s": 4949,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4995,
"s": 4985,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5005,
"s": 4995,
"text": "\nContest\n"
},
{
"code": null,
"e": 5068,
"s": 5005,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5216,
"s": 5068,
"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": 5424,
"s": 5216,
"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": 5530,
"s": 5424,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Getting Started with Graph Databases in Azure Cosmos DB | by Will Velida | Towards Data Science
|
In Azure Cosmos DB, we can build graph databases using the Gremlin API offering. Like many up and coming trends in the data universe, you may hear people talk about Graph databases and roll your eyes thinking ‘here we go’.
But there are many situations that we could model using a graph format. The most obvious example you might come across is Social Networks. I know Mike, who knows Gemma and we all enjoy hiking. Gemma has gone hiking in Raglan, New Zealand and I live in New Zealand, etc. etc. (We’ll build the basics of this example in a little bit!).
Modelling these relationships might be quite challenging to do in a traditional relational way, so using a graph data model would be quite nice to do, but what is a graph database and can we build one using Azure Cosmos DB.
The purpose of this article is to just introduce what Graph Databases are at a basic level and then show you how you can start building Graph Databases using the Gremlin API offering in Azure Cosmos DB.
So what are Graph Databases?
A graph is a structure that is composed of vertices and edges, which can have a number of properties.
Vertices or Nodes represent objects. Within our graph databases, we can determine the nodes in our graph by identifying entities within our use cases. Bearing this in mind, our nodes could represent entities such as:
A customer
An employee
A product
An order
Edges are what the relationships between vertices or edges are. For example, a person might know another person, or that person might have visited a location.
Properties describe information about the vertices and edges. For example, properties in vertices might include information about the person, such as their name, age or hair color. In edges, this might include information about how these two people know each other.
This data model can also be referred to as a Property Graph Model, which is what is supported by Azure Cosmos DB
We typically implement graph databases as NoSQL stores since we need the flexibility that schema-free data stores provide. This can also provide us with a data model that we can change quickly that has minimal impact on the applications that use them.
Graph Databases can provide us with high-performance levels even as the data inside our databases grows. Even as our relationships grow in complexity, we can still get a high level of performance from our database.
In a relational database, the performance of our queries decrease as soon as our relationships become more complicated.
As I mentioned earlier, we can add more relationships and data to our graph database without it having a massive impact on our functionality.
However, If we have high volumes of transactions that we need to process in our applications, then our graph database will suffer.
OK, what could I use a Graph Database for?
There are several use cases where we could deploy a graph database. Since I currently work for a bank, I’ve had a look at deploying graph databases for the purpose of fraud analytics.
Building recommendation engines and social networks would also be good situations where we could use Graph Databases. In these cases, we can use graphs to infer relationships based on interactions and activities that our users make or have previously made.
Another cool example of where we could use Graph databases would be for the use of master data management. We could use graphs to see how our data within our organisation is connected, what types of users query it, etc.
Why build a graph database using Cosmos DB?
We could run a Graph Database on our own computers. There’s no reason why you couldn’t just download Apache Tinkerpop, run some commands on the Gremlin Console and you’d have your graph database.
BUT, graph databases in productions are HUGE systems. Large graph databases in productions would have billions and billions of vertices and edges in them, so it’d be impractical for us to try and run this on our own computers.
That’s where Cosmos DB can come in and help us. We can build Graph Databases in Azure Cosmos DB thanks to the Gremlin API offering. This gives us a fully managed graph database in the cloud that can elastically grow in terms of storage and throughput.
Creating a Graph Database in Cosmos DB
Let’s get on with building a Graph Database using Cosmos DB. Go to the Azure Portal and click Create a New Resource. Under Databases, click Azure Cosmos DB.
Now we have to configure it. We give it a name, put it in a resource group and a location close to us. The most important thing here is to ensure that the Gremlin (graph) option is chosen as the API
Wait a few minutes and we’ll have our Cosmos DB account with the Gremlin API ready to go. Let’s create our first Graph database and add a graph to it so we can execute some queries in it.
When your account has been provisioned, you’ll be taken to an overview page. Click Add Graph to set up your first Graph Database.
I’m just going to set up a basic graph for this tutorial, I’ve created a Database called PeopleDB, adding a graph to it called PeopleGraph and providing a partition key call hobby which will contain the values of our hobbies. I’m going to keep the maximum RU value at 400 since we’re not going to do any major operations for this tutorial. Click OK to provision it.
Running some queries in Cosmos
Now that we have our graph set up, let’s build our people scenario that I referred to earlier. For this, we’ll add some vertices that represent People within our graph. They’ll all have properties for their first name, last name, age, hobby, where they are from and where they live.
We can add these vertices by running the below queries:
// Add Willg.addV('person').property('firstName', 'Will').property('lastName', 'Velida').property('age', 28).property('userid', 1).property('hobby', 'kayaking').property('from', 'UK').property('lives', 'NZ')// Add Gemmag.addV('person').property('firstName', 'Gemma').property('lastName', 'Wright').property('age', 30).property('userid', 2).property('hobby', 'hiking').property('from', 'NZ').property('lives', 'NZ')// Add Mikeg.addV('person').property('firstName', 'Mike').property('lastName', 'Smith').property('age', 30).property('userid', 3).property('hobby', 'kayaking').property('from', 'NZ').property('lives', 'NZ')// Add Sloang.addV('person').property('firstName', 'Sloan').property('lastName', 'Timms').property('age', 21).property('userid', 4).property('hobby', 'kayaking').property('from', 'UK').property('lives', 'NZ')
Now we can add some edges that will represent the relationships between our vertices in our People application.
// Will Knows Gemmag.V().hasLabel('person').has('firstName', 'Will').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Gemma'))// Sloan Knows Willg.V().hasLabel('person').has('firstName', 'Sloan').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Will'))// Mike Knows Gemmag.V().hasLabel('person').has('firstName', 'Will').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Gemma'))
Now that we’ve added everything, we can run some simple queries. Let’s run a query that returns all the people in our graph database that have kayaking as a hobby.
// Select everyone who kayaks as a hobbyg.V().hasLabel('person').has('hobby', 'kayaking')
We see the results returned as a graph like so. Three people were returned as results in our query and we can click on each node to see their properties.
In Conclusion
This was a really basic example just to introduce you to Graph databases and how you can build them using Azure Cosmos DB. In a future blog post, I’ll dive a little bit deeper into how to run Gremlin queries and compare them to SQL queries.
If you have any questions, please feel free to comment below!
|
[
{
"code": null,
"e": 394,
"s": 171,
"text": "In Azure Cosmos DB, we can build graph databases using the Gremlin API offering. Like many up and coming trends in the data universe, you may hear people talk about Graph databases and roll your eyes thinking ‘here we go’."
},
{
"code": null,
"e": 728,
"s": 394,
"text": "But there are many situations that we could model using a graph format. The most obvious example you might come across is Social Networks. I know Mike, who knows Gemma and we all enjoy hiking. Gemma has gone hiking in Raglan, New Zealand and I live in New Zealand, etc. etc. (We’ll build the basics of this example in a little bit!)."
},
{
"code": null,
"e": 952,
"s": 728,
"text": "Modelling these relationships might be quite challenging to do in a traditional relational way, so using a graph data model would be quite nice to do, but what is a graph database and can we build one using Azure Cosmos DB."
},
{
"code": null,
"e": 1155,
"s": 952,
"text": "The purpose of this article is to just introduce what Graph Databases are at a basic level and then show you how you can start building Graph Databases using the Gremlin API offering in Azure Cosmos DB."
},
{
"code": null,
"e": 1184,
"s": 1155,
"text": "So what are Graph Databases?"
},
{
"code": null,
"e": 1286,
"s": 1184,
"text": "A graph is a structure that is composed of vertices and edges, which can have a number of properties."
},
{
"code": null,
"e": 1503,
"s": 1286,
"text": "Vertices or Nodes represent objects. Within our graph databases, we can determine the nodes in our graph by identifying entities within our use cases. Bearing this in mind, our nodes could represent entities such as:"
},
{
"code": null,
"e": 1514,
"s": 1503,
"text": "A customer"
},
{
"code": null,
"e": 1526,
"s": 1514,
"text": "An employee"
},
{
"code": null,
"e": 1536,
"s": 1526,
"text": "A product"
},
{
"code": null,
"e": 1545,
"s": 1536,
"text": "An order"
},
{
"code": null,
"e": 1704,
"s": 1545,
"text": "Edges are what the relationships between vertices or edges are. For example, a person might know another person, or that person might have visited a location."
},
{
"code": null,
"e": 1970,
"s": 1704,
"text": "Properties describe information about the vertices and edges. For example, properties in vertices might include information about the person, such as their name, age or hair color. In edges, this might include information about how these two people know each other."
},
{
"code": null,
"e": 2083,
"s": 1970,
"text": "This data model can also be referred to as a Property Graph Model, which is what is supported by Azure Cosmos DB"
},
{
"code": null,
"e": 2335,
"s": 2083,
"text": "We typically implement graph databases as NoSQL stores since we need the flexibility that schema-free data stores provide. This can also provide us with a data model that we can change quickly that has minimal impact on the applications that use them."
},
{
"code": null,
"e": 2550,
"s": 2335,
"text": "Graph Databases can provide us with high-performance levels even as the data inside our databases grows. Even as our relationships grow in complexity, we can still get a high level of performance from our database."
},
{
"code": null,
"e": 2670,
"s": 2550,
"text": "In a relational database, the performance of our queries decrease as soon as our relationships become more complicated."
},
{
"code": null,
"e": 2812,
"s": 2670,
"text": "As I mentioned earlier, we can add more relationships and data to our graph database without it having a massive impact on our functionality."
},
{
"code": null,
"e": 2943,
"s": 2812,
"text": "However, If we have high volumes of transactions that we need to process in our applications, then our graph database will suffer."
},
{
"code": null,
"e": 2986,
"s": 2943,
"text": "OK, what could I use a Graph Database for?"
},
{
"code": null,
"e": 3170,
"s": 2986,
"text": "There are several use cases where we could deploy a graph database. Since I currently work for a bank, I’ve had a look at deploying graph databases for the purpose of fraud analytics."
},
{
"code": null,
"e": 3427,
"s": 3170,
"text": "Building recommendation engines and social networks would also be good situations where we could use Graph Databases. In these cases, we can use graphs to infer relationships based on interactions and activities that our users make or have previously made."
},
{
"code": null,
"e": 3647,
"s": 3427,
"text": "Another cool example of where we could use Graph databases would be for the use of master data management. We could use graphs to see how our data within our organisation is connected, what types of users query it, etc."
},
{
"code": null,
"e": 3691,
"s": 3647,
"text": "Why build a graph database using Cosmos DB?"
},
{
"code": null,
"e": 3887,
"s": 3691,
"text": "We could run a Graph Database on our own computers. There’s no reason why you couldn’t just download Apache Tinkerpop, run some commands on the Gremlin Console and you’d have your graph database."
},
{
"code": null,
"e": 4114,
"s": 3887,
"text": "BUT, graph databases in productions are HUGE systems. Large graph databases in productions would have billions and billions of vertices and edges in them, so it’d be impractical for us to try and run this on our own computers."
},
{
"code": null,
"e": 4366,
"s": 4114,
"text": "That’s where Cosmos DB can come in and help us. We can build Graph Databases in Azure Cosmos DB thanks to the Gremlin API offering. This gives us a fully managed graph database in the cloud that can elastically grow in terms of storage and throughput."
},
{
"code": null,
"e": 4405,
"s": 4366,
"text": "Creating a Graph Database in Cosmos DB"
},
{
"code": null,
"e": 4562,
"s": 4405,
"text": "Let’s get on with building a Graph Database using Cosmos DB. Go to the Azure Portal and click Create a New Resource. Under Databases, click Azure Cosmos DB."
},
{
"code": null,
"e": 4761,
"s": 4562,
"text": "Now we have to configure it. We give it a name, put it in a resource group and a location close to us. The most important thing here is to ensure that the Gremlin (graph) option is chosen as the API"
},
{
"code": null,
"e": 4949,
"s": 4761,
"text": "Wait a few minutes and we’ll have our Cosmos DB account with the Gremlin API ready to go. Let’s create our first Graph database and add a graph to it so we can execute some queries in it."
},
{
"code": null,
"e": 5079,
"s": 4949,
"text": "When your account has been provisioned, you’ll be taken to an overview page. Click Add Graph to set up your first Graph Database."
},
{
"code": null,
"e": 5445,
"s": 5079,
"text": "I’m just going to set up a basic graph for this tutorial, I’ve created a Database called PeopleDB, adding a graph to it called PeopleGraph and providing a partition key call hobby which will contain the values of our hobbies. I’m going to keep the maximum RU value at 400 since we’re not going to do any major operations for this tutorial. Click OK to provision it."
},
{
"code": null,
"e": 5476,
"s": 5445,
"text": "Running some queries in Cosmos"
},
{
"code": null,
"e": 5759,
"s": 5476,
"text": "Now that we have our graph set up, let’s build our people scenario that I referred to earlier. For this, we’ll add some vertices that represent People within our graph. They’ll all have properties for their first name, last name, age, hobby, where they are from and where they live."
},
{
"code": null,
"e": 5815,
"s": 5759,
"text": "We can add these vertices by running the below queries:"
},
{
"code": null,
"e": 6644,
"s": 5815,
"text": "// Add Willg.addV('person').property('firstName', 'Will').property('lastName', 'Velida').property('age', 28).property('userid', 1).property('hobby', 'kayaking').property('from', 'UK').property('lives', 'NZ')// Add Gemmag.addV('person').property('firstName', 'Gemma').property('lastName', 'Wright').property('age', 30).property('userid', 2).property('hobby', 'hiking').property('from', 'NZ').property('lives', 'NZ')// Add Mikeg.addV('person').property('firstName', 'Mike').property('lastName', 'Smith').property('age', 30).property('userid', 3).property('hobby', 'kayaking').property('from', 'NZ').property('lives', 'NZ')// Add Sloang.addV('person').property('firstName', 'Sloan').property('lastName', 'Timms').property('age', 21).property('userid', 4).property('hobby', 'kayaking').property('from', 'UK').property('lives', 'NZ')"
},
{
"code": null,
"e": 6756,
"s": 6644,
"text": "Now we can add some edges that will represent the relationships between our vertices in our People application."
},
{
"code": null,
"e": 7168,
"s": 6756,
"text": "// Will Knows Gemmag.V().hasLabel('person').has('firstName', 'Will').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Gemma'))// Sloan Knows Willg.V().hasLabel('person').has('firstName', 'Sloan').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Will'))// Mike Knows Gemmag.V().hasLabel('person').has('firstName', 'Will').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Gemma'))"
},
{
"code": null,
"e": 7332,
"s": 7168,
"text": "Now that we’ve added everything, we can run some simple queries. Let’s run a query that returns all the people in our graph database that have kayaking as a hobby."
},
{
"code": null,
"e": 7422,
"s": 7332,
"text": "// Select everyone who kayaks as a hobbyg.V().hasLabel('person').has('hobby', 'kayaking')"
},
{
"code": null,
"e": 7576,
"s": 7422,
"text": "We see the results returned as a graph like so. Three people were returned as results in our query and we can click on each node to see their properties."
},
{
"code": null,
"e": 7590,
"s": 7576,
"text": "In Conclusion"
},
{
"code": null,
"e": 7831,
"s": 7590,
"text": "This was a really basic example just to introduce you to Graph databases and how you can build them using Azure Cosmos DB. In a future blog post, I’ll dive a little bit deeper into how to run Gremlin queries and compare them to SQL queries."
}
] |
Scansets in C - GeeksforGeeks
|
06 Jul, 2021
scanf family functions support scanset specifiers which are represented by %[]. Inside scanset, we can specify single character or range of characters. While processing scanset, scanf will process only those characters which are part of scanset. We can define scanset by putting characters inside square brackets. Please note that the scansets are case-sensitive.
We can also use scanset by providing comma in between the character you want to add.
example: scanf(%s[A-Z,_,a,b,c]s,str);
This will scan all the specified character in the scanset.Let us see with example. Below example will store only capital letters to character array ‘str’, any other character will not be stored inside character array.
C
/* A simple scanset example */#include <stdio.h> int main(void){ char str[128]; printf("Enter a string: "); scanf("%[A-Z]s", str); printf("You entered: %s\n", str); return 0;}
[root@centos-6 C]# ./scan-set
Enter a string: GEEKs_for_geeks
You entered: GEEK
If first character of scanset is ‘^’, then the specifier will stop reading after first occurrence of that character. For example, given below scanset will read all characters but stops after first occurrence of ‘o’
C
scanf("%[^o]s", str);
Let us see with example.
C
/* Another scanset example with ^ */#include <stdio.h> int main(void){ char str[128]; printf("Enter a string: "); scanf("%[^o]s", str); printf("You entered: %s\n", str); return 0;}
[root@centos-6 C]# ./scan-set
Enter a string: http://geeks for geeks
You entered: http://geeks f
[root@centos-6 C]#
Let us implement gets() function by using scan set. gets() function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF found.
C
/* implementation of gets() function using scanset */#include <stdio.h> int main(void){ char str[128]; printf("Enter a string with spaces: "); scanf("%[^\n]s", str); printf("You entered: %s\n", str); return 0;}
[root@centos-6 C]# ./gets
Enter a string with spaces: Geeks For Geeks
You entered: Geeks For Geeks
[root@centos-6 C]#
As a side note, using gets() may not be a good idea in general. Check below note from Linux man page.Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. Also see this post.This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
tornado711
nidhi_biet
neeraj844singh
varshagumber28
C-Input and Output Quiz
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
Structures in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
std::string class in C++
Data Types in C
|
[
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 24878,
"s": 24514,
"text": "scanf family functions support scanset specifiers which are represented by %[]. Inside scanset, we can specify single character or range of characters. While processing scanset, scanf will process only those characters which are part of scanset. We can define scanset by putting characters inside square brackets. Please note that the scansets are case-sensitive."
},
{
"code": null,
"e": 24963,
"s": 24878,
"text": "We can also use scanset by providing comma in between the character you want to add."
},
{
"code": null,
"e": 25001,
"s": 24963,
"text": "example: scanf(%s[A-Z,_,a,b,c]s,str);"
},
{
"code": null,
"e": 25219,
"s": 25001,
"text": "This will scan all the specified character in the scanset.Let us see with example. Below example will store only capital letters to character array ‘str’, any other character will not be stored inside character array."
},
{
"code": null,
"e": 25221,
"s": 25219,
"text": "C"
},
{
"code": "/* A simple scanset example */#include <stdio.h> int main(void){ char str[128]; printf(\"Enter a string: \"); scanf(\"%[A-Z]s\", str); printf(\"You entered: %s\\n\", str); return 0;}",
"e": 25415,
"s": 25221,
"text": null
},
{
"code": null,
"e": 25502,
"s": 25415,
"text": " [root@centos-6 C]# ./scan-set \n Enter a string: GEEKs_for_geeks\n You entered: GEEK"
},
{
"code": null,
"e": 25718,
"s": 25502,
"text": "If first character of scanset is ‘^’, then the specifier will stop reading after first occurrence of that character. For example, given below scanset will read all characters but stops after first occurrence of ‘o’ "
},
{
"code": null,
"e": 25720,
"s": 25718,
"text": "C"
},
{
"code": "scanf(\"%[^o]s\", str);",
"e": 25742,
"s": 25720,
"text": null
},
{
"code": null,
"e": 25767,
"s": 25742,
"text": "Let us see with example."
},
{
"code": null,
"e": 25769,
"s": 25767,
"text": "C"
},
{
"code": "/* Another scanset example with ^ */#include <stdio.h> int main(void){ char str[128]; printf(\"Enter a string: \"); scanf(\"%[^o]s\", str); printf(\"You entered: %s\\n\", str); return 0;}",
"e": 25968,
"s": 25769,
"text": null
},
{
"code": null,
"e": 26094,
"s": 25968,
"text": " [root@centos-6 C]# ./scan-set \n Enter a string: http://geeks for geeks\n You entered: http://geeks f\n [root@centos-6 C]# "
},
{
"code": null,
"e": 26267,
"s": 26094,
"text": "Let us implement gets() function by using scan set. gets() function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF found."
},
{
"code": null,
"e": 26269,
"s": 26267,
"text": "C"
},
{
"code": "/* implementation of gets() function using scanset */#include <stdio.h> int main(void){ char str[128]; printf(\"Enter a string with spaces: \"); scanf(\"%[^\\n]s\", str); printf(\"You entered: %s\\n\", str); return 0;}",
"e": 26498,
"s": 26269,
"text": null
},
{
"code": null,
"e": 26626,
"s": 26498,
"text": " [root@centos-6 C]# ./gets \n Enter a string with spaces: Geeks For Geeks\n You entered: Geeks For Geeks\n [root@centos-6 C]# "
},
{
"code": null,
"e": 27263,
"s": 26626,
"text": "As a side note, using gets() may not be a good idea in general. Check below note from Linux man page.Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. Also see this post.This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27274,
"s": 27263,
"text": "tornado711"
},
{
"code": null,
"e": 27285,
"s": 27274,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27300,
"s": 27285,
"text": "neeraj844singh"
},
{
"code": null,
"e": 27315,
"s": 27300,
"text": "varshagumber28"
},
{
"code": null,
"e": 27339,
"s": 27315,
"text": "C-Input and Output Quiz"
},
{
"code": null,
"e": 27350,
"s": 27339,
"text": "C Language"
},
{
"code": null,
"e": 27448,
"s": 27350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27460,
"s": 27448,
"text": "fork() in C"
},
{
"code": null,
"e": 27492,
"s": 27460,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 27514,
"s": 27492,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27531,
"s": 27514,
"text": "Substring in C++"
},
{
"code": null,
"e": 27578,
"s": 27531,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 27594,
"s": 27578,
"text": "Structures in C"
},
{
"code": null,
"e": 27632,
"s": 27594,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27659,
"s": 27632,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 27684,
"s": 27659,
"text": "std::string class in C++"
}
] |
Binary Search Tree insert with Parent Pointer in C++
|
We can insert new node into the BST in recursive manner. In that case we return the address of the root of each subtree. Here we will see another approach, where parent pointer will need to be maintained. Parent pointer will be helpful to find ancestor of a node etc.
The idea is to store the address of the left and right subtrees, we set parent pointers of the returned pointers after recursive call. This confirms that all parent pointers are set during insertion. The parent of root is set to null.
insert(node, key) −
begin
if node is null, then create a new node and return
if the key is less than the key of node, then
create a new node with key
add the new node with the left pointer or node
else if key is greater or equal to the key of node, then
create a new node with key
add the new node at the right pointer of the node
end if
return node
end
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right, *parent;
};
struct Node *getNode(int item) {
Node *temp = new Node;
temp->data = item;
temp->left = temp->right = temp->parent = NULL;
return temp;
}
void inorderTraverse(struct Node *root) {
if (root != NULL) {
inorderTraverse(root->left);
cout << root->data << " ";
if (root->parent == NULL)
cout << "NULL" << endl;
else
cout << root->parent->data << endl;
inorderTraverse(root->right);
}
}
struct Node* insert(struct Node* node, int key) {
if (node == NULL) return getNode(key);
if (key < node->data) { //to the left subtree
Node *left_child = insert(node->left, key);
node->left = left_child;
left_child->parent = node;
}
else if (key > node->data) { // to the right subtree
Node *right_child = insert(node->right, key);
node->right = right_child;
right_child->parent = node;
}
return node;
}
int main() {
struct Node *root = NULL;
root = insert(root, 100);
insert(root, 60);
insert(root, 40);
insert(root, 80);
insert(root, 140);
insert(root, 120);
insert(root, 160);
inorderTraverse(root);
}
40 60
60 100
80 60
100 NULL
120 140
140 100
160 140
|
[
{
"code": null,
"e": 1330,
"s": 1062,
"text": "We can insert new node into the BST in recursive manner. In that case we return the address of the root of each subtree. Here we will see another approach, where parent pointer will need to be maintained. Parent pointer will be helpful to find ancestor of a node etc."
},
{
"code": null,
"e": 1565,
"s": 1330,
"text": "The idea is to store the address of the left and right subtrees, we set parent pointers of the returned pointers after recursive call. This confirms that all parent pointers are set during insertion. The parent of root is set to null."
},
{
"code": null,
"e": 1585,
"s": 1565,
"text": "insert(node, key) −"
},
{
"code": null,
"e": 1982,
"s": 1585,
"text": "begin\n if node is null, then create a new node and return\n if the key is less than the key of node, then\n create a new node with key\n add the new node with the left pointer or node\n else if key is greater or equal to the key of node, then\n create a new node with key\n add the new node at the right pointer of the node\n end if\n return node\nend"
},
{
"code": null,
"e": 3233,
"s": 1982,
"text": "#include<iostream>\nusing namespace std;\nclass Node {\n public:\n int data;\n Node *left, *right, *parent;\n};\nstruct Node *getNode(int item) {\n Node *temp = new Node;\n temp->data = item;\n temp->left = temp->right = temp->parent = NULL;\n return temp;\n}\nvoid inorderTraverse(struct Node *root) {\n if (root != NULL) {\n inorderTraverse(root->left);\n cout << root->data << \" \";\n if (root->parent == NULL)\n cout << \"NULL\" << endl;\n else\n cout << root->parent->data << endl;\n inorderTraverse(root->right);\n }\n}\nstruct Node* insert(struct Node* node, int key) {\n if (node == NULL) return getNode(key);\n if (key < node->data) { //to the left subtree\n Node *left_child = insert(node->left, key);\n node->left = left_child;\n left_child->parent = node;\n }\n else if (key > node->data) { // to the right subtree\n Node *right_child = insert(node->right, key);\n node->right = right_child;\n right_child->parent = node;\n }\n return node;\n}\nint main() {\n struct Node *root = NULL;\n root = insert(root, 100);\n insert(root, 60);\n insert(root, 40);\n insert(root, 80);\n insert(root, 140);\n insert(root, 120);\n insert(root, 160);\n inorderTraverse(root);\n}"
},
{
"code": null,
"e": 3285,
"s": 3233,
"text": "40 60\n60 100\n80 60\n100 NULL\n120 140\n140 100\n160 140"
}
] |
How to check if an input is an integer using C/C++?
|
Here we will see how to check whether a given input is integer string or a normal string. The integer string will hold all characters that are in range 0 – 9. The solution is very simple, we will simply go through each characters one by one, and check whether it is numeric or not. If it is numeric, then point to the next, otherwise return false value.
#include <iostream>
using namespace std;
bool isNumeric(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false; //when one non numeric value is found, return false
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isNumeric(str))
cout << "This is a Number" << endl;
else
cout << "This is not a number";
}
Enter a string: 5687
This is a Number
Enter a string: 584asS
This is not a number
|
[
{
"code": null,
"e": 1416,
"s": 1062,
"text": "Here we will see how to check whether a given input is integer string or a normal string. The integer string will hold all characters that are in range 0 – 9. The solution is very simple, we will simply go through each characters one by one, and check whether it is numeric or not. If it is numeric, then point to the next, otherwise return false value."
},
{
"code": null,
"e": 1841,
"s": 1416,
"text": "#include <iostream>\nusing namespace std;\nbool isNumeric(string str) {\n for (int i = 0; i < str.length(); i++)\n if (isdigit(str[i]) == false)\n return false; //when one non numeric value is found, return false\n return true;\n}\nint main() {\n string str;\n cout << \"Enter a string: \";\n cin >> str;\n if (isNumeric(str))\n cout << \"This is a Number\" << endl;\n else\n cout << \"This is not a number\";\n}"
},
{
"code": null,
"e": 1879,
"s": 1841,
"text": "Enter a string: 5687\nThis is a Number"
},
{
"code": null,
"e": 1923,
"s": 1879,
"text": "Enter a string: 584asS\nThis is not a number"
}
] |
Building a weather app using Openweathermap and Flask | by Sagun Shrestha | Towards Data Science
|
In this article, we will learn the basics of using a web API. We will use Python and Flask to create a simple backend that calls Openweathermap API and render the result in a web page.
If you want to skip the article and access code, head over to the GitHub repo.
Goto https://home.openweathermap.org/users/sign_up and sign up for a free plan if you haven’t already. Then visit the API key section https://home.openweathermap.org/api_keys to get your key. You can use the default key or generate a new one as you wish. You may have to wait for a while to get your key verified.
I am using Python 3.6 for this project so make sure you have 3.6 or higher version installed. Beside that, we will only need Flask for web and requests for making API calls. Create a new file called requirements.txt and add the dependencies. Your file should look like this:
Flask==1.1.1requests==2.22.0
Now use the following command to install requirements:
pip install -r requirements.txt
Or if you just want to install Flask and requests
pip install Flask requests
You may need to use pip3 instead of pip and sudo for linux and mac if pip is occupied by Python 2.7.
Going through the documentation, the simplest way to make requests is using the city name. The url to make request will look like this
http://api.openweathermap.org/data/2.5/weather?q=city_name&APPID=your_api_key
You can copy paste the url and replace the city_name and your_api_key with appropriate value to see the result.
If you want to see a formatted JSON response, you can use a chrome extension called JSONView. Your response will look something like this in browser.
All the data shown are pretty much straightforward. The temperature is shown inside the main key. name and id both can be used to query the API.
Flask is a simple, lightweight web framework. It can be used to create minimal web applications and APIs. Create a file named weather_app.py and initialize our Flask application.
In the above snippet, we are importing Flask and creating an instance of it. @app.route() is used to create routes. Here we are creating one for the home page which basically renders “Welcome to weather app” inside h1 tag in the browser. We will add more routes later. Inside the if block, we are running the app with debug=True which tells Flask that the app is running in debug mode. The advantage of running in debug mode is that if we make changes in our app, Flask will automatically detect those changes and reload the server for us. Make sure you set this to False when moving into production.
Run the server by typing the following command in your terminal/cmd
python weather_app.py
If you have python 2 and 3 both installed (usually in linux and mac), you will have to use python3 instead of python
python3 weather_app.py
You will see something like this
* Debug mode: on* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 123-456-789
Visit http://127.0.0.1:5000/ and you will see “Welcome to weather app” in h1. To quit the server, press CTRL + C.
Now we want a way to enter a city name and get the current weather for that place. For that we will have to create another route, let’s call it /city which takes the city’s name as an argument and returns the temperature.
Now to test the API, visit the url
http://127.0.0.1:5000/city?q=kathmandu
You will see a response like this in your browser:
Current temperature of Kathmandu is 15.0 °C
Whatever we pass in our url as query will be stored in request.args as a dictionary. Here, q=kathmandu is the query string so the request.args will hold {“q": “kathmandu"}. Then we are using the get method to access the dictionary by keys. You can learn more about dictionaries in this tutorial. Same is the case while getting current temperature.
current_temperature = response.get('main', {}).get('temp')
You can change kathmandu with the city you want. The list of cities along with id can be downloaded from this link.
The final weather_app.py file should look like this.
At this point, we have created a simple application that gets the current temperature for a certain city. This article should give you an idea of how Flask works and how you can use an API with Python. You can access the code from my GitHub repo.
From here, you can extend the functionality and add more features to the app such as
adding a search buttonusing templates and a nice looking interfacedisplaying the list of cities and respective idsquerying by id along with namedisplay other data like max, min temperature, humidity, wind, etc
adding a search button
using templates and a nice looking interface
displaying the list of cities and respective ids
querying by id along with name
display other data like max, min temperature, humidity, wind, etc
Let me know if you have any problems while following this tutorial or need help adding more features.
|
[
{
"code": null,
"e": 357,
"s": 172,
"text": "In this article, we will learn the basics of using a web API. We will use Python and Flask to create a simple backend that calls Openweathermap API and render the result in a web page."
},
{
"code": null,
"e": 436,
"s": 357,
"text": "If you want to skip the article and access code, head over to the GitHub repo."
},
{
"code": null,
"e": 750,
"s": 436,
"text": "Goto https://home.openweathermap.org/users/sign_up and sign up for a free plan if you haven’t already. Then visit the API key section https://home.openweathermap.org/api_keys to get your key. You can use the default key or generate a new one as you wish. You may have to wait for a while to get your key verified."
},
{
"code": null,
"e": 1025,
"s": 750,
"text": "I am using Python 3.6 for this project so make sure you have 3.6 or higher version installed. Beside that, we will only need Flask for web and requests for making API calls. Create a new file called requirements.txt and add the dependencies. Your file should look like this:"
},
{
"code": null,
"e": 1054,
"s": 1025,
"text": "Flask==1.1.1requests==2.22.0"
},
{
"code": null,
"e": 1109,
"s": 1054,
"text": "Now use the following command to install requirements:"
},
{
"code": null,
"e": 1141,
"s": 1109,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 1191,
"s": 1141,
"text": "Or if you just want to install Flask and requests"
},
{
"code": null,
"e": 1218,
"s": 1191,
"text": "pip install Flask requests"
},
{
"code": null,
"e": 1319,
"s": 1218,
"text": "You may need to use pip3 instead of pip and sudo for linux and mac if pip is occupied by Python 2.7."
},
{
"code": null,
"e": 1454,
"s": 1319,
"text": "Going through the documentation, the simplest way to make requests is using the city name. The url to make request will look like this"
},
{
"code": null,
"e": 1532,
"s": 1454,
"text": "http://api.openweathermap.org/data/2.5/weather?q=city_name&APPID=your_api_key"
},
{
"code": null,
"e": 1644,
"s": 1532,
"text": "You can copy paste the url and replace the city_name and your_api_key with appropriate value to see the result."
},
{
"code": null,
"e": 1794,
"s": 1644,
"text": "If you want to see a formatted JSON response, you can use a chrome extension called JSONView. Your response will look something like this in browser."
},
{
"code": null,
"e": 1939,
"s": 1794,
"text": "All the data shown are pretty much straightforward. The temperature is shown inside the main key. name and id both can be used to query the API."
},
{
"code": null,
"e": 2118,
"s": 1939,
"text": "Flask is a simple, lightweight web framework. It can be used to create minimal web applications and APIs. Create a file named weather_app.py and initialize our Flask application."
},
{
"code": null,
"e": 2719,
"s": 2118,
"text": "In the above snippet, we are importing Flask and creating an instance of it. @app.route() is used to create routes. Here we are creating one for the home page which basically renders “Welcome to weather app” inside h1 tag in the browser. We will add more routes later. Inside the if block, we are running the app with debug=True which tells Flask that the app is running in debug mode. The advantage of running in debug mode is that if we make changes in our app, Flask will automatically detect those changes and reload the server for us. Make sure you set this to False when moving into production."
},
{
"code": null,
"e": 2787,
"s": 2719,
"text": "Run the server by typing the following command in your terminal/cmd"
},
{
"code": null,
"e": 2809,
"s": 2787,
"text": "python weather_app.py"
},
{
"code": null,
"e": 2926,
"s": 2809,
"text": "If you have python 2 and 3 both installed (usually in linux and mac), you will have to use python3 instead of python"
},
{
"code": null,
"e": 2949,
"s": 2926,
"text": "python3 weather_app.py"
},
{
"code": null,
"e": 2982,
"s": 2949,
"text": "You will see something like this"
},
{
"code": null,
"e": 3127,
"s": 2982,
"text": "* Debug mode: on* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 123-456-789"
},
{
"code": null,
"e": 3241,
"s": 3127,
"text": "Visit http://127.0.0.1:5000/ and you will see “Welcome to weather app” in h1. To quit the server, press CTRL + C."
},
{
"code": null,
"e": 3463,
"s": 3241,
"text": "Now we want a way to enter a city name and get the current weather for that place. For that we will have to create another route, let’s call it /city which takes the city’s name as an argument and returns the temperature."
},
{
"code": null,
"e": 3498,
"s": 3463,
"text": "Now to test the API, visit the url"
},
{
"code": null,
"e": 3537,
"s": 3498,
"text": "http://127.0.0.1:5000/city?q=kathmandu"
},
{
"code": null,
"e": 3588,
"s": 3537,
"text": "You will see a response like this in your browser:"
},
{
"code": null,
"e": 3632,
"s": 3588,
"text": "Current temperature of Kathmandu is 15.0 °C"
},
{
"code": null,
"e": 3980,
"s": 3632,
"text": "Whatever we pass in our url as query will be stored in request.args as a dictionary. Here, q=kathmandu is the query string so the request.args will hold {“q\": “kathmandu\"}. Then we are using the get method to access the dictionary by keys. You can learn more about dictionaries in this tutorial. Same is the case while getting current temperature."
},
{
"code": null,
"e": 4039,
"s": 3980,
"text": "current_temperature = response.get('main', {}).get('temp')"
},
{
"code": null,
"e": 4155,
"s": 4039,
"text": "You can change kathmandu with the city you want. The list of cities along with id can be downloaded from this link."
},
{
"code": null,
"e": 4208,
"s": 4155,
"text": "The final weather_app.py file should look like this."
},
{
"code": null,
"e": 4455,
"s": 4208,
"text": "At this point, we have created a simple application that gets the current temperature for a certain city. This article should give you an idea of how Flask works and how you can use an API with Python. You can access the code from my GitHub repo."
},
{
"code": null,
"e": 4540,
"s": 4455,
"text": "From here, you can extend the functionality and add more features to the app such as"
},
{
"code": null,
"e": 4750,
"s": 4540,
"text": "adding a search buttonusing templates and a nice looking interfacedisplaying the list of cities and respective idsquerying by id along with namedisplay other data like max, min temperature, humidity, wind, etc"
},
{
"code": null,
"e": 4773,
"s": 4750,
"text": "adding a search button"
},
{
"code": null,
"e": 4818,
"s": 4773,
"text": "using templates and a nice looking interface"
},
{
"code": null,
"e": 4867,
"s": 4818,
"text": "displaying the list of cities and respective ids"
},
{
"code": null,
"e": 4898,
"s": 4867,
"text": "querying by id along with name"
},
{
"code": null,
"e": 4964,
"s": 4898,
"text": "display other data like max, min temperature, humidity, wind, etc"
}
] |
How to connect to my MongoDB table by command line?
|
In order to connect to my table by command line, you need to use db command
db.yourCollectionName.find();
Let’s say we have a database “sample” with some collections. First check the current database
> use sample;
switched to db sample
> db;
Sample
Now we have reached the database sample. The database “sample” is having the following collections:
> show collections;
This will produce the following output
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation
Here is the correct way of connecting to a table i.e. collection. You need to use db command. Following is the query
> db.userInformation.find();
This will produce the following output
{ "_id" : ObjectId("5c6a765964f3d70fcc9147f5"), "Name" : "John", "Age" : 30, "isStudent" : false, "Subjects" : [ "Introduction to java", "Introduction to MongoDB" ] }
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "In order to connect to my table by command line, you need to use db command"
},
{
"code": null,
"e": 1168,
"s": 1138,
"text": "db.yourCollectionName.find();"
},
{
"code": null,
"e": 1262,
"s": 1168,
"text": "Let’s say we have a database “sample” with some collections. First check the current database"
},
{
"code": null,
"e": 1431,
"s": 1262,
"text": "> use sample;\nswitched to db sample\n> db;\nSample\nNow we have reached the database sample. The database “sample” is having the following collections:\n> show collections;"
},
{
"code": null,
"e": 1470,
"s": 1431,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2033,
"s": 1470,
"text": "arraySizeErrorDemo\nbasicInformationDemo\ncopyThisCollectionToSampleDatabaseDemo\ndeleteAllRecordsDemo\ndeleteDocuments\ndeleteDocumentsDemo\ndeleteSomeInformation\ndocumentWithAParticularFieldValueDemo\nemployee\nfindListOfIdsDemo\nfindSubstring\ngetAllRecordsFromSourceCollectionDemo\ngetElementWithMaxIdDemo\ninternalArraySizeDemo\nlargestDocumentDemo\nmakingStudentInformationClone\noppositeAddToSetDemo\nprettyDemo\nreturnOnlyUniqueValuesDemo\nselectWhereInDemo\nsourceCollection\nstudentInformation\nsumOfValueDemo\nsumTwoFieldsDemo\ntruncateDemo\nupdateInformation\nuserInformation"
},
{
"code": null,
"e": 2150,
"s": 2033,
"text": "Here is the correct way of connecting to a table i.e. collection. You need to use db command. Following is the query"
},
{
"code": null,
"e": 2179,
"s": 2150,
"text": "> db.userInformation.find();"
},
{
"code": null,
"e": 2218,
"s": 2179,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2385,
"s": 2218,
"text": "{ \"_id\" : ObjectId(\"5c6a765964f3d70fcc9147f5\"), \"Name\" : \"John\", \"Age\" : 30, \"isStudent\" : false, \"Subjects\" : [ \"Introduction to java\", \"Introduction to MongoDB\" ] }"
}
] |
The Binary Multidimensional Knapsack Problem (MKP) | by Mohammed Agha | Towards Data Science
|
There are numerous posts addressing the knapsack problem as both an integer programming problem, and as a simple example to explain dynamic programming. Not enough content on the multidimensional knapsack problem though. In this post, I will go through the Multidimensional Knapsack Problem ‘MKP’, point to where we can find benchmark instances, provide my used code file to read these instances (in Python), then proceed with how to model an MKP instance on Python and solve it with IBM CPLEX. This article is intended to serve as a gentle introduction to the MKP and a simple tutorial on how to code it for interested optimization enthusiasts and young practitioners.
The MKP is an NP-hard extension to the standard binary knapsack selection problem. The goal is the same; to find a subset of items that maximizes the total profit/gain (objective function), however, the difference is that instead of having a single knapsack or resource, there are multiple knapsacks/resources (each is a separate constraint) and the subset of items should not violate the capacity of any of these knapsacks. Avid readers interested in the various versions of knapsack problems are referred to the book Knapsack Problems by Kellerer, Pferschy and Pisinger for more details. Here we will only limit our scope to the binary MKP.
The mathematical formulation of the MKP is:
(MKP) maximize z = ∑ c. x
Subject to:
A.x ≤ b, ∀ i = 1,...., n
x ∈ {0,1},∀ j = 1,....,m
where c is the profit-per-item vector, b is the right hand side vector or the capacity of each knapsack, x is a vector of binary variables indicating whether an item is selected, and A is the constraints’ coefficients matrix. The number of variables is m while the number of constraints is n.
The widely used benchmark instances in the literature can be found at the online OR-Library with a complete explanation about the format and content of each benchmark set. These instances are either test problems collected from the literature or test instances solved in Chu & Beasley (1998) [1]. Benchmark sets vary in number of variables (columns) and number of constraints (rows) with the hardest benchmark set containing 30 instances, each comprising 500 columns and 30 rows (columns and variables are used interchangeaby in this post, similarly, rows and constraints).
Benchmark sets found at the online OR-Library are text files containing the:
number of test instances in each set,
size of each instance (i.e., number of columns and rows),
objective function coefficients (profits),
constraints coefficients (resource consumption of each variable from each knapsack/resource) and,
right hand side (capacity of each knapsack).
To simplify things, we will consider a text file containing data of only one instance. At this GitHub repository you can find text files, each with data pertaining to a single instance, in addition to a function that reads the text files, populates the instance and prepares the input to be used in the mathematical model (c, A and b).
There are multiple linear programming open-source or commercial solvers that can be used to model an optimization problem. This informative post is a very good start to learn how to use some solvers.
Optimization Modeling in Python: PuLP, Gurobi, and CPLEX
I will be using IBM CPLEX since I have more experience working with it. CPLEX should be installed in advance and has a free edition for students and academics.
We start by importing relevant libraries:
import cplexfrom docplex.mp.model import Model
we will also import the file containing the function that reads and populates the MKP instances (refered to in the previous section).
# Import the reading function import MKP_populate_function as rdmkp
next, we will call the function on an instance and get our parameters to be used in creating the model:
# Call the function on a given instanceinstance = 'mknapcb1_1.txt'c, A, b = rdmkp.MKPpopulate(instance)# Define the ranges for variables and constraintsnCols, nRows = range(len(c)), range(len(b))
I usually use the last additional step in the previous code block to define ranges for the number of variables and number of constraints. They mainly represent the sets of variables and constraints. It’ll prove handy when we define variables and constraints in the mathematical model.
As we have our parameters ready, we will proceed with creating an empty model:
# Create an empty model mkp = Model('MKP')
Now we will augment the empty model by defining the decision variables. In MKP, variables are binary so we will declare them accordingly. You will notice that I added lower and upper bounds which are not needed for binary variables, however, sometimes I want to check the linear relaxation bound, so I keep bounds defined in all my models but change the binary type to continuous.
# Define decision variables x = mkp.binary_var_list(nCols, lb = 0, ub = 1, name = 'x')
Each constraint represents a different knapsack with its own capacity. The consumption of each item from this knapsack is given by the elements in the A matrix.
# Declare constraintsconstraints = mkp.add_constraints(sum(A[i][j] * x[j] for j in nCols) <= b[i] for i in nRows)
The next step is to create the objective function, which is to maxmimize the sum of the profits of the chosen subset of items. Adding the objective function as a KPI is a good practice that makes reporting results better. I learned this from more seasoned modelers.
# Declare the objective functionprofit = mkp.sum(c[j] * x[j] for j in nCols)# Add Obj. Function as a kpi for better reporting of results mkp.add_kpi(profit, 'profit') # Add objective function to the model as a maximization typeobj = mkp.maximize(profit)
What remains now is to solve the created model and report the results.
# Solving the modelmkp.solve()# Reporting resultsmkp.report()
The following method, when called, provides information about the number of variables and their types, the number of constraints and the type of the problem along with the sense of the objective function(maximization or minimization).
mkp.print_information()
It should be noted that CPLEX finds the exact solution to the MKP. While it seems fast in solving small instances, it takes longer time to solve larger size integer/binary instances.
As Prof. J. E. Beasly puts it: “What makes solving the problem easy when it is small is precisely what makes it become very hard very quickly as the problem size increases”.
This is simply because when the problem size is relatively small, we can enumerate all possible solutions and examine their feasibility and find the optimum one. However, when the problem size grows, the number of solutions grows faster and we cannot check all of them in feasible time. Other methods can be used such as heursitics/metaheuristics but maybe we can discuss them in another post.
If you liked this content you might be interested in this post about a very interesting application in networks optimization where we used social network analysis to measure and minimize disruption to teams.
[1] PC Chu, JE Beasley, A genetic algorithm for the multidimensional knapsack problem (1998), Journal of heuristics 4 (1), 63–86
|
[
{
"code": null,
"e": 842,
"s": 172,
"text": "There are numerous posts addressing the knapsack problem as both an integer programming problem, and as a simple example to explain dynamic programming. Not enough content on the multidimensional knapsack problem though. In this post, I will go through the Multidimensional Knapsack Problem ‘MKP’, point to where we can find benchmark instances, provide my used code file to read these instances (in Python), then proceed with how to model an MKP instance on Python and solve it with IBM CPLEX. This article is intended to serve as a gentle introduction to the MKP and a simple tutorial on how to code it for interested optimization enthusiasts and young practitioners."
},
{
"code": null,
"e": 1485,
"s": 842,
"text": "The MKP is an NP-hard extension to the standard binary knapsack selection problem. The goal is the same; to find a subset of items that maximizes the total profit/gain (objective function), however, the difference is that instead of having a single knapsack or resource, there are multiple knapsacks/resources (each is a separate constraint) and the subset of items should not violate the capacity of any of these knapsacks. Avid readers interested in the various versions of knapsack problems are referred to the book Knapsack Problems by Kellerer, Pferschy and Pisinger for more details. Here we will only limit our scope to the binary MKP."
},
{
"code": null,
"e": 1529,
"s": 1485,
"text": "The mathematical formulation of the MKP is:"
},
{
"code": null,
"e": 1555,
"s": 1529,
"text": "(MKP) maximize z = ∑ c. x"
},
{
"code": null,
"e": 1567,
"s": 1555,
"text": "Subject to:"
},
{
"code": null,
"e": 1592,
"s": 1567,
"text": "A.x ≤ b, ∀ i = 1,...., n"
},
{
"code": null,
"e": 1617,
"s": 1592,
"text": "x ∈ {0,1},∀ j = 1,....,m"
},
{
"code": null,
"e": 1910,
"s": 1617,
"text": "where c is the profit-per-item vector, b is the right hand side vector or the capacity of each knapsack, x is a vector of binary variables indicating whether an item is selected, and A is the constraints’ coefficients matrix. The number of variables is m while the number of constraints is n."
},
{
"code": null,
"e": 2484,
"s": 1910,
"text": "The widely used benchmark instances in the literature can be found at the online OR-Library with a complete explanation about the format and content of each benchmark set. These instances are either test problems collected from the literature or test instances solved in Chu & Beasley (1998) [1]. Benchmark sets vary in number of variables (columns) and number of constraints (rows) with the hardest benchmark set containing 30 instances, each comprising 500 columns and 30 rows (columns and variables are used interchangeaby in this post, similarly, rows and constraints)."
},
{
"code": null,
"e": 2561,
"s": 2484,
"text": "Benchmark sets found at the online OR-Library are text files containing the:"
},
{
"code": null,
"e": 2599,
"s": 2561,
"text": "number of test instances in each set,"
},
{
"code": null,
"e": 2657,
"s": 2599,
"text": "size of each instance (i.e., number of columns and rows),"
},
{
"code": null,
"e": 2700,
"s": 2657,
"text": "objective function coefficients (profits),"
},
{
"code": null,
"e": 2798,
"s": 2700,
"text": "constraints coefficients (resource consumption of each variable from each knapsack/resource) and,"
},
{
"code": null,
"e": 2843,
"s": 2798,
"text": "right hand side (capacity of each knapsack)."
},
{
"code": null,
"e": 3179,
"s": 2843,
"text": "To simplify things, we will consider a text file containing data of only one instance. At this GitHub repository you can find text files, each with data pertaining to a single instance, in addition to a function that reads the text files, populates the instance and prepares the input to be used in the mathematical model (c, A and b)."
},
{
"code": null,
"e": 3379,
"s": 3179,
"text": "There are multiple linear programming open-source or commercial solvers that can be used to model an optimization problem. This informative post is a very good start to learn how to use some solvers."
},
{
"code": null,
"e": 3436,
"s": 3379,
"text": "Optimization Modeling in Python: PuLP, Gurobi, and CPLEX"
},
{
"code": null,
"e": 3596,
"s": 3436,
"text": "I will be using IBM CPLEX since I have more experience working with it. CPLEX should be installed in advance and has a free edition for students and academics."
},
{
"code": null,
"e": 3638,
"s": 3596,
"text": "We start by importing relevant libraries:"
},
{
"code": null,
"e": 3685,
"s": 3638,
"text": "import cplexfrom docplex.mp.model import Model"
},
{
"code": null,
"e": 3819,
"s": 3685,
"text": "we will also import the file containing the function that reads and populates the MKP instances (refered to in the previous section)."
},
{
"code": null,
"e": 3887,
"s": 3819,
"text": "# Import the reading function import MKP_populate_function as rdmkp"
},
{
"code": null,
"e": 3991,
"s": 3887,
"text": "next, we will call the function on an instance and get our parameters to be used in creating the model:"
},
{
"code": null,
"e": 4187,
"s": 3991,
"text": "# Call the function on a given instanceinstance = 'mknapcb1_1.txt'c, A, b = rdmkp.MKPpopulate(instance)# Define the ranges for variables and constraintsnCols, nRows = range(len(c)), range(len(b))"
},
{
"code": null,
"e": 4472,
"s": 4187,
"text": "I usually use the last additional step in the previous code block to define ranges for the number of variables and number of constraints. They mainly represent the sets of variables and constraints. It’ll prove handy when we define variables and constraints in the mathematical model."
},
{
"code": null,
"e": 4551,
"s": 4472,
"text": "As we have our parameters ready, we will proceed with creating an empty model:"
},
{
"code": null,
"e": 4594,
"s": 4551,
"text": "# Create an empty model mkp = Model('MKP')"
},
{
"code": null,
"e": 4975,
"s": 4594,
"text": "Now we will augment the empty model by defining the decision variables. In MKP, variables are binary so we will declare them accordingly. You will notice that I added lower and upper bounds which are not needed for binary variables, however, sometimes I want to check the linear relaxation bound, so I keep bounds defined in all my models but change the binary type to continuous."
},
{
"code": null,
"e": 5067,
"s": 4975,
"text": "# Define decision variables x = mkp.binary_var_list(nCols, lb = 0, ub = 1, name = 'x')"
},
{
"code": null,
"e": 5228,
"s": 5067,
"text": "Each constraint represents a different knapsack with its own capacity. The consumption of each item from this knapsack is given by the elements in the A matrix."
},
{
"code": null,
"e": 5342,
"s": 5228,
"text": "# Declare constraintsconstraints = mkp.add_constraints(sum(A[i][j] * x[j] for j in nCols) <= b[i] for i in nRows)"
},
{
"code": null,
"e": 5608,
"s": 5342,
"text": "The next step is to create the objective function, which is to maxmimize the sum of the profits of the chosen subset of items. Adding the objective function as a KPI is a good practice that makes reporting results better. I learned this from more seasoned modelers."
},
{
"code": null,
"e": 5873,
"s": 5608,
"text": "# Declare the objective functionprofit = mkp.sum(c[j] * x[j] for j in nCols)# Add Obj. Function as a kpi for better reporting of results mkp.add_kpi(profit, 'profit') # Add objective function to the model as a maximization typeobj = mkp.maximize(profit)"
},
{
"code": null,
"e": 5944,
"s": 5873,
"text": "What remains now is to solve the created model and report the results."
},
{
"code": null,
"e": 6006,
"s": 5944,
"text": "# Solving the modelmkp.solve()# Reporting resultsmkp.report()"
},
{
"code": null,
"e": 6241,
"s": 6006,
"text": "The following method, when called, provides information about the number of variables and their types, the number of constraints and the type of the problem along with the sense of the objective function(maximization or minimization)."
},
{
"code": null,
"e": 6265,
"s": 6241,
"text": "mkp.print_information()"
},
{
"code": null,
"e": 6448,
"s": 6265,
"text": "It should be noted that CPLEX finds the exact solution to the MKP. While it seems fast in solving small instances, it takes longer time to solve larger size integer/binary instances."
},
{
"code": null,
"e": 6622,
"s": 6448,
"text": "As Prof. J. E. Beasly puts it: “What makes solving the problem easy when it is small is precisely what makes it become very hard very quickly as the problem size increases”."
},
{
"code": null,
"e": 7016,
"s": 6622,
"text": "This is simply because when the problem size is relatively small, we can enumerate all possible solutions and examine their feasibility and find the optimum one. However, when the problem size grows, the number of solutions grows faster and we cannot check all of them in feasible time. Other methods can be used such as heursitics/metaheuristics but maybe we can discuss them in another post."
},
{
"code": null,
"e": 7224,
"s": 7016,
"text": "If you liked this content you might be interested in this post about a very interesting application in networks optimization where we used social network analysis to measure and minimize disruption to teams."
}
] |
Display MySQL table values using Java
|
For this, you can use the ResultSet concept. For connection, we will be using the MySQL JDBC Driver.
Let us create a table −
mysql> create table demo87
-> (
-> name varchar(20),
-> age int
-> )
-> ;
Query OK, 0 rows affected (0.62
Insert some records into the table with the help of insert command −
mysql> insert into demo87 values('John',21);
Query OK, 1 row affected (0.15
mysql> insert into demo87 values('David',23);
Query OK, 1 row affected (0.12
mysql> insert into demo87 values('Bob',22);
Query OK, 1 row affected (0.16
Display records from the table using select statement −
mysql> select *from demo87;
This will produce the following output −
+-------+------+
| name | age |+-------+------+
| John | 21 || David | 23 |
| Bob | 22 |+-------+------+
3 rows in set (0.00 sec)
| name | age |
| John | 21 |
| Bob | 22 |
3 rows in set (0.00 sec)
Following is the Java code to display table values in MySQL −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import com.mysql.jdbc.Statement;
public class TableValuesDemo {
public static void main(String[] args) {
Connection con = null;
Statement statement = null;
try {
HashMap hm = new HashMap<>();
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
statement = (Statement) con.createStatement();
String sql;
sql = "select *from demo87";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
hm.put(resultSet.getString("name"), resultSet.getInt("age"));
}
System.out.println(hm);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This will produce the following output −
{Bob=22, John=21, David=23}
Following is the snapshot of sample output −
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "For this, you can use the ResultSet concept. For connection, we will be using the MySQL JDBC Driver."
},
{
"code": null,
"e": 1187,
"s": 1163,
"text": "Let us create a table −"
},
{
"code": null,
"e": 1308,
"s": 1187,
"text": "mysql> create table demo87\n -> (\n -> name varchar(20),\n -> age int\n -> )\n -> ;\nQuery OK, 0 rows affected (0.62"
},
{
"code": null,
"e": 1377,
"s": 1308,
"text": "Insert some records into the table with the help of insert command −"
},
{
"code": null,
"e": 1607,
"s": 1377,
"text": "mysql> insert into demo87 values('John',21);\nQuery OK, 1 row affected (0.15\n\nmysql> insert into demo87 values('David',23);\nQuery OK, 1 row affected (0.12\n\nmysql> insert into demo87 values('Bob',22);\nQuery OK, 1 row affected (0.16"
},
{
"code": null,
"e": 1663,
"s": 1607,
"text": "Display records from the table using select statement −"
},
{
"code": null,
"e": 1691,
"s": 1663,
"text": "mysql> select *from demo87;"
},
{
"code": null,
"e": 1732,
"s": 1691,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1873,
"s": 1732,
"text": "+-------+------+\n| name | age |+-------+------+\n| John | 21 || David | 23 |\n| Bob | 22 |+-------+------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1890,
"s": 1873,
"text": "| name | age |"
},
{
"code": null,
"e": 1907,
"s": 1890,
"text": "| John | 21 |"
},
{
"code": null,
"e": 1924,
"s": 1907,
"text": "| Bob | 22 |"
},
{
"code": null,
"e": 1949,
"s": 1924,
"text": "3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2011,
"s": 1949,
"text": "Following is the Java code to display table values in MySQL −"
},
{
"code": null,
"e": 2928,
"s": 2011,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.util.ArrayList;\nimport java.util.HashMap;\n\nimport com.mysql.jdbc.Statement;\n\npublic class TableValuesDemo {\n public static void main(String[] args) {\n Connection con = null;\n Statement statement = null;\n try {\n HashMap hm = new HashMap<>();\n Class.forName(\"com.mysql.jdbc.Driver\");\n con = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/sampledatabase\", \"root\", \"123456\");\n statement = (Statement) con.createStatement();\n String sql;\n sql = \"select *from demo87\";\n ResultSet resultSet = statement.executeQuery(sql);\n while (resultSet.next()) {\n hm.put(resultSet.getString(\"name\"), resultSet.getInt(\"age\"));\n }\n System.out.println(hm);\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2969,
"s": 2928,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2997,
"s": 2969,
"text": "{Bob=22, John=21, David=23}"
},
{
"code": null,
"e": 3042,
"s": 2997,
"text": "Following is the snapshot of sample output −"
}
] |
Interfacing OLED Display with ESP32
|
The combination of OLED with ESP32 is so popular that there are some boards of ESP32 with the OLED integrated. We'll, however, assume that you will be using a separate OLED module with your ESP32 board. If you have an OLED module, it perhaps looks like the image below.
Like the MPU6050 module that we discussed in a previous chapter, the OLED module also generally uses I2C for communication. Therefore, the connection will be similar to the MPU6050 module. You need to connect the SDA line to pin 21 on ESP32, SCL line to pin 22, GND to GND, and VCC to 3V3 pin
There are a number of libraries available for interfacing the OLED display with ESP32. You are free to use anyone you are comfortable with. For this example, we will use the 'ESP8266 and ESP32 OLED driver for SSD1306 displays, by ThingPulse, Fabrice Weinberg'. You can install this library from Tools −> Manage Libraries. It can also be found on GitHub
The code becomes very simple thanks to the library we just installed. We will run a counter code, which will just count the seconds since the last reset and print them on the OLED module. The code can be found on GitHub
We begin with the inclusion of the SSD1306 library.
#include "SSD1306Wire.h"
Next, we define the OLED pins and its I2C address. Note that some OLED modules contain an additional Reset pin. A good example is the ESP32 TTGO board, which comes with an inbuilt OLED display. For that board, pin 16 is the reset pin. If you are connecting an external OLED module to your ESP32, you will most likely not use the Reset pin. The I2C address of 0x3c is generally common for all OLED modules.
//OLED related variables
#define OLED_ADDR 0x3c
#define OLED_SDA 21//4 //TTGO board without SD Card has OLED SDA connected to pin 4 of ESP32
#define OLED_SCL 22//15 //TTGO board without SD Card has OLED SCL connected to pin 15 of ESP32
#define OLED_RST 16 //Optional, TTGO board contains OLED_RST connected to pin 16 of ESP32
Next, we create the OLED display object and the counter variable.
SSD1306Wire display(OLED_ADDR, OLED_SDA, OLED_SCL);
int counter = 0;
After that, we define two functions. One for initializing the OLED display (this function is redundant if your OLED module doesn't contain a reset pin), and the other for printing text messages on the OLED Display. The showOLEDMessage() function breaks down the OLED display area into 3 lines and asks for 3 strings, one for each line.
void initOLED() {
pinMode(OLED_RST, OUTPUT);
//Give a low to high pulse to the OLED display to reset it
//This is optional and not required for OLED modules not containing a reset pin
digitalWrite(OLED_RST, LOW);
delay(20);
digitalWrite(OLED_RST, HIGH);
}
void showOLEDMessage(String line1, String line2, String line3) {
display.init(); // clears screen
display.setFont(ArialMT_Plain_16);
display.drawString(0, 0, line1); // adds to buffer
display.drawString(0, 20, line2);
display.drawString(0, 40, line3);
display.display(); // displays content in buffer
}
Finally, in the setup, we just initialize the OLED display, and in the loop, we just utilize the first two lines of the display to show the counter.
void setup() {
// put your setup code here, to run once:
initOLED();
}
void loop() {
// put your main code here, to run repeatedly
showOLEDMessage("Num seconds is: ", String(counter), "");
delay(1000);
counter = counter+1;
}
That's it. Congratulations on displaying your first text statements on the OLED display.
54 Lectures
4.5 hours
Frahaan Hussain
20 Lectures
5 hours
Azaz Patel
20 Lectures
4 hours
Azaz Patel
0 Lectures
0 mins
Eduonix Learning Solutions
169 Lectures
12.5 hours
Kalob Taulien
29 Lectures
2 hours
Zenva
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2453,
"s": 2183,
"text": "The combination of OLED with ESP32 is so popular that there are some boards of ESP32 with the OLED integrated. We'll, however, assume that you will be using a separate OLED module with your ESP32 board. If you have an OLED module, it perhaps looks like the image below."
},
{
"code": null,
"e": 2746,
"s": 2453,
"text": "Like the MPU6050 module that we discussed in a previous chapter, the OLED module also generally uses I2C for communication. Therefore, the connection will be similar to the MPU6050 module. You need to connect the SDA line to pin 21 on ESP32, SCL line to pin 22, GND to GND, and VCC to 3V3 pin"
},
{
"code": null,
"e": 3099,
"s": 2746,
"text": "There are a number of libraries available for interfacing the OLED display with ESP32. You are free to use anyone you are comfortable with. For this example, we will use the 'ESP8266 and ESP32 OLED driver for SSD1306 displays, by ThingPulse, Fabrice Weinberg'. You can install this library from Tools −> Manage Libraries. It can also be found on GitHub"
},
{
"code": null,
"e": 3319,
"s": 3099,
"text": "The code becomes very simple thanks to the library we just installed. We will run a counter code, which will just count the seconds since the last reset and print them on the OLED module. The code can be found on GitHub"
},
{
"code": null,
"e": 3371,
"s": 3319,
"text": "We begin with the inclusion of the SSD1306 library."
},
{
"code": null,
"e": 3397,
"s": 3371,
"text": "#include \"SSD1306Wire.h\"\n"
},
{
"code": null,
"e": 3804,
"s": 3397,
"text": "Next, we define the OLED pins and its I2C address. Note that some OLED modules contain an additional Reset pin. A good example is the ESP32 TTGO board, which comes with an inbuilt OLED display. For that board, pin 16 is the reset pin. If you are connecting an external OLED module to your ESP32, you will most likely not use the Reset pin. The I2C address of 0x3c is generally common for all OLED modules. "
},
{
"code": null,
"e": 4156,
"s": 3804,
"text": "//OLED related variables\n#define OLED_ADDR 0x3c\n#define OLED_SDA 21//4 //TTGO board without SD Card has OLED SDA connected to pin 4 of ESP32\n#define OLED_SCL 22//15 //TTGO board without SD Card has OLED SCL connected to pin 15 of ESP32\n#define OLED_RST 16 //Optional, TTGO board contains OLED_RST connected to pin 16 of ESP32\n"
},
{
"code": null,
"e": 4224,
"s": 4156,
"text": "Next, we create the OLED display object and the counter variable. "
},
{
"code": null,
"e": 4296,
"s": 4224,
"text": "SSD1306Wire display(OLED_ADDR, OLED_SDA, OLED_SCL); \nint counter = 0;\n"
},
{
"code": null,
"e": 4633,
"s": 4296,
"text": "After that, we define two functions. One for initializing the OLED display (this function is redundant if your OLED module doesn't contain a reset pin), and the other for printing text messages on the OLED Display. The showOLEDMessage() function breaks down the OLED display area into 3 lines and asks for 3 strings, one for each line. "
},
{
"code": null,
"e": 5278,
"s": 4633,
"text": "void initOLED() {\n pinMode(OLED_RST, OUTPUT);\n //Give a low to high pulse to the OLED display to reset it\n //This is optional and not required for OLED modules not containing a reset pin\n digitalWrite(OLED_RST, LOW);\n delay(20);\n digitalWrite(OLED_RST, HIGH);\n}\nvoid showOLEDMessage(String line1, String line2, String line3) {\n display.init(); // clears screen\n display.setFont(ArialMT_Plain_16);\n display.drawString(0, 0, line1); // adds to buffer\n display.drawString(0, 20, line2);\n display.drawString(0, 40, line3);\n display.display(); // displays content in buffer\n}"
},
{
"code": null,
"e": 5427,
"s": 5278,
"text": "Finally, in the setup, we just initialize the OLED display, and in the loop, we just utilize the first two lines of the display to show the counter."
},
{
"code": null,
"e": 5670,
"s": 5427,
"text": "void setup() {\n // put your setup code here, to run once:\n initOLED();\n}\nvoid loop() {\n // put your main code here, to run repeatedly\n showOLEDMessage(\"Num seconds is: \", String(counter), \"\");\n delay(1000);\n counter = counter+1;\n}"
},
{
"code": null,
"e": 5759,
"s": 5670,
"text": "That's it. Congratulations on displaying your first text statements on the OLED display."
},
{
"code": null,
"e": 5794,
"s": 5759,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5811,
"s": 5794,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5844,
"s": 5811,
"text": "\n 20 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5856,
"s": 5844,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5889,
"s": 5856,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5901,
"s": 5889,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5931,
"s": 5901,
"text": "\n 0 Lectures \n 0 mins\n"
},
{
"code": null,
"e": 5959,
"s": 5931,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5996,
"s": 5959,
"text": "\n 169 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6011,
"s": 5996,
"text": " Kalob Taulien"
},
{
"code": null,
"e": 6044,
"s": 6011,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6051,
"s": 6044,
"text": " Zenva"
},
{
"code": null,
"e": 6058,
"s": 6051,
"text": " Print"
},
{
"code": null,
"e": 6069,
"s": 6058,
"text": " Add Notes"
}
] |
CNN based face detector from dlib | by Arun Ponnusamy | Towards Data Science
|
If you are into any sort of image processing, computer vision or machine learning, chances are high that you might have come across/used dlib somewhere in your journey.
According to dlib’s github page, dlib is a toolkit for making real world machine learning and data analysis applications in C++. While the library is originally written in C++, it has good, easy to use Python bindings.
I have majorly used dlib for face detection and facial landmark detection. The frontal face detector in dlib works really well. It is simple and just works out of the box.
This detector is based on histogram of oriented gradients (HOG) and linear SVM. (Explaining how this detector works is beyond the scope of this blog post. Probably a topic to discuss for another day)
While the HOG+SVM based face detector has been around for a while and has gathered a good amount of users, I am not sure how many of us noticed the CNN (Convolutional Neural Network) based face detector available in dlib. Honestly, I didn’t. I accidentally came across it while browsing through dlib’s github repository.
My immediate thoughts were like,
“Wow. Is it better than the existing detector ? How accurate it is ? Can it detect the face in all angles ? Can it run on real-time video ?”
Well, that’s what this post is all about. Trying to find out the answers for the above questions.
If you have ever used the HOG based face detector in dlib, you probably know that it will not detect faces at odd angles. It is meant to be a good “frontal” face detector and it is, indeed.
It detects faces even when they are not perfectly frontal to a good extend. Which is really good for a frontal face detector. But you can only expect so much from it.
Meanwhile, the CNN based detector is capable of detecting faces almost in all angles. Unfortunately it is not suitable for real time video. It is meant to be executed on a GPU. To get the same speed as the HOG based detector you might need to run on a powerful Nvidia GPU.
Nevertheless, this should not stop us from trying it on still images.
In the remainder of this post, I am going to show you how you can use the CNN based face detector from dlib on images and compare the results with HOG based detector with ready to use Python code.
Let’s jump right in and start coding.
Let’s start by importing the necessary packages. If you have not installed these packages, you can install them by typing the below command in the Terminal.
pip install opencv-python dlib argparse time
(argparse and time are more likely to come pre-installed with Python)
If you are not using virtual environment for Python, I highly recommend to start using it. You can checkout my previous post if you need a starting point.
This script requires two command line arguments.
input image
model weights
You can get the model weights file by typing the below command in Terminal.
wget http://arunponnusamy.com/files/mmod_human_face_detector.dat
By default the code looks for the model file in the current directory if you don’t provide any specific path.
For example, you can run by typing
python cnn-face-detector-dlib.py -i input.jpg
(This will work if both the input.jpg and model weights file are in the current directory same as the python script)
Or you can run by typing,
python cnn-face-detector-dlib.py -i <path-to-image-input> -w <path-to-weights-file>
(python cnn-face-detector-dlib.py -i ~/Downloads/input.jpg -w ~/Downloads/mmod_human_face_detector.dat)
(I assume you have the latest version of Python installed. Must be 3.0+)
Read the input image provided and check whether its of type None. If so print the error statement and exit the program.
Initialize the HOG based and CNN based face detectors which we will be applying on the input image.
For the HOG based one we don’t need to provide any file to initialize. It is pre-built inside dlib. Just calling the method should be enough.
For the CNN based one, we need to provide the weights file to initialize with.
Let’s apply the detector on the input image.
faces_hog = hog_face_detector(image, 1)
1 is the number of times it should upsample the image. By default, 1 works for most cases. (Upsampling the image helps to detect smaller faces)
time.time() can be used to measure the execution time in seconds.
Once the detection is done, we can loop over the detected face(s). To draw box over the detected faces, we need to provide (x,y) — top left corner and (x+w, y+h) — bottom right corner to OpenCV.
Rectangle format in dlib and OpenCV are a bit different. We can use skimage here to directly overlay the dlib rectangle object on the image. But getting familiar with the conversion between dlib and OpenCV will be helpful when we are processing real time video with OpenCV.
cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)
The above line will draw a rectangle on the detected face on the input image. (0,255,0) represents the color of the box in BGR order (green in this case). 2 represents the thickness of the line.
The process is almost same as the previous detector except the returned rectangle object by the detector. Let’s use color red for CNN detected faces to differentiate from HOG.
To differentiate the detections from HOG and CNN detectors, lets’s write which color is which at the top right corner of the image.
cv2.imshow() will display the output image when you run the script.
cv2.waitKey() specifies how long the display window should wait before closing. For example cv2.waitKey(500) will display the window for 500ms(0.5 sec). If you don’t pass any number it will wait until you press any key.
cv2.imwrite() will save the output image to disk.
It’s a good practice to release all the windows once we are done with the display.
The full code is available here.
To give you an idea of the execution time, for a 620x420 image , HOG takes around 0.2 seconds whereas CNN takes around 3.3 seconds on CPU (Intel i5 Dual core 1.8GHz).
The exact number might vary depending on your hardware setup and the size of the image. The bottom line is HOG takes less than a second whereas CNN takes few seconds on CPU.
Here comes the important part.
Can the CNN based detector detect faces at odd angles (read non-frontal) which the HOG based detector might fail to detect?
Well, the answer is “almost”. ( I have not tested it rigorously to give a confident “yes”. But as far as I have tested, it is working really well for non-frontal images).
Let’s look at some of the examples where HOG based detector fails but CNN is able to detect.
and the list goes on.
This is not to say that HOG based detector doesn’t work at all for non-frontal images. In fact it does detect some of the non-frontal images such as below.
In this post we looked at the lesser known CNN based face detector from dlib and compared the output with the widely used HOG+SVM based face detector.
We observed that the CNN based detector works really well for non-frontal faces at odd angles where HOG based detector struggles.
Unfortunately, CNN based detector is computationally heavy and is not suitable for real-time video at the moment. If you have noticed the detector function call ( dlib.cnn_face_detection_model_v1() ) it says v1 which is version 1. Which means there is a high chance that the author might come up with the next version which is light weight and can be used for real-time applications.
Let’s hope for a light weight version in the next release of dlib.
Well, that’s all for now. Feel free to share your thoughts in the comments below or you can reach out to me on twitter at @ponnusamy_arun .
If you found this post interesting, you can subscribe to my blog to get notified when new posts go live. (Don’t worry I publish only one or two posts per month)
Cheers.
If you are concerned about real time performance, checkout the face detector available in cvlib. It detects faces in (almost) all angles and is capable of processing real time input.
|
[
{
"code": null,
"e": 341,
"s": 172,
"text": "If you are into any sort of image processing, computer vision or machine learning, chances are high that you might have come across/used dlib somewhere in your journey."
},
{
"code": null,
"e": 560,
"s": 341,
"text": "According to dlib’s github page, dlib is a toolkit for making real world machine learning and data analysis applications in C++. While the library is originally written in C++, it has good, easy to use Python bindings."
},
{
"code": null,
"e": 732,
"s": 560,
"text": "I have majorly used dlib for face detection and facial landmark detection. The frontal face detector in dlib works really well. It is simple and just works out of the box."
},
{
"code": null,
"e": 932,
"s": 732,
"text": "This detector is based on histogram of oriented gradients (HOG) and linear SVM. (Explaining how this detector works is beyond the scope of this blog post. Probably a topic to discuss for another day)"
},
{
"code": null,
"e": 1253,
"s": 932,
"text": "While the HOG+SVM based face detector has been around for a while and has gathered a good amount of users, I am not sure how many of us noticed the CNN (Convolutional Neural Network) based face detector available in dlib. Honestly, I didn’t. I accidentally came across it while browsing through dlib’s github repository."
},
{
"code": null,
"e": 1286,
"s": 1253,
"text": "My immediate thoughts were like,"
},
{
"code": null,
"e": 1427,
"s": 1286,
"text": "“Wow. Is it better than the existing detector ? How accurate it is ? Can it detect the face in all angles ? Can it run on real-time video ?”"
},
{
"code": null,
"e": 1525,
"s": 1427,
"text": "Well, that’s what this post is all about. Trying to find out the answers for the above questions."
},
{
"code": null,
"e": 1715,
"s": 1525,
"text": "If you have ever used the HOG based face detector in dlib, you probably know that it will not detect faces at odd angles. It is meant to be a good “frontal” face detector and it is, indeed."
},
{
"code": null,
"e": 1882,
"s": 1715,
"text": "It detects faces even when they are not perfectly frontal to a good extend. Which is really good for a frontal face detector. But you can only expect so much from it."
},
{
"code": null,
"e": 2155,
"s": 1882,
"text": "Meanwhile, the CNN based detector is capable of detecting faces almost in all angles. Unfortunately it is not suitable for real time video. It is meant to be executed on a GPU. To get the same speed as the HOG based detector you might need to run on a powerful Nvidia GPU."
},
{
"code": null,
"e": 2225,
"s": 2155,
"text": "Nevertheless, this should not stop us from trying it on still images."
},
{
"code": null,
"e": 2422,
"s": 2225,
"text": "In the remainder of this post, I am going to show you how you can use the CNN based face detector from dlib on images and compare the results with HOG based detector with ready to use Python code."
},
{
"code": null,
"e": 2460,
"s": 2422,
"text": "Let’s jump right in and start coding."
},
{
"code": null,
"e": 2617,
"s": 2460,
"text": "Let’s start by importing the necessary packages. If you have not installed these packages, you can install them by typing the below command in the Terminal."
},
{
"code": null,
"e": 2662,
"s": 2617,
"text": "pip install opencv-python dlib argparse time"
},
{
"code": null,
"e": 2732,
"s": 2662,
"text": "(argparse and time are more likely to come pre-installed with Python)"
},
{
"code": null,
"e": 2887,
"s": 2732,
"text": "If you are not using virtual environment for Python, I highly recommend to start using it. You can checkout my previous post if you need a starting point."
},
{
"code": null,
"e": 2936,
"s": 2887,
"text": "This script requires two command line arguments."
},
{
"code": null,
"e": 2948,
"s": 2936,
"text": "input image"
},
{
"code": null,
"e": 2962,
"s": 2948,
"text": "model weights"
},
{
"code": null,
"e": 3038,
"s": 2962,
"text": "You can get the model weights file by typing the below command in Terminal."
},
{
"code": null,
"e": 3103,
"s": 3038,
"text": "wget http://arunponnusamy.com/files/mmod_human_face_detector.dat"
},
{
"code": null,
"e": 3213,
"s": 3103,
"text": "By default the code looks for the model file in the current directory if you don’t provide any specific path."
},
{
"code": null,
"e": 3248,
"s": 3213,
"text": "For example, you can run by typing"
},
{
"code": null,
"e": 3294,
"s": 3248,
"text": "python cnn-face-detector-dlib.py -i input.jpg"
},
{
"code": null,
"e": 3411,
"s": 3294,
"text": "(This will work if both the input.jpg and model weights file are in the current directory same as the python script)"
},
{
"code": null,
"e": 3437,
"s": 3411,
"text": "Or you can run by typing,"
},
{
"code": null,
"e": 3521,
"s": 3437,
"text": "python cnn-face-detector-dlib.py -i <path-to-image-input> -w <path-to-weights-file>"
},
{
"code": null,
"e": 3625,
"s": 3521,
"text": "(python cnn-face-detector-dlib.py -i ~/Downloads/input.jpg -w ~/Downloads/mmod_human_face_detector.dat)"
},
{
"code": null,
"e": 3698,
"s": 3625,
"text": "(I assume you have the latest version of Python installed. Must be 3.0+)"
},
{
"code": null,
"e": 3818,
"s": 3698,
"text": "Read the input image provided and check whether its of type None. If so print the error statement and exit the program."
},
{
"code": null,
"e": 3918,
"s": 3818,
"text": "Initialize the HOG based and CNN based face detectors which we will be applying on the input image."
},
{
"code": null,
"e": 4060,
"s": 3918,
"text": "For the HOG based one we don’t need to provide any file to initialize. It is pre-built inside dlib. Just calling the method should be enough."
},
{
"code": null,
"e": 4139,
"s": 4060,
"text": "For the CNN based one, we need to provide the weights file to initialize with."
},
{
"code": null,
"e": 4184,
"s": 4139,
"text": "Let’s apply the detector on the input image."
},
{
"code": null,
"e": 4224,
"s": 4184,
"text": "faces_hog = hog_face_detector(image, 1)"
},
{
"code": null,
"e": 4368,
"s": 4224,
"text": "1 is the number of times it should upsample the image. By default, 1 works for most cases. (Upsampling the image helps to detect smaller faces)"
},
{
"code": null,
"e": 4434,
"s": 4368,
"text": "time.time() can be used to measure the execution time in seconds."
},
{
"code": null,
"e": 4629,
"s": 4434,
"text": "Once the detection is done, we can loop over the detected face(s). To draw box over the detected faces, we need to provide (x,y) — top left corner and (x+w, y+h) — bottom right corner to OpenCV."
},
{
"code": null,
"e": 4903,
"s": 4629,
"text": "Rectangle format in dlib and OpenCV are a bit different. We can use skimage here to directly overlay the dlib rectangle object on the image. But getting familiar with the conversion between dlib and OpenCV will be helpful when we are processing real time video with OpenCV."
},
{
"code": null,
"e": 4956,
"s": 4903,
"text": "cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)"
},
{
"code": null,
"e": 5151,
"s": 4956,
"text": "The above line will draw a rectangle on the detected face on the input image. (0,255,0) represents the color of the box in BGR order (green in this case). 2 represents the thickness of the line."
},
{
"code": null,
"e": 5327,
"s": 5151,
"text": "The process is almost same as the previous detector except the returned rectangle object by the detector. Let’s use color red for CNN detected faces to differentiate from HOG."
},
{
"code": null,
"e": 5459,
"s": 5327,
"text": "To differentiate the detections from HOG and CNN detectors, lets’s write which color is which at the top right corner of the image."
},
{
"code": null,
"e": 5527,
"s": 5459,
"text": "cv2.imshow() will display the output image when you run the script."
},
{
"code": null,
"e": 5747,
"s": 5527,
"text": "cv2.waitKey() specifies how long the display window should wait before closing. For example cv2.waitKey(500) will display the window for 500ms(0.5 sec). If you don’t pass any number it will wait until you press any key."
},
{
"code": null,
"e": 5797,
"s": 5747,
"text": "cv2.imwrite() will save the output image to disk."
},
{
"code": null,
"e": 5880,
"s": 5797,
"text": "It’s a good practice to release all the windows once we are done with the display."
},
{
"code": null,
"e": 5913,
"s": 5880,
"text": "The full code is available here."
},
{
"code": null,
"e": 6080,
"s": 5913,
"text": "To give you an idea of the execution time, for a 620x420 image , HOG takes around 0.2 seconds whereas CNN takes around 3.3 seconds on CPU (Intel i5 Dual core 1.8GHz)."
},
{
"code": null,
"e": 6254,
"s": 6080,
"text": "The exact number might vary depending on your hardware setup and the size of the image. The bottom line is HOG takes less than a second whereas CNN takes few seconds on CPU."
},
{
"code": null,
"e": 6285,
"s": 6254,
"text": "Here comes the important part."
},
{
"code": null,
"e": 6409,
"s": 6285,
"text": "Can the CNN based detector detect faces at odd angles (read non-frontal) which the HOG based detector might fail to detect?"
},
{
"code": null,
"e": 6580,
"s": 6409,
"text": "Well, the answer is “almost”. ( I have not tested it rigorously to give a confident “yes”. But as far as I have tested, it is working really well for non-frontal images)."
},
{
"code": null,
"e": 6673,
"s": 6580,
"text": "Let’s look at some of the examples where HOG based detector fails but CNN is able to detect."
},
{
"code": null,
"e": 6695,
"s": 6673,
"text": "and the list goes on."
},
{
"code": null,
"e": 6851,
"s": 6695,
"text": "This is not to say that HOG based detector doesn’t work at all for non-frontal images. In fact it does detect some of the non-frontal images such as below."
},
{
"code": null,
"e": 7002,
"s": 6851,
"text": "In this post we looked at the lesser known CNN based face detector from dlib and compared the output with the widely used HOG+SVM based face detector."
},
{
"code": null,
"e": 7132,
"s": 7002,
"text": "We observed that the CNN based detector works really well for non-frontal faces at odd angles where HOG based detector struggles."
},
{
"code": null,
"e": 7516,
"s": 7132,
"text": "Unfortunately, CNN based detector is computationally heavy and is not suitable for real-time video at the moment. If you have noticed the detector function call ( dlib.cnn_face_detection_model_v1() ) it says v1 which is version 1. Which means there is a high chance that the author might come up with the next version which is light weight and can be used for real-time applications."
},
{
"code": null,
"e": 7583,
"s": 7516,
"text": "Let’s hope for a light weight version in the next release of dlib."
},
{
"code": null,
"e": 7723,
"s": 7583,
"text": "Well, that’s all for now. Feel free to share your thoughts in the comments below or you can reach out to me on twitter at @ponnusamy_arun ."
},
{
"code": null,
"e": 7884,
"s": 7723,
"text": "If you found this post interesting, you can subscribe to my blog to get notified when new posts go live. (Don’t worry I publish only one or two posts per month)"
},
{
"code": null,
"e": 7892,
"s": 7884,
"text": "Cheers."
}
] |
Get Random record from MongoDB?
|
To get a random record from MongoDB, you can use aggregate function. The syntax is as follows:
db.yourCollectionName.aggregate([{$sample:{size:1}}]);
To understand the above syntax, let us create a collection with some documents. The query to create collection is as follows:
>db.employeeInformation.insert({"EmployeeId":1,"EmployeeName":"Maxwell","EmployeeAge":26});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":2,"EmployeeName":"David","EmployeeAge":25});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":3,"EmployeeName":"Carol","EmployeeAge":24});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":4,"EmployeeName":"Bob","EmployeeAge":28});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":5,"EmployeeName":"Sam","EmployeeAge":27);
WriteResult({ "nInserted" : 1 })
Now you can display all documents from a collection with the help of find() method. The query is as follows:
> db.employeeInformation.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6d3079734e98fc0a434ae5"),
"EmployeeId" : 1,
"EmployeeName" : "Maxwell",
"EmployeeAge" : 26
}
{
"_id" : ObjectId("5c6d308c734e98fc0a434ae6"),
"EmployeeId" : 2,
"EmployeeName" : "David",
"EmployeeAge" : 25
}
{
"_id" : ObjectId("5c6d309d734e98fc0a434ae7"),
"EmployeeId" : 3,
"EmployeeName" : "Carol",
"EmployeeAge" : 24
}
{
"_id" : ObjectId("5c6d30ab734e98fc0a434ae8"),
"EmployeeId" : 4,
"EmployeeName" : "Bob",
"EmployeeAge" : 28
}
{
"_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),
"EmployeeId" : 5,
"EmployeeName" : "Sam",
"EmployeeAge" : 27
}
Here is the query to get random record:
> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();
The following is the output:
{
"_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),
"EmployeeId" : 5,
"EmployeeName" : "Sam",
"EmployeeAge" : 27
}
Let us get another random record using the same query:
> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();
The following is the output:
{
"_id" : ObjectId("5c6d308c734e98fc0a434ae6"),
"EmployeeId" : 2,
"EmployeeName" : "David",
"EmployeeAge" : 25
}
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "To get a random record from MongoDB, you can use aggregate function. The syntax is as follows:"
},
{
"code": null,
"e": 1212,
"s": 1157,
"text": "db.yourCollectionName.aggregate([{$sample:{size:1}}]);"
},
{
"code": null,
"e": 1338,
"s": 1212,
"text": "To understand the above syntax, let us create a collection with some documents. The query to create collection is as follows:"
},
{
"code": null,
"e": 1950,
"s": 1338,
"text": ">db.employeeInformation.insert({\"EmployeeId\":1,\"EmployeeName\":\"Maxwell\",\"EmployeeAge\":26});\nWriteResult({ \"nInserted\" : 1 })\n>db.employeeInformation.insert({\"EmployeeId\":2,\"EmployeeName\":\"David\",\"EmployeeAge\":25});\nWriteResult({ \"nInserted\" : 1 })\n>db.employeeInformation.insert({\"EmployeeId\":3,\"EmployeeName\":\"Carol\",\"EmployeeAge\":24});\nWriteResult({ \"nInserted\" : 1 })\n>db.employeeInformation.insert({\"EmployeeId\":4,\"EmployeeName\":\"Bob\",\"EmployeeAge\":28});\nWriteResult({ \"nInserted\" : 1 })\n>db.employeeInformation.insert({\"EmployeeId\":5,\"EmployeeName\":\"Sam\",\"EmployeeAge\":27);\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 2059,
"s": 1950,
"text": "Now you can display all documents from a collection with the help of find() method. The query is as follows:"
},
{
"code": null,
"e": 2101,
"s": 2059,
"text": "> db.employeeInformation.find().pretty();"
},
{
"code": null,
"e": 2130,
"s": 2101,
"text": "The following is the output:"
},
{
"code": null,
"e": 2753,
"s": 2130,
"text": "{\n \"_id\" : ObjectId(\"5c6d3079734e98fc0a434ae5\"),\n \"EmployeeId\" : 1,\n \"EmployeeName\" : \"Maxwell\",\n \"EmployeeAge\" : 26\n}\n{\n \"_id\" : ObjectId(\"5c6d308c734e98fc0a434ae6\"),\n \"EmployeeId\" : 2,\n \"EmployeeName\" : \"David\",\n \"EmployeeAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c6d309d734e98fc0a434ae7\"),\n \"EmployeeId\" : 3,\n \"EmployeeName\" : \"Carol\",\n \"EmployeeAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c6d30ab734e98fc0a434ae8\"),\n \"EmployeeId\" : 4,\n \"EmployeeName\" : \"Bob\",\n \"EmployeeAge\" : 28\n}\n{\n \"_id\" : ObjectId(\"5c6d30bb734e98fc0a434ae9\"),\n \"EmployeeId\" : 5,\n \"EmployeeName\" : \"Sam\",\n \"EmployeeAge\" : 27\n}"
},
{
"code": null,
"e": 2793,
"s": 2753,
"text": "Here is the query to get random record:"
},
{
"code": null,
"e": 2860,
"s": 2793,
"text": "> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();"
},
{
"code": null,
"e": 2889,
"s": 2860,
"text": "The following is the output:"
},
{
"code": null,
"e": 3012,
"s": 2889,
"text": "{\n \"_id\" : ObjectId(\"5c6d30bb734e98fc0a434ae9\"),\n \"EmployeeId\" : 5,\n \"EmployeeName\" : \"Sam\",\n \"EmployeeAge\" : 27\n}"
},
{
"code": null,
"e": 3067,
"s": 3012,
"text": "Let us get another random record using the same query:"
},
{
"code": null,
"e": 3134,
"s": 3067,
"text": "> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();"
},
{
"code": null,
"e": 3163,
"s": 3134,
"text": "The following is the output:"
},
{
"code": null,
"e": 3288,
"s": 3163,
"text": "{\n \"_id\" : ObjectId(\"5c6d308c734e98fc0a434ae6\"),\n \"EmployeeId\" : 2,\n \"EmployeeName\" : \"David\",\n \"EmployeeAge\" : 25\n}"
}
] |
How to create a simple MySQL function?
|
You can create a function using create function command. The syntax is as follows −
delimiter //
DROP FUNCTION if exists yourFunctionName;
CREATE FUNCTION yourFunctionName(Parameter1,...N) returns type
BEGIN
# declaring variables;
# MySQL statementns
END //
delimiter ;
First, here we will create a table and add some records in the table. After that, a simple function will be created. The following is the query to create a table −
mysql> create table ViewDemo
−> (
−> Id int,
−> Name varchar(200),
−> Age int
−> );
Query OK, 0 rows affected (0.58 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into ViewDemo values(1,'John',23);
Query OK, 1 row affected (0.15 sec)
mysql> insert into ViewDemo values(2,'Sam',24);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from ViewDemo;
The following is the output −
+------+------+------+
| Id | Name | Age |
+------+------+------+
| 1 | John | 23 |
| 2 | Sam | 24 |
+------+------+------+
2 rows in set (0.00 sec)
Now we will create a function that takes on integer parameters and returns strings. The purpose of this function is to search records with given id. If the given id matches with table id then it returns the name otherwise it will give an error message like not found.
The function is as follows −
mysql> SET GLOBAL log_bin_trust_function_creators = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> drop function if exists searchRecord;
->
-> create function searchRecord(yourId int) returns char(100)
-> begin
-> declare Name1 char(100) default "No Name Found For This Id";
-> select Name into Name1 from ViewDemo where Id =yourId;
-> return Name1;
-> end //
Query OK, 0 rows affected (0.21 sec)
Query OK, 0 rows affected (0.33 sec)
mysql> delimiter ;
Now to check the function is working with given id.
Case 1 − When the given id is present.
The query is as follows −
mysql> select searchRecord(2) as Found;
The following is the output −
+-------+
| Found |
+-------+
| Sam |
+-------+
1 row in set (0.00 sec)
Case 2 − When the given id is not present.
The query is as follows −
mysql> select searchRecord(100) as Found;
The following is the output displaing the record isn’t there −
+---------------------------+
| Found |
+---------------------------+
| No Name Found For This Id |
+---------------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "You can create a function using create function command. The syntax is as follows −"
},
{
"code": null,
"e": 1332,
"s": 1146,
"text": "delimiter //\nDROP FUNCTION if exists yourFunctionName;\nCREATE FUNCTION yourFunctionName(Parameter1,...N) returns type\nBEGIN\n# declaring variables;\n# MySQL statementns\nEND //\ndelimiter ;"
},
{
"code": null,
"e": 1496,
"s": 1332,
"text": "First, here we will create a table and add some records in the table. After that, a simple function will be created. The following is the query to create a table −"
},
{
"code": null,
"e": 1632,
"s": 1496,
"text": "mysql> create table ViewDemo\n −> (\n −> Id int,\n −> Name varchar(200),\n −> Age int\n −> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1708,
"s": 1632,
"text": "Insert records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 1878,
"s": 1708,
"text": "mysql> insert into ViewDemo values(1,'John',23);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ViewDemo values(2,'Sam',24);\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 1963,
"s": 1878,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 1993,
"s": 1963,
"text": "mysql> select *from ViewDemo;"
},
{
"code": null,
"e": 2023,
"s": 1993,
"text": "The following is the output −"
},
{
"code": null,
"e": 2186,
"s": 2023,
"text": "+------+------+------+\n| Id | Name | Age |\n+------+------+------+\n| 1 | John | 23 |\n| 2 | Sam | 24 |\n+------+------+------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2454,
"s": 2186,
"text": "Now we will create a function that takes on integer parameters and returns strings. The purpose of this function is to search records with given id. If the given id matches with table id then it returns the name otherwise it will give an error message like not found."
},
{
"code": null,
"e": 2483,
"s": 2454,
"text": "The function is as follows −"
},
{
"code": null,
"e": 2957,
"s": 2483,
"text": "mysql> SET GLOBAL log_bin_trust_function_creators = 1;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> drop function if exists searchRecord;\n ->\n -> create function searchRecord(yourId int) returns char(100)\n -> begin\n -> declare Name1 char(100) default \"No Name Found For This Id\";\n -> select Name into Name1 from ViewDemo where Id =yourId;\n -> return Name1;\n -> end //\nQuery OK, 0 rows affected (0.21 sec)\nQuery OK, 0 rows affected (0.33 sec)\nmysql> delimiter ;"
},
{
"code": null,
"e": 3009,
"s": 2957,
"text": "Now to check the function is working with given id."
},
{
"code": null,
"e": 3048,
"s": 3009,
"text": "Case 1 − When the given id is present."
},
{
"code": null,
"e": 3074,
"s": 3048,
"text": "The query is as follows −"
},
{
"code": null,
"e": 3114,
"s": 3074,
"text": "mysql> select searchRecord(2) as Found;"
},
{
"code": null,
"e": 3144,
"s": 3114,
"text": "The following is the output −"
},
{
"code": null,
"e": 3218,
"s": 3144,
"text": "+-------+\n| Found |\n+-------+\n| Sam |\n+-------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 3262,
"s": 3218,
"text": "Case 2 − When the given id is not present. "
},
{
"code": null,
"e": 3288,
"s": 3262,
"text": "The query is as follows −"
},
{
"code": null,
"e": 3330,
"s": 3288,
"text": "mysql> select searchRecord(100) as Found;"
},
{
"code": null,
"e": 3393,
"s": 3330,
"text": "The following is the output displaing the record isn’t there −"
},
{
"code": null,
"e": 3567,
"s": 3393,
"text": "+---------------------------+\n| Found |\n+---------------------------+\n| No Name Found For This Id |\n+---------------------------+\n1 row in set (0.00 sec)"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.