title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Get the count of elements in HashMap in Java | Use the size() method to get the count of elements.
Let us first create a HashMap and add elements −
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));
Now, get the size −
hm.size()
The following is an example to get the count of HashMap elements −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));
hm.put("Physics", new Integer(91));
hm.put("Chemistry", new Integer(93));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
System.out.println("Count of elements = "+hm.size());
}
}
Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91
Size: 5 | [
{
"code": null,
"e": 1114,
"s": 1062,
"text": "Use the size() method to get the count of elements."
},
{
"code": null,
"e": 1163,
"s": 1114,
"text": "Let us first create a HashMap and add elements −"
},
{
"code": null,
"e": 1324,
"s": 1163,
"text": "HashMap hm = new HashMap();\n// Put elements to the map\nhm.put(\"Maths\", new Integer(98));\nhm.put(\"Science\", new Integer(90));\nhm.put(\"English\", new Integer(97));"
},
{
"code": null,
"e": 1344,
"s": 1324,
"text": "Now, get the size −"
},
{
"code": null,
"e": 1354,
"s": 1344,
"text": "hm.size()"
},
{
"code": null,
"e": 1421,
"s": 1354,
"text": "The following is an example to get the count of HashMap elements −"
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": " Live Demo"
},
{
"code": null,
"e": 2237,
"s": 1432,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create a hash map\n HashMap hm = new HashMap();\n // Put elements to the map\n hm.put(\"Maths\", new Integer(98));\n hm.put(\"Science\", new Integer(90));\n hm.put(\"English\", new Integer(97));\n hm.put(\"Physics\", new Integer(91));\n hm.put(\"Chemistry\", new Integer(93));\n // Get a set of the entries\n Set set = hm.entrySet();\n // Get an iterator\n Iterator i = set.iterator();\n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n System.out.println(\"Count of elements = \"+hm.size());\n }\n}"
},
{
"code": null,
"e": 2305,
"s": 2237,
"text": "Maths: 98\nEnglish: 97\nChemistry: 93\nScience: 90\nPhysics: 91\nSize: 5"
}
] |
MySQL query to get the next number in sequence for AUTO_INCREMENT field? | Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+
| Id |
+----+
| 1 |
| 2 |
| 3 |
+----+
3 rows in set (0.00 sec)
Following is the query to get the next number in sequence for AUTO_INCREMENT field −
mysql> SELECT auto_increment FROM information_schema.tables WHERE table_name='DemoTable';
This will produce the following output −
+----------------+
| AUTO_INCREMENT |
+----------------+
| 4 |
+----------------+
1 row in set (0.26 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1224,
"s": 1092,
"text": "mysql> create table DemoTable\n-> (\n-> Id int NOT NULL AUTO_INCREMENT,\n-> PRIMARY KEY(Id)\n-> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1280,
"s": 1224,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1507,
"s": 1280,
"text": "mysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1567,
"s": 1507,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1598,
"s": 1567,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1639,
"s": 1598,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1713,
"s": 1639,
"text": "+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n+----+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1798,
"s": 1713,
"text": "Following is the query to get the next number in sequence for AUTO_INCREMENT field −"
},
{
"code": null,
"e": 1888,
"s": 1798,
"text": "mysql> SELECT auto_increment FROM information_schema.tables WHERE table_name='DemoTable';"
},
{
"code": null,
"e": 1929,
"s": 1888,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2048,
"s": 1929,
"text": "+----------------+\n| AUTO_INCREMENT |\n+----------------+\n| 4 |\n+----------------+\n1 row in set (0.26 sec)"
}
] |
How to separate date and time in R ? - GeeksforGeeks | 29 Jun, 2021
In this article, we are going to separate date and time in R Programming Language. Date-time is in the format of date and time (YYYY/MM/DD HH:MM:SS- year/month/day Hours:Minute:Seconds).
Extracting date from timestamp: We are going to extract date by using as.Date() function.
Syntax:
as.Date(data)
where data is the time stamp.
Extracting time from the time stamp: We can do this by using as.POSIXct() function. To get a particular time hour format we can use the format() function
Syntax:
format(as.POSIXct(data), format = “%H:%M”)
Where,
as.POSIXct() is used to extract time from the time stamp
format is used to get the time format. Ex : hours:Minutes and seconds
data is the time stamp
Example 1:
R
# create variable with one time stamp data ="2021/05/25 12:34:25" # extract date from the time stampprint( as.Date(data)) # get time from date using format in # the form of hours and minutes print( format(as.POSIXct(data), format = "%H:%M"))
Output:
Example 2:
R
# create variable with one time stamp data ="2021/05/25 12:34:25" # extract date from the time stampprint( as.Date(data)) # get time from date using format in the # form of hours ,minutes and secondsprint( format(as.POSIXct(data), format = "%H:%M:%S"))
Output:
Example 3:
R
# create data with five time stamps data = c("2021/05/25 12:34:25", "2019/1/14 04:10:30", "2020/7/11 09:05:05", "2018/1/14 04:10:30", "2017/7/11 09:05:05") # extract date from the time stampprint( as.Date(data)) # get time from date using format in the# form of hours ,minutes and secondsprint( format(as.POSIXct(data), format = "%H:%M:%S"))
Output:
Picked
R-DateTime
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
Time Series Analysis in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 26676,
"s": 26487,
"text": "In this article, we are going to separate date and time in R Programming Language. Date-time is in the format of date and time (YYYY/MM/DD HH:MM:SS- year/month/day Hours:Minute:Seconds). "
},
{
"code": null,
"e": 26766,
"s": 26676,
"text": "Extracting date from timestamp: We are going to extract date by using as.Date() function."
},
{
"code": null,
"e": 26774,
"s": 26766,
"text": "Syntax:"
},
{
"code": null,
"e": 26789,
"s": 26774,
"text": " as.Date(data)"
},
{
"code": null,
"e": 26819,
"s": 26789,
"text": "where data is the time stamp."
},
{
"code": null,
"e": 26973,
"s": 26819,
"text": "Extracting time from the time stamp: We can do this by using as.POSIXct() function. To get a particular time hour format we can use the format() function"
},
{
"code": null,
"e": 26981,
"s": 26973,
"text": "Syntax:"
},
{
"code": null,
"e": 27024,
"s": 26981,
"text": "format(as.POSIXct(data), format = “%H:%M”)"
},
{
"code": null,
"e": 27031,
"s": 27024,
"text": "Where,"
},
{
"code": null,
"e": 27088,
"s": 27031,
"text": "as.POSIXct() is used to extract time from the time stamp"
},
{
"code": null,
"e": 27158,
"s": 27088,
"text": "format is used to get the time format. Ex : hours:Minutes and seconds"
},
{
"code": null,
"e": 27181,
"s": 27158,
"text": "data is the time stamp"
},
{
"code": null,
"e": 27192,
"s": 27181,
"text": "Example 1:"
},
{
"code": null,
"e": 27194,
"s": 27192,
"text": "R"
},
{
"code": "# create variable with one time stamp data =\"2021/05/25 12:34:25\" # extract date from the time stampprint( as.Date(data)) # get time from date using format in # the form of hours and minutes print( format(as.POSIXct(data), format = \"%H:%M\"))",
"e": 27466,
"s": 27194,
"text": null
},
{
"code": null,
"e": 27474,
"s": 27466,
"text": "Output:"
},
{
"code": null,
"e": 27486,
"s": 27474,
"text": "Example 2: "
},
{
"code": null,
"e": 27488,
"s": 27486,
"text": "R"
},
{
"code": "# create variable with one time stamp data =\"2021/05/25 12:34:25\" # extract date from the time stampprint( as.Date(data)) # get time from date using format in the # form of hours ,minutes and secondsprint( format(as.POSIXct(data), format = \"%H:%M:%S\"))",
"e": 27773,
"s": 27488,
"text": null
},
{
"code": null,
"e": 27781,
"s": 27773,
"text": "Output:"
},
{
"code": null,
"e": 27792,
"s": 27781,
"text": "Example 3:"
},
{
"code": null,
"e": 27794,
"s": 27792,
"text": "R"
},
{
"code": "# create data with five time stamps data = c(\"2021/05/25 12:34:25\", \"2019/1/14 04:10:30\", \"2020/7/11 09:05:05\", \"2018/1/14 04:10:30\", \"2017/7/11 09:05:05\") # extract date from the time stampprint( as.Date(data)) # get time from date using format in the# form of hours ,minutes and secondsprint( format(as.POSIXct(data), format = \"%H:%M:%S\"))",
"e": 28199,
"s": 27794,
"text": null
},
{
"code": null,
"e": 28207,
"s": 28199,
"text": "Output:"
},
{
"code": null,
"e": 28214,
"s": 28207,
"text": "Picked"
},
{
"code": null,
"e": 28225,
"s": 28214,
"text": "R-DateTime"
},
{
"code": null,
"e": 28236,
"s": 28225,
"text": "R Language"
},
{
"code": null,
"e": 28334,
"s": 28236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28386,
"s": 28334,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28421,
"s": 28386,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28459,
"s": 28421,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28517,
"s": 28459,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28560,
"s": 28517,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28609,
"s": 28560,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28626,
"s": 28609,
"text": "R - if statement"
},
{
"code": null,
"e": 28676,
"s": 28626,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28728,
"s": 28676,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Design data structures for a very large social network like Facebook or Linkedln - GeeksforGeeks | 09 Feb, 2022
How would you design the data structures for a very large social network like Facebook or Linkedln? Describe how you would design an algorithm to show the shortest path between two people (e.g., Me-> Bob-> Susan-> Jason-> You). Asked In : Google Interview
A good way to approach this problem is to remove some of the constraints and solve it for that situation first. Case 1: Simplify the Problem (Not considering millions of people) We can construct a graph by treating each person as a node and letting an edge between two nodes indicate that the two users are friends. If we want to find the path between two people, we start with one person and do a simple breadth-first search. Alternatively, we can do bidirectional breadth first search. This means doing two breadth first searches, one from the source and one from the destination. When the searches collide, we know we’ve found a path. Why not a depth-first search work well? First, the depth-first search would just find a path. It wouldn’t necessarily find the shortest path. Second, even if we just needed any path, it would be very inefficient. Two users might be only one degree of separation apart, but it could search millions of nodes in their”subtrees” before finding this relatively immediate connection. In the implementation, we’ll use two classes to help us. BFSData holds the data needed for a breadth-first search, such as the isVisited hash table and the toVisit queue. PathNode represents the path as we’re searching, storing each Person and the previousNode we visited in this path. Main Logic in Java given below
Java
Linkedlist<Person> findPathBiBFS(HashMap<Integer, Person> people, int source, int destination){ BFSData sourceData = new BFSData(people.get(source)); BFSData destData = new BFSData(people.get(destination)); while (!sourceData.isFinished() && !destData.isFinished()) { /* Search out from source. */ Person collision = searchlevel(people, sourceData, destData); if (collision != null) return mergePaths(sourceData, destData, collision.getID()); /* Search out from destination. */ collision = searchlevel(people, destData, sourceData); if (collision != null) return mergePaths(sourceData, destData, collision.getID()); } return null;} /* Search one level and return collision, if any.*/Person searchLevel(HashMap<Integer, Person> people, BFSData primary, BFSData secondary){ /* We only want to search one level at a time. Count how many nodes are currently in the primary's level and only do that many nodes. We continue to add nodes to the end. */ int count = primary.toVisit.size(); for (int i= 0; i < count; i++) { /* Pull out first node. */ PathNode pathNode = primary.toVisit.poll(); int personid = pathNode.getPerson().getID(); /* Check if it's already been visited. */ if (secondary.visited.containsKey(personid)) return pathNode.getPerson(); /* Add friends to queue. */ Person person = pathNode. getPerson(); Arraylist<Integer> friends = person.getFriends(); for (int friendid : friends) { if (!primary.visited.containsKey(friendid)) { Person friend= people.get(friendld); PathNode next = new PathNode(friend, pathNode); primary.visited.put(friendld, next); primary.toVisit.add(next); } } } return null;} /* Merge paths where searches met at the connection. */Linkedlist<Person> mergePaths(BFSData bfsl, BFSData bfs2, int connection){ // endl -> source, end2 -> dest PathNode endl = bfsl.visited.get(connection); PathNode end2 = bfs2.visited.get(connection); Linkedlist<Person> pathOne = endl.collapse(false); Linkedlist<Person> pathTwo = end2.collapse(true); pathTwo.removeFirst(); // remove connection pathOne.addAll(pathTwo); // add second path return pathOne;} class PathNode{ private Person person = null; private PathNode previousNode = null; public PathNode(Person p, PathNode previous) { person = p; previousNode = previous; } public Person getPerson() { return person; } public Linkedlist<Person> collapse(boolean startsWithRoot) { Linkedlist<Person> path= new Linkedlist<Person>(); PathNode node = this; while (node != null) { if (startsWithRoot) path.addlast(node.person); else path.addFirst(node.person); node = node.previousNode; } return path; }} class BFSData{ public Queue<PathNode> toVisit = new Linkedlist<PathNode>(); public HashMap<Integer, PathNode> visited = new HashMap<Integer, PathNode>(); public BFSData(Person root) { PathNode sourcePath = new PathNode(root, null); toVisit.add(sourcePath); visited.put(root.getID(), sourcePath); } public boolean isFinished() { return toVisit.isEmpty(); }}
How fast is above BFS based solution? Suppose every person has k friends, and Source S and Destination D have a friend C in common.1. Traditional breadth-first search from S to D: We go through roughly k+k*k nodes: each of S’s k friends, and then each of their k friends.2. Bidirectional breadth-first search: We go through 2k nodes: each of S’s k friends and each of D’s k friends. Of course, 2k is much less than k+k*k. 3. Generalizing this to a path of length q, we have this: 3.1 BFS: O(kq) 3.2 Bidirectional BFS: 0( kq/2 + kq/2), which is just 0( kq/2) If we imagine a path like A->B->C->D->E where each person has 100 friends, this is a big difference. BFS will require looking at 100 million (1004) nodes. A bidirectional BFS will require looking at only 20,000 nodes (2 x 1002). Case 2: Handle Millions of Users For these many users, we cannot possibly keep all of our data on one machine. That means that our simple Person data structure from above doesn’t quite work-our friends may not live on the same machine as we do. Instead, we can replace our list of friends with a list of their IDs, and traverse as follows: 1: For each friend ID: int machine index = getMachineIDForUser(person_ID); 2: Go to machine #machine_index 3: On that machine, do: Person friend = getPersonWithID( person_ID);The code below outlines this process. We’ve defined a class Server, which holds a list of all the machines, and a class Machine, which represents a single machine. Both classes have hash tables to efficiently lookup data. Main Logic in Java given below->
Java
// A server that holds list of all machinesclass Server{ HashMap<Integer, Machine> machines = new HashMap<Integer, Machine>(); HashMap<Integer, Integer> personToMachineMap = new HashMap<Integer, Integer>(); public Machine getMachineWithid(int machineID) { return machines.get(machineID); } public int getMachineIDForUser(int personID) { Integer machineID = personToMachineMap.get(personID); return machineID == null ? -1 : machineID; } public Person getPersonWithID(int personID) { Integer machineID = personToMachineMap.get(personID); if (machineID == null) return null; Machine machine = getMachineWithid(machineID); if (machine == null) return null; return machine.getPersonWithID(personID); }} // A person on social network has id, friends and other infoclass Person{ private Arraylist<Integer> friends = new Arraylist<Integer>(); private int personID; private String info; public Person(int id) { this.personID =id; } public String getinfo() { return info; } public void setinfo(String info) { this.info = info; } public Arraylist<Integer> getFriends() { return friends; } public int getID() { return personID; } public void addFriend(int id) { friends.add(id); }}
Following are some optimizations and follow-up questions. Optimization: Reduce machine jumps Jumping from one machine to another is expensive. Instead of randomly jumping from machine to machine with each friend, try to batch this jumps-e.g., if five of my friends live on one machine, I should look them up all at once. Optimization: Smart division of people and machines People are much more likely to be friends with people who live in the same country as they do. Rather than randomly dividing people across machines, try to divide them by country, city, state, and so on. This will reduce the number of jumps. Question: Breadth-first search usually requires “marking” a node as visited. How do you do that in this case? Usually, in BFS, we mark a node as visited by setting a visited flag in its node class. Here, we don’t want to do that. There could be multiple searches going on at the same time, so it’s a bad idea to just edit our data. Instead, we could mimic the marking of nodes with a hash table to look up a node id and determine whether it’s been visited. Other Follow-Up Questions: 1. In the real world, servers fail. How does this affect you? 2. How could you take advantage of caching? 3. Do you search until the end of the graph (infinite)? How do you decide when to give up? 4. In real life, some people have more friends of friends than others and are therefore more likely to make a path between you and someone else. How could you use this data to pick where to start traversing? Reference for this Article Reference for this ArticleThis article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rkbhola5
BFS
GBlog
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
How to Start Learning DSA?
12 pip Commands For Python Developers
Supervised and Unsupervised learning
Differences between Procedural and Object Oriented Programming
Top 10 System Design Interview Questions and Answers | [
{
"code": null,
"e": 25811,
"s": 25783,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 26067,
"s": 25811,
"text": "How would you design the data structures for a very large social network like Facebook or Linkedln? Describe how you would design an algorithm to show the shortest path between two people (e.g., Me-> Bob-> Susan-> Jason-> You). Asked In : Google Interview"
},
{
"code": null,
"e": 27405,
"s": 26069,
"text": "A good way to approach this problem is to remove some of the constraints and solve it for that situation first. Case 1: Simplify the Problem (Not considering millions of people) We can construct a graph by treating each person as a node and letting an edge between two nodes indicate that the two users are friends. If we want to find the path between two people, we start with one person and do a simple breadth-first search. Alternatively, we can do bidirectional breadth first search. This means doing two breadth first searches, one from the source and one from the destination. When the searches collide, we know we’ve found a path. Why not a depth-first search work well? First, the depth-first search would just find a path. It wouldn’t necessarily find the shortest path. Second, even if we just needed any path, it would be very inefficient. Two users might be only one degree of separation apart, but it could search millions of nodes in their”subtrees” before finding this relatively immediate connection. In the implementation, we’ll use two classes to help us. BFSData holds the data needed for a breadth-first search, such as the isVisited hash table and the toVisit queue. PathNode represents the path as we’re searching, storing each Person and the previousNode we visited in this path. Main Logic in Java given below "
},
{
"code": null,
"e": 27410,
"s": 27405,
"text": "Java"
},
{
"code": "Linkedlist<Person> findPathBiBFS(HashMap<Integer, Person> people, int source, int destination){ BFSData sourceData = new BFSData(people.get(source)); BFSData destData = new BFSData(people.get(destination)); while (!sourceData.isFinished() && !destData.isFinished()) { /* Search out from source. */ Person collision = searchlevel(people, sourceData, destData); if (collision != null) return mergePaths(sourceData, destData, collision.getID()); /* Search out from destination. */ collision = searchlevel(people, destData, sourceData); if (collision != null) return mergePaths(sourceData, destData, collision.getID()); } return null;} /* Search one level and return collision, if any.*/Person searchLevel(HashMap<Integer, Person> people, BFSData primary, BFSData secondary){ /* We only want to search one level at a time. Count how many nodes are currently in the primary's level and only do that many nodes. We continue to add nodes to the end. */ int count = primary.toVisit.size(); for (int i= 0; i < count; i++) { /* Pull out first node. */ PathNode pathNode = primary.toVisit.poll(); int personid = pathNode.getPerson().getID(); /* Check if it's already been visited. */ if (secondary.visited.containsKey(personid)) return pathNode.getPerson(); /* Add friends to queue. */ Person person = pathNode. getPerson(); Arraylist<Integer> friends = person.getFriends(); for (int friendid : friends) { if (!primary.visited.containsKey(friendid)) { Person friend= people.get(friendld); PathNode next = new PathNode(friend, pathNode); primary.visited.put(friendld, next); primary.toVisit.add(next); } } } return null;} /* Merge paths where searches met at the connection. */Linkedlist<Person> mergePaths(BFSData bfsl, BFSData bfs2, int connection){ // endl -> source, end2 -> dest PathNode endl = bfsl.visited.get(connection); PathNode end2 = bfs2.visited.get(connection); Linkedlist<Person> pathOne = endl.collapse(false); Linkedlist<Person> pathTwo = end2.collapse(true); pathTwo.removeFirst(); // remove connection pathOne.addAll(pathTwo); // add second path return pathOne;} class PathNode{ private Person person = null; private PathNode previousNode = null; public PathNode(Person p, PathNode previous) { person = p; previousNode = previous; } public Person getPerson() { return person; } public Linkedlist<Person> collapse(boolean startsWithRoot) { Linkedlist<Person> path= new Linkedlist<Person>(); PathNode node = this; while (node != null) { if (startsWithRoot) path.addlast(node.person); else path.addFirst(node.person); node = node.previousNode; } return path; }} class BFSData{ public Queue<PathNode> toVisit = new Linkedlist<PathNode>(); public HashMap<Integer, PathNode> visited = new HashMap<Integer, PathNode>(); public BFSData(Person root) { PathNode sourcePath = new PathNode(root, null); toVisit.add(sourcePath); visited.put(root.getID(), sourcePath); } public boolean isFinished() { return toVisit.isEmpty(); }}",
"e": 31007,
"s": 27410,
"text": null
},
{
"code": null,
"e": 32566,
"s": 31007,
"text": "How fast is above BFS based solution? Suppose every person has k friends, and Source S and Destination D have a friend C in common.1. Traditional breadth-first search from S to D: We go through roughly k+k*k nodes: each of S’s k friends, and then each of their k friends.2. Bidirectional breadth-first search: We go through 2k nodes: each of S’s k friends and each of D’s k friends. Of course, 2k is much less than k+k*k. 3. Generalizing this to a path of length q, we have this: 3.1 BFS: O(kq) 3.2 Bidirectional BFS: 0( kq/2 + kq/2), which is just 0( kq/2) If we imagine a path like A->B->C->D->E where each person has 100 friends, this is a big difference. BFS will require looking at 100 million (1004) nodes. A bidirectional BFS will require looking at only 20,000 nodes (2 x 1002). Case 2: Handle Millions of Users For these many users, we cannot possibly keep all of our data on one machine. That means that our simple Person data structure from above doesn’t quite work-our friends may not live on the same machine as we do. Instead, we can replace our list of friends with a list of their IDs, and traverse as follows: 1: For each friend ID: int machine index = getMachineIDForUser(person_ID); 2: Go to machine #machine_index 3: On that machine, do: Person friend = getPersonWithID( person_ID);The code below outlines this process. We’ve defined a class Server, which holds a list of all the machines, and a class Machine, which represents a single machine. Both classes have hash tables to efficiently lookup data. Main Logic in Java given below-> "
},
{
"code": null,
"e": 32571,
"s": 32566,
"text": "Java"
},
{
"code": "// A server that holds list of all machinesclass Server{ HashMap<Integer, Machine> machines = new HashMap<Integer, Machine>(); HashMap<Integer, Integer> personToMachineMap = new HashMap<Integer, Integer>(); public Machine getMachineWithid(int machineID) { return machines.get(machineID); } public int getMachineIDForUser(int personID) { Integer machineID = personToMachineMap.get(personID); return machineID == null ? -1 : machineID; } public Person getPersonWithID(int personID) { Integer machineID = personToMachineMap.get(personID); if (machineID == null) return null; Machine machine = getMachineWithid(machineID); if (machine == null) return null; return machine.getPersonWithID(personID); }} // A person on social network has id, friends and other infoclass Person{ private Arraylist<Integer> friends = new Arraylist<Integer>(); private int personID; private String info; public Person(int id) { this.personID =id; } public String getinfo() { return info; } public void setinfo(String info) { this.info = info; } public Arraylist<Integer> getFriends() { return friends; } public int getID() { return personID; } public void addFriend(int id) { friends.add(id); }}",
"e": 34016,
"s": 32571,
"text": null
},
{
"code": null,
"e": 36000,
"s": 34016,
"text": "Following are some optimizations and follow-up questions. Optimization: Reduce machine jumps Jumping from one machine to another is expensive. Instead of randomly jumping from machine to machine with each friend, try to batch this jumps-e.g., if five of my friends live on one machine, I should look them up all at once. Optimization: Smart division of people and machines People are much more likely to be friends with people who live in the same country as they do. Rather than randomly dividing people across machines, try to divide them by country, city, state, and so on. This will reduce the number of jumps. Question: Breadth-first search usually requires “marking” a node as visited. How do you do that in this case? Usually, in BFS, we mark a node as visited by setting a visited flag in its node class. Here, we don’t want to do that. There could be multiple searches going on at the same time, so it’s a bad idea to just edit our data. Instead, we could mimic the marking of nodes with a hash table to look up a node id and determine whether it’s been visited. Other Follow-Up Questions: 1. In the real world, servers fail. How does this affect you? 2. How could you take advantage of caching? 3. Do you search until the end of the graph (infinite)? How do you decide when to give up? 4. In real life, some people have more friends of friends than others and are therefore more likely to make a path between you and someone else. How could you use this data to pick where to start traversing? Reference for this Article Reference for this ArticleThis article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36009,
"s": 36000,
"text": "rkbhola5"
},
{
"code": null,
"e": 36013,
"s": 36009,
"text": "BFS"
},
{
"code": null,
"e": 36019,
"s": 36013,
"text": "GBlog"
},
{
"code": null,
"e": 36023,
"s": 36019,
"text": "BFS"
},
{
"code": null,
"e": 36121,
"s": 36023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36146,
"s": 36121,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36181,
"s": 36146,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 36243,
"s": 36181,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36269,
"s": 36243,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 36302,
"s": 36269,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 36329,
"s": 36302,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 36367,
"s": 36329,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 36404,
"s": 36367,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 36467,
"s": 36404,
"text": "Differences between Procedural and Object Oriented Programming"
}
] |
Java Examples - Replace an element in a list | How to replace an element in a list
Following example uses replaceAll() method to replace all the occurance of an element with a different element in a list.
import java.util.*;
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
System.out.println("List :"+list);
Collections.replaceAll(list, "one", "hundread");
System.out.println("replaceAll: " + list);
}
}
The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2104,
"s": 2068,
"text": "How to replace an element in a list"
},
{
"code": null,
"e": 2226,
"s": 2104,
"text": "Following example uses replaceAll() method to replace all the occurance of an element with a different element in a list."
},
{
"code": null,
"e": 2553,
"s": 2226,
"text": "import java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n List list = Arrays.asList(\"one Two three Four five six one three Four\".split(\" \"));\n System.out.println(\"List :\"+list);\n Collections.replaceAll(list, \"one\", \"hundread\");\n System.out.println(\"replaceAll: \" + list);\n }\n}"
},
{
"code": null,
"e": 2610,
"s": 2553,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2745,
"s": 2610,
"text": "List :[one, Two, three, Four, five, six, one, three, Four]\nreplaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]\n"
},
{
"code": null,
"e": 2752,
"s": 2745,
"text": " Print"
},
{
"code": null,
"e": 2763,
"s": 2752,
"text": " Add Notes"
}
] |
Difference between TreeMap, HashMap, and LinkedHashMap in Java | HashMap, TreeMap and LinkedHashMap all implements java.util.Map interface and following are their characteristics.
HashMap has complexity of O(1) for insertion and lookup.
HashMap has complexity of O(1) for insertion and lookup.
HashMap allows one null key and multiple null values.
HashMap allows one null key and multiple null values.
HashMap does not maintain any order.
HashMap does not maintain any order.
TreeMap has complexity of O(logN) for insertion and lookup.
TreeMap has complexity of O(logN) for insertion and lookup.
TreeMap does not allow null key but allow multiple null values.
TreeMap does not allow null key but allow multiple null values.
TreeMap maintains order. It stores keys in sorted and ascending order.
TreeMap maintains order. It stores keys in sorted and ascending order.
LinkedHashMap has complexity of O(1) for insertion and lookup.
LinkedHashMap has complexity of O(1) for insertion and lookup.
LinkedHashMap allows one null key and multiple null values.
LinkedHashMap allows one null key and multiple null values.
LinkedHashMap maintains order in which key-value pairs are inserted.
LinkedHashMap maintains order in which key-value pairs are inserted.
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class Tester {
public static void main(String args[]) {
Map<String, String> map = new HashMap<String, String>();
map.put("One", "1");
map.put("Five", "5");
map.put("Four", "4");
map.put("Two", "2");
map.put("Three", "3");
System.out.println("HashMap: \n" + map);
Map<String, String> map1 = new LinkedHashMap<String, String>();
map1.put("One", "1");
map1.put("Five", "5");
map1.put("Four", "4");
map1.put("Two", "2");
map1.put("Three", "3");
System.out.println("LinkedHashMap: \n" + map1);
Map<String, String> map2 = new TreeMap<String, String>();
map2.put("One", "1");
map2.put("Five", "5");
map2.put("Four", "4");
map2.put("Two", "2");
map2.put("Three", "3");
System.out.println("TreeMap: \n" + map2);
}
}
HashMap:
{Five = 5, One = 1, Four = 4, Two = 2, Three = 3}
LinkedHashMap:
{One = 1, Five = 5, Four = 4, Two = 2, Three = 3}
TreeMap:
{Five = 5, Four = 4, One = 1, Three = 3, Two = 2}
Here you see, HashMap has random order of Keys, LinkedHashMap has preserved the order in which keys are inserted and TreeMap has sorted order of keys. | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "HashMap, TreeMap and LinkedHashMap all implements java.util.Map interface and following are their characteristics."
},
{
"code": null,
"e": 1234,
"s": 1177,
"text": "HashMap has complexity of O(1) for insertion and lookup."
},
{
"code": null,
"e": 1291,
"s": 1234,
"text": "HashMap has complexity of O(1) for insertion and lookup."
},
{
"code": null,
"e": 1345,
"s": 1291,
"text": "HashMap allows one null key and multiple null values."
},
{
"code": null,
"e": 1399,
"s": 1345,
"text": "HashMap allows one null key and multiple null values."
},
{
"code": null,
"e": 1436,
"s": 1399,
"text": "HashMap does not maintain any order."
},
{
"code": null,
"e": 1473,
"s": 1436,
"text": "HashMap does not maintain any order."
},
{
"code": null,
"e": 1533,
"s": 1473,
"text": "TreeMap has complexity of O(logN) for insertion and lookup."
},
{
"code": null,
"e": 1593,
"s": 1533,
"text": "TreeMap has complexity of O(logN) for insertion and lookup."
},
{
"code": null,
"e": 1657,
"s": 1593,
"text": "TreeMap does not allow null key but allow multiple null values."
},
{
"code": null,
"e": 1721,
"s": 1657,
"text": "TreeMap does not allow null key but allow multiple null values."
},
{
"code": null,
"e": 1792,
"s": 1721,
"text": "TreeMap maintains order. It stores keys in sorted and ascending order."
},
{
"code": null,
"e": 1863,
"s": 1792,
"text": "TreeMap maintains order. It stores keys in sorted and ascending order."
},
{
"code": null,
"e": 1926,
"s": 1863,
"text": "LinkedHashMap has complexity of O(1) for insertion and lookup."
},
{
"code": null,
"e": 1989,
"s": 1926,
"text": "LinkedHashMap has complexity of O(1) for insertion and lookup."
},
{
"code": null,
"e": 2049,
"s": 1989,
"text": "LinkedHashMap allows one null key and multiple null values."
},
{
"code": null,
"e": 2109,
"s": 2049,
"text": "LinkedHashMap allows one null key and multiple null values."
},
{
"code": null,
"e": 2178,
"s": 2109,
"text": "LinkedHashMap maintains order in which key-value pairs are inserted."
},
{
"code": null,
"e": 2247,
"s": 2178,
"text": "LinkedHashMap maintains order in which key-value pairs are inserted."
},
{
"code": null,
"e": 3231,
"s": 2247,
"text": "import java.util.HashMap;\nimport java.util.Hashtable;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class Tester {\n public static void main(String args[]) {\n\n Map<String, String> map = new HashMap<String, String>();\n map.put(\"One\", \"1\");\n map.put(\"Five\", \"5\");\n map.put(\"Four\", \"4\");\n map.put(\"Two\", \"2\");\n map.put(\"Three\", \"3\");\n System.out.println(\"HashMap: \\n\" + map);\n\n Map<String, String> map1 = new LinkedHashMap<String, String>();\n map1.put(\"One\", \"1\");\n map1.put(\"Five\", \"5\");\n map1.put(\"Four\", \"4\");\n map1.put(\"Two\", \"2\");\n map1.put(\"Three\", \"3\");\n System.out.println(\"LinkedHashMap: \\n\" + map1);\n\n Map<String, String> map2 = new TreeMap<String, String>();\n map2.put(\"One\", \"1\");\n map2.put(\"Five\", \"5\");\n map2.put(\"Four\", \"4\");\n map2.put(\"Two\", \"2\");\n map2.put(\"Three\", \"3\");\n System.out.println(\"TreeMap: \\n\" + map2);\n }\n}"
},
{
"code": null,
"e": 3414,
"s": 3231,
"text": "HashMap:\n{Five = 5, One = 1, Four = 4, Two = 2, Three = 3}\nLinkedHashMap:\n{One = 1, Five = 5, Four = 4, Two = 2, Three = 3}\nTreeMap:\n{Five = 5, Four = 4, One = 1, Three = 3, Two = 2}"
},
{
"code": null,
"e": 3565,
"s": 3414,
"text": "Here you see, HashMap has random order of Keys, LinkedHashMap has preserved the order in which keys are inserted and TreeMap has sorted order of keys."
}
] |
Program to find length of contiguous strictly increasing sublist in Python | Suppose we have a list of numbers called nums, we have to find the maximum length of a contiguous strictly increasing sublist when we can remove one or zero elements from the list.
So, if the input is like nums = [30, 11, 12, 13, 14, 15, 18, 17, 32], then the output will be 7, as when we remove 18 in the list we can get [11, 12, 13, 14, 15, 17, 32] which is the longest, contiguous, strictly increasing sublist, and its length is 7.
To solve this, we will follow these steps−
n := size of nums
n := size of nums
pre := a list of size n and fill with 1s
pre := a list of size n and fill with 1s
for i in range 1 to n - 1, doif nums[i] > nums[i - 1], thenpre[i] := pre[i - 1] + 1
for i in range 1 to n - 1, do
if nums[i] > nums[i - 1], thenpre[i] := pre[i - 1] + 1
if nums[i] > nums[i - 1], then
pre[i] := pre[i - 1] + 1
pre[i] := pre[i - 1] + 1
suff := a list of size n and fill with 1s
suff := a list of size n and fill with 1s
for i in range n - 2 to -1, decrease by 1, doif nums[i] < nums[i + 1], thensuff[i] := suff[i + 1] + 1
for i in range n - 2 to -1, decrease by 1, do
if nums[i] < nums[i + 1], thensuff[i] := suff[i + 1] + 1
if nums[i] < nums[i + 1], then
suff[i] := suff[i + 1] + 1
suff[i] := suff[i + 1] + 1
ans := maximum value of maximum of pre and maximum of suff
ans := maximum value of maximum of pre and maximum of suff
for i in range 1 to n - 1, doif nums[i - 1] < nums[i + 1], thenans := maximum of ans and (pre[i - 1] + suff[i + 1])
for i in range 1 to n - 1, do
if nums[i - 1] < nums[i + 1], thenans := maximum of ans and (pre[i - 1] + suff[i + 1])
if nums[i - 1] < nums[i + 1], then
ans := maximum of ans and (pre[i - 1] + suff[i + 1])
ans := maximum of ans and (pre[i - 1] + suff[i + 1])
return ans
return ans
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
n = len(nums)
pre = [1] * n
for i in range(1, n - 1):
if nums[i] > nums[i - 1]:
pre[i] = pre[i - 1] + 1
suff = [1] * n
for i in range(n - 2, -1, -1):
if nums[i] < nums[i + 1]:
suff[i] = suff[i + 1] + 1
ans = max(max(pre), max(suff))
for i in range(1, n - 1):
if nums[i - 1] < nums[i + 1]:
ans = max(ans, pre[i - 1] + suff[i + 1])
return ans
ob = Solution()
nums = [30, 11, 12, 13, 14, 15, 18, 17, 32]
print(ob.solve(nums))
[30, 11, 12, 13, 14, 15, 18, 17, 32]
7 | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, we have to find the maximum length of a contiguous strictly increasing sublist when we can remove one or zero elements from the list."
},
{
"code": null,
"e": 1497,
"s": 1243,
"text": "So, if the input is like nums = [30, 11, 12, 13, 14, 15, 18, 17, 32], then the output will be 7, as when we remove 18 in the list we can get [11, 12, 13, 14, 15, 17, 32] which is the longest, contiguous, strictly increasing sublist, and its length is 7."
},
{
"code": null,
"e": 1540,
"s": 1497,
"text": "To solve this, we will follow these steps−"
},
{
"code": null,
"e": 1558,
"s": 1540,
"text": "n := size of nums"
},
{
"code": null,
"e": 1576,
"s": 1558,
"text": "n := size of nums"
},
{
"code": null,
"e": 1617,
"s": 1576,
"text": "pre := a list of size n and fill with 1s"
},
{
"code": null,
"e": 1658,
"s": 1617,
"text": "pre := a list of size n and fill with 1s"
},
{
"code": null,
"e": 1742,
"s": 1658,
"text": "for i in range 1 to n - 1, doif nums[i] > nums[i - 1], thenpre[i] := pre[i - 1] + 1"
},
{
"code": null,
"e": 1772,
"s": 1742,
"text": "for i in range 1 to n - 1, do"
},
{
"code": null,
"e": 1827,
"s": 1772,
"text": "if nums[i] > nums[i - 1], thenpre[i] := pre[i - 1] + 1"
},
{
"code": null,
"e": 1858,
"s": 1827,
"text": "if nums[i] > nums[i - 1], then"
},
{
"code": null,
"e": 1883,
"s": 1858,
"text": "pre[i] := pre[i - 1] + 1"
},
{
"code": null,
"e": 1908,
"s": 1883,
"text": "pre[i] := pre[i - 1] + 1"
},
{
"code": null,
"e": 1950,
"s": 1908,
"text": "suff := a list of size n and fill with 1s"
},
{
"code": null,
"e": 1992,
"s": 1950,
"text": "suff := a list of size n and fill with 1s"
},
{
"code": null,
"e": 2094,
"s": 1992,
"text": "for i in range n - 2 to -1, decrease by 1, doif nums[i] < nums[i + 1], thensuff[i] := suff[i + 1] + 1"
},
{
"code": null,
"e": 2140,
"s": 2094,
"text": "for i in range n - 2 to -1, decrease by 1, do"
},
{
"code": null,
"e": 2197,
"s": 2140,
"text": "if nums[i] < nums[i + 1], thensuff[i] := suff[i + 1] + 1"
},
{
"code": null,
"e": 2228,
"s": 2197,
"text": "if nums[i] < nums[i + 1], then"
},
{
"code": null,
"e": 2255,
"s": 2228,
"text": "suff[i] := suff[i + 1] + 1"
},
{
"code": null,
"e": 2282,
"s": 2255,
"text": "suff[i] := suff[i + 1] + 1"
},
{
"code": null,
"e": 2341,
"s": 2282,
"text": "ans := maximum value of maximum of pre and maximum of suff"
},
{
"code": null,
"e": 2400,
"s": 2341,
"text": "ans := maximum value of maximum of pre and maximum of suff"
},
{
"code": null,
"e": 2516,
"s": 2400,
"text": "for i in range 1 to n - 1, doif nums[i - 1] < nums[i + 1], thenans := maximum of ans and (pre[i - 1] + suff[i + 1])"
},
{
"code": null,
"e": 2546,
"s": 2516,
"text": "for i in range 1 to n - 1, do"
},
{
"code": null,
"e": 2633,
"s": 2546,
"text": "if nums[i - 1] < nums[i + 1], thenans := maximum of ans and (pre[i - 1] + suff[i + 1])"
},
{
"code": null,
"e": 2668,
"s": 2633,
"text": "if nums[i - 1] < nums[i + 1], then"
},
{
"code": null,
"e": 2721,
"s": 2668,
"text": "ans := maximum of ans and (pre[i - 1] + suff[i + 1])"
},
{
"code": null,
"e": 2774,
"s": 2721,
"text": "ans := maximum of ans and (pre[i - 1] + suff[i + 1])"
},
{
"code": null,
"e": 2785,
"s": 2774,
"text": "return ans"
},
{
"code": null,
"e": 2796,
"s": 2785,
"text": "return ans"
},
{
"code": null,
"e": 2866,
"s": 2796,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2877,
"s": 2866,
"text": " Live Demo"
},
{
"code": null,
"e": 3498,
"s": 2877,
"text": "class Solution:\n def solve(self, nums):\n n = len(nums)\n pre = [1] * n\n for i in range(1, n - 1):\n if nums[i] > nums[i - 1]:\n pre[i] = pre[i - 1] + 1\n suff = [1] * n\n for i in range(n - 2, -1, -1):\n if nums[i] < nums[i + 1]:\n suff[i] = suff[i + 1] + 1\n ans = max(max(pre), max(suff))\n for i in range(1, n - 1):\n if nums[i - 1] < nums[i + 1]:\n ans = max(ans, pre[i - 1] + suff[i + 1])\n return ans\nob = Solution()\nnums = [30, 11, 12, 13, 14, 15, 18, 17, 32]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 3535,
"s": 3498,
"text": "[30, 11, 12, 13, 14, 15, 18, 17, 32]"
},
{
"code": null,
"e": 3537,
"s": 3535,
"text": "7"
}
] |
Spring JDBC - SqlQuery Class | The org.springframework.jdbc.object.SqlQuery class provides a reusable operation object representing a SQL query.
Following is the declaration for org.springframework.jdbc.object.SqlQuery class −
public abstract class SqlQuery<T>
extends SqlOperation
Step 1 − Create a JdbcTemplate object using a configured datasource.
Step 1 − Create a JdbcTemplate object using a configured datasource.
Step 2 − Create a StudentMapper object implementing RowMapper interface.
Step 2 − Create a StudentMapper object implementing RowMapper interface.
Step 3 − Use JdbcTemplate object methods to make database operations while using SqlQuery object.
Step 3 − Use JdbcTemplate object methods to make database operations while using SqlQuery object.
Following example will demonstrate how to read a Query using SqlQuery Object. We'll map read records from Student Table to Student object using StudentMapper object.
String sql = "select * from Student";
SqlQuery<Student> sqlQuery = new SqlQuery<Student>() {
@Override
protected RowMapper<Student> newRowMapper(Object[] parameters,
Map<?, ?> context) {
return new StudentMapper();
}
};
sqlQuery.setDataSource(dataSource);
sqlQuery.setSql(sql);
List <Student> students = sqlQuery.execute();
Where,
SQL − Read query to read all student records.
SQL − Read query to read all student records.
jdbcTemplateObject − StudentJDBCTemplate object to read student records from the database.
jdbcTemplateObject − StudentJDBCTemplate object to read student records from the database.
StudentMapper − StudentMapper object to map the student records to student objects.
StudentMapper − StudentMapper object to map the student records to student objects.
SqlQuery − SqlQuery object to query student records and map them to student objects.
SqlQuery − SqlQuery object to query student records and map them to student objects.
To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will read a query and map the result using StudentMapper object. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of the Data Access Object interface file StudentDao.java.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDao {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Following is the content of the StudentMapper.java file.
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO.
package com.tutorialspoint;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.object.SqlQuery;
public class StudentJDBCTemplate implements StudentDao {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public List<Student> listStudents() {
String sql = "select * from Student";
SqlQuery<Student> sqlQuery = new SqlQuery<Student>() {
@Override
protected RowMapper<Student> newRowMapper(Object[] parameters, Map<?, ?> context){
return new StudentMapper();
}
};
sqlQuery.setDataSource(dataSource);
sqlQuery.setSql(sql);
List <Student> students = sqlQuery.execute();
return students;
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id = "studentJDBCTemplate"
class = "com.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message.
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 17
ID : 3, Name : Ayan, Age : 18
ID : 4, Name : Nuha, Age : 12
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2510,
"s": 2396,
"text": "The org.springframework.jdbc.object.SqlQuery class provides a reusable operation object representing a SQL query."
},
{
"code": null,
"e": 2592,
"s": 2510,
"text": "Following is the declaration for org.springframework.jdbc.object.SqlQuery class −"
},
{
"code": null,
"e": 2651,
"s": 2592,
"text": "public abstract class SqlQuery<T>\n extends SqlOperation\n"
},
{
"code": null,
"e": 2720,
"s": 2651,
"text": "Step 1 − Create a JdbcTemplate object using a configured datasource."
},
{
"code": null,
"e": 2789,
"s": 2720,
"text": "Step 1 − Create a JdbcTemplate object using a configured datasource."
},
{
"code": null,
"e": 2862,
"s": 2789,
"text": "Step 2 − Create a StudentMapper object implementing RowMapper interface."
},
{
"code": null,
"e": 2935,
"s": 2862,
"text": "Step 2 − Create a StudentMapper object implementing RowMapper interface."
},
{
"code": null,
"e": 3033,
"s": 2935,
"text": "Step 3 − Use JdbcTemplate object methods to make database operations while using SqlQuery object."
},
{
"code": null,
"e": 3131,
"s": 3033,
"text": "Step 3 − Use JdbcTemplate object methods to make database operations while using SqlQuery object."
},
{
"code": null,
"e": 3297,
"s": 3131,
"text": "Following example will demonstrate how to read a Query using SqlQuery Object. We'll map read records from Student Table to Student object using StudentMapper object."
},
{
"code": null,
"e": 3642,
"s": 3297,
"text": "String sql = \"select * from Student\";\nSqlQuery<Student> sqlQuery = new SqlQuery<Student>() {\n @Override\n protected RowMapper<Student> newRowMapper(Object[] parameters,\n Map<?, ?> context) {\n return new StudentMapper();\n }\n};\nsqlQuery.setDataSource(dataSource);\nsqlQuery.setSql(sql);\nList <Student> students = sqlQuery.execute();"
},
{
"code": null,
"e": 3649,
"s": 3642,
"text": "Where,"
},
{
"code": null,
"e": 3695,
"s": 3649,
"text": "SQL − Read query to read all student records."
},
{
"code": null,
"e": 3741,
"s": 3695,
"text": "SQL − Read query to read all student records."
},
{
"code": null,
"e": 3832,
"s": 3741,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to read student records from the database."
},
{
"code": null,
"e": 3923,
"s": 3832,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to read student records from the database."
},
{
"code": null,
"e": 4007,
"s": 3923,
"text": "StudentMapper − StudentMapper object to map the student records to student objects."
},
{
"code": null,
"e": 4091,
"s": 4007,
"text": "StudentMapper − StudentMapper object to map the student records to student objects."
},
{
"code": null,
"e": 4176,
"s": 4091,
"text": "SqlQuery − SqlQuery object to query student records and map them to student objects."
},
{
"code": null,
"e": 4261,
"s": 4176,
"text": "SqlQuery − SqlQuery object to query student records and map them to student objects."
},
{
"code": null,
"e": 4548,
"s": 4261,
"text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will read a query and map the result using StudentMapper object. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 4631,
"s": 4548,
"text": "Following is the content of the Data Access Object interface file StudentDao.java."
},
{
"code": null,
"e": 5059,
"s": 4631,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDao {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to list down\n * all the records from the Student table.\n */\n public List<Student> listStudents(); \n}"
},
{
"code": null,
"e": 5110,
"s": 5059,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 5582,
"s": 5110,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 5639,
"s": 5582,
"text": "Following is the content of the StudentMapper.java file."
},
{
"code": null,
"e": 6097,
"s": 5639,
"text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}"
},
{
"code": null,
"e": 6207,
"s": 6097,
"text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO."
},
{
"code": null,
"e": 7229,
"s": 6207,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport java.util.Map;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.RowMapper;\nimport org.springframework.jdbc.object.SqlQuery;\n\npublic class StudentJDBCTemplate implements StudentDao {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource); \n }\n public List<Student> listStudents() {\n String sql = \"select * from Student\";\n SqlQuery<Student> sqlQuery = new SqlQuery<Student>() {\n @Override\n protected RowMapper<Student> newRowMapper(Object[] parameters, Map<?, ?> context){\n return new StudentMapper();\n }\n };\n sqlQuery.setDataSource(dataSource);\n sqlQuery.setSql(sql);\n List <Student> students = sqlQuery.execute();\n return students;\n }\n}"
},
{
"code": null,
"e": 7280,
"s": 7229,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 8150,
"s": 7280,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n \n System.out.println(\"------Listing Multiple Records--------\" );\n List<Student> students = studentJDBCTemplate.listStudents();\n \n for (Student record : students) {\n System.out.print(\"ID : \" + record.getId() );\n System.out.print(\", Name : \" + record.getName() );\n System.out.println(\", Age : \" + record.getAge());\n } \n }\n}"
},
{
"code": null,
"e": 8197,
"s": 8150,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 9147,
"s": 8197,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean> \n</beans>"
},
{
"code": null,
"e": 9325,
"s": 9147,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 9455,
"s": 9325,
"text": "------Listing Multiple Records--------\nID : 1, Name : Zara, Age : 17\nID : 3, Name : Ayan, Age : 18\nID : 4, Name : Nuha, Age : 12\n"
},
{
"code": null,
"e": 9462,
"s": 9455,
"text": " Print"
},
{
"code": null,
"e": 9473,
"s": 9462,
"text": " Add Notes"
}
] |
How does sparse convolution work? | by Zhiliang Zhou | Towards Data Science | Sparse Convolution plays an essential role in LiDAR signal processing. This article describes how the sparse convolution works, which used a quite different concept and GPU calculation schema compared with traditional convolution.
In this article, the theory part is based on the paper “3D Semantic Segmentation with Submanifold Sparse Convolutional Networks” [1]. The implementation part, i.e. SpConv() is based on the paper “SECOND: Sparsely Embedded Convolutional Detection” [2]. In [3], the author made a more general discussion about sparse convolution.
Convolutional Neural Network(CNN) has been proved very effective for 2D image signal processing. However, for 3D point cloud signals, the extra dimension Z increases the calculation significantly. On the other hand, unlike regular images, most of the voxels of the 3D point cloud are empty, which makes point cloud data in the 3D voxels often sparse signals.
The question is whether we can only calculate the convolution with the sparse data efficiently instead of scanning all the image pixels or spatial voxels.
One intuitive thinking is, regular image signals are stored as matrix or tensor. And the corresponding convolution was calculated as dense matrix multiplication. The sparse signals are normally represented as data lists and index lists. We could develop a special convolution schema that uses the advantage of sparse signal representation.
In a short, the traditional convolution uses FFT or im2col [5] to build the computational pipeline. Sparse Convolution collects all atomic operations w.r.t convolution kernel elements and saves them in a Rulebook as instructions of computation.
Below is an example, which explains how sparse convolution works.
In order to explain the concept of sparse convolution step by step and let it easier to read, I use 2D sparse image processing as an example. Since the sparse signals are represented with data list and index list, 2D and 3D sparse signals have no essential difference.
As Fig.2 illustrated, we have a 5x5 image with 3 channels. All the pixels are (0, 0, 0) except two points P1 and P2. P1 and P2, such nonzero elements are also called active input sites, according to [1]. In dense form, the input tensor has a shape [1x3x5x5] with NCHW order. In sparse form, the data list is [[0.1, 0.1, 0.1], [0.2, 0.2, 0.2]] , and the index list is [[1,2], [2, 3]] with YX order.
The convolution kernel of sparse convolution is the same as traditional convolution. Fig.3 is an example, which has kernel size 3x3. The dark and light colors stand for 2 filters. In this example, we use the following convolution parameters.
conv2D(kernel_size=3, out_channels=2, stride=1, padding=0)
The output of the sparse convolution is quite different from traditional convolution. The sparse convolution has 2 kinds of output definitions [1]. One is regular output definition, just like ordinary convolution, calculate the output sites as long as kernel covers an input site. The other one is called the submanifold output definition. the convolution output will be counted only when the kernel center covers an input site.
Fig.4 illustrates the difference between these two kinds of outputs. A1 stands for the active output sites, i.e. the convolution result from P1. Similarly, A2 stands for the active output sites which are calculated from P2. A1A2 stands for the active output sites which are the sum of outputs from P1 and P2. Dark and light colors stand for different output channels.
So in dense form, the output tensor has a shape [1x2x3x3] with NCHW order. In sparse form, the output has two lists, a data list, and an index list, which are similar to the input representation.
Traditional convolution normally uses im2col [5] to rewrite convolution as a dense matrix multiplication problem. However, sparse convolution [1] uses a Rulebook to schedule all atomic operations instead of im2col.
The first step is to build hash tables.
In fig.5, the input hash table stores all active input sites. Then we estimated all possible active output sites, considering either regular output definition or submanifold output definition. At last, using the output hash table to record all involved active output sites.
Note, in fig.5 my convention is not very clear, the v is more like a hash key, and the key is more like a hash value. However, neither of them has duplicate elements. Thus which one should be the key depends on the program.
The second step is to build the Rulebook. This is the key part of sparse convolution. The purpose of Rulebook is similar to im2col [5], which converts convolution from mathematic form to an efficient programmable form. But unlike im2col, Rulebook collects all involved atomic operation in convolution, then associate them to corresponding kernel elements.
Fig.6 is an example of how to build Rulebook. Pin has the input sites index. In this example, we have two nonzero data at position (2, 1) and (3, 2). Pout has the corresponding output sites index. Then we collect the atomic operations from the convolution calculation process, i.e. consider the convolution process as many atomic operations w.r.t kernel elements. At last, we record all atomic operations into Rulebook. In Fig.6 the right table is an example of the Rulebook. The first column is the kernel element index. The second column is a counter and index about how many atomic operations this kernel element involves. The third and fourth column is about the source and result of this atomic operation.
The last step is the overview of the programming calculation pipeline.
As Fig.7 illustrates, we calculate the convolution, not like the sliding window approach but calculate all the atomic operations according to Rulebook. In Fig.7 red and blue arrows indicate two examples.
In Fig.7 red and blue arrows indicate two calculation instances. The red arrow processes the first atomic operation for kernel element (-1, -1). From Rulebook, we know this atomic operation has input from P1 with position (2, 1) and has output with position (2, 1). This entire atomic operation can be constructed as Fig. 8.
Similarly, the blue arrow indicates another atomic operation, which shares the same output site. The result from the red arrow instance and the blue arrow instance can be added together.
However, in practice, the neural network calculates the sum of the linear transformation with activation function like f(∑ wi xi +b). So we don’t really need the hash table for active output sites, just sum all of the atomic operation results together.
The computation w.r.t the Rulebook can be parallel launched in GPU.
So the sparse convolution is quite efficient because we do not need to scan all the pixels or spatial voxels. We only calculate convolution for the nonzero elements. We use Rulebook instead of im2col to rewrite the sparse convolution into a compact linear transformation problem, or we say a compact matrix multiplication problem. One additional computation cost is building the Rulebook. Fortunately, this building work can be also parallel processed with GPU.
At last, I wrote a SpConv Lite library [4], which was derived from [2]. It was implemented by CUDA and packaged into a python library. I also made a real-time LiDAR object detector [6] based on SpConv Lite.
I wrote this article when my living city Dresden is under lockdown. Merry Christmas 2020 and Happy new year 2021. Hope everyone keeps healthy. Hope 2021 will be a better year.
[1] Graham, Benjamin, Martin Engelcke, and Laurens Van Der Maaten. “3d semantic segmentation with submanifold sparse convolutional networks.” Proceedings of the IEEE conference on computer vision and pattern recognition. 2018.[2] Yan, Yan, Yuxing Mao, and Bo Li. “Second: Sparsely embedded convolutional detection.” Sensors 18.10 (2018): 3337.[3] Li, Xuesong, et al. “Three-dimensional Backbone Network for 3D Object Detection in Traffic Scenes.” arXiv preprint arXiv:1901.08373 (2019).[4] SpConv Lite by the author. https://github.com/masszhou/spconv_lite[5] im2col, Convolution implementation as Matrix Multiplication https://cs231n.github.io/convolutional-networks/[6] Real-time 3D voxel-based LiDAR object detector by the author. https://github.com/masszhou/second_lite[7] Geiger, Andreas, Philip Lenz, and Raquel Urtasun. “Are we ready for autonomous driving? the kitti vision benchmark suite.” 2012 IEEE Conference on Computer Vision and Pattern Recognition. IEEE, 2012. | [
{
"code": null,
"e": 278,
"s": 47,
"text": "Sparse Convolution plays an essential role in LiDAR signal processing. This article describes how the sparse convolution works, which used a quite different concept and GPU calculation schema compared with traditional convolution."
},
{
"code": null,
"e": 606,
"s": 278,
"text": "In this article, the theory part is based on the paper “3D Semantic Segmentation with Submanifold Sparse Convolutional Networks” [1]. The implementation part, i.e. SpConv() is based on the paper “SECOND: Sparsely Embedded Convolutional Detection” [2]. In [3], the author made a more general discussion about sparse convolution."
},
{
"code": null,
"e": 965,
"s": 606,
"text": "Convolutional Neural Network(CNN) has been proved very effective for 2D image signal processing. However, for 3D point cloud signals, the extra dimension Z increases the calculation significantly. On the other hand, unlike regular images, most of the voxels of the 3D point cloud are empty, which makes point cloud data in the 3D voxels often sparse signals."
},
{
"code": null,
"e": 1120,
"s": 965,
"text": "The question is whether we can only calculate the convolution with the sparse data efficiently instead of scanning all the image pixels or spatial voxels."
},
{
"code": null,
"e": 1460,
"s": 1120,
"text": "One intuitive thinking is, regular image signals are stored as matrix or tensor. And the corresponding convolution was calculated as dense matrix multiplication. The sparse signals are normally represented as data lists and index lists. We could develop a special convolution schema that uses the advantage of sparse signal representation."
},
{
"code": null,
"e": 1705,
"s": 1460,
"text": "In a short, the traditional convolution uses FFT or im2col [5] to build the computational pipeline. Sparse Convolution collects all atomic operations w.r.t convolution kernel elements and saves them in a Rulebook as instructions of computation."
},
{
"code": null,
"e": 1771,
"s": 1705,
"text": "Below is an example, which explains how sparse convolution works."
},
{
"code": null,
"e": 2040,
"s": 1771,
"text": "In order to explain the concept of sparse convolution step by step and let it easier to read, I use 2D sparse image processing as an example. Since the sparse signals are represented with data list and index list, 2D and 3D sparse signals have no essential difference."
},
{
"code": null,
"e": 2438,
"s": 2040,
"text": "As Fig.2 illustrated, we have a 5x5 image with 3 channels. All the pixels are (0, 0, 0) except two points P1 and P2. P1 and P2, such nonzero elements are also called active input sites, according to [1]. In dense form, the input tensor has a shape [1x3x5x5] with NCHW order. In sparse form, the data list is [[0.1, 0.1, 0.1], [0.2, 0.2, 0.2]] , and the index list is [[1,2], [2, 3]] with YX order."
},
{
"code": null,
"e": 2680,
"s": 2438,
"text": "The convolution kernel of sparse convolution is the same as traditional convolution. Fig.3 is an example, which has kernel size 3x3. The dark and light colors stand for 2 filters. In this example, we use the following convolution parameters."
},
{
"code": null,
"e": 2739,
"s": 2680,
"text": "conv2D(kernel_size=3, out_channels=2, stride=1, padding=0)"
},
{
"code": null,
"e": 3168,
"s": 2739,
"text": "The output of the sparse convolution is quite different from traditional convolution. The sparse convolution has 2 kinds of output definitions [1]. One is regular output definition, just like ordinary convolution, calculate the output sites as long as kernel covers an input site. The other one is called the submanifold output definition. the convolution output will be counted only when the kernel center covers an input site."
},
{
"code": null,
"e": 3536,
"s": 3168,
"text": "Fig.4 illustrates the difference between these two kinds of outputs. A1 stands for the active output sites, i.e. the convolution result from P1. Similarly, A2 stands for the active output sites which are calculated from P2. A1A2 stands for the active output sites which are the sum of outputs from P1 and P2. Dark and light colors stand for different output channels."
},
{
"code": null,
"e": 3732,
"s": 3536,
"text": "So in dense form, the output tensor has a shape [1x2x3x3] with NCHW order. In sparse form, the output has two lists, a data list, and an index list, which are similar to the input representation."
},
{
"code": null,
"e": 3947,
"s": 3732,
"text": "Traditional convolution normally uses im2col [5] to rewrite convolution as a dense matrix multiplication problem. However, sparse convolution [1] uses a Rulebook to schedule all atomic operations instead of im2col."
},
{
"code": null,
"e": 3987,
"s": 3947,
"text": "The first step is to build hash tables."
},
{
"code": null,
"e": 4261,
"s": 3987,
"text": "In fig.5, the input hash table stores all active input sites. Then we estimated all possible active output sites, considering either regular output definition or submanifold output definition. At last, using the output hash table to record all involved active output sites."
},
{
"code": null,
"e": 4485,
"s": 4261,
"text": "Note, in fig.5 my convention is not very clear, the v is more like a hash key, and the key is more like a hash value. However, neither of them has duplicate elements. Thus which one should be the key depends on the program."
},
{
"code": null,
"e": 4841,
"s": 4485,
"text": "The second step is to build the Rulebook. This is the key part of sparse convolution. The purpose of Rulebook is similar to im2col [5], which converts convolution from mathematic form to an efficient programmable form. But unlike im2col, Rulebook collects all involved atomic operation in convolution, then associate them to corresponding kernel elements."
},
{
"code": null,
"e": 5552,
"s": 4841,
"text": "Fig.6 is an example of how to build Rulebook. Pin has the input sites index. In this example, we have two nonzero data at position (2, 1) and (3, 2). Pout has the corresponding output sites index. Then we collect the atomic operations from the convolution calculation process, i.e. consider the convolution process as many atomic operations w.r.t kernel elements. At last, we record all atomic operations into Rulebook. In Fig.6 the right table is an example of the Rulebook. The first column is the kernel element index. The second column is a counter and index about how many atomic operations this kernel element involves. The third and fourth column is about the source and result of this atomic operation."
},
{
"code": null,
"e": 5623,
"s": 5552,
"text": "The last step is the overview of the programming calculation pipeline."
},
{
"code": null,
"e": 5827,
"s": 5623,
"text": "As Fig.7 illustrates, we calculate the convolution, not like the sliding window approach but calculate all the atomic operations according to Rulebook. In Fig.7 red and blue arrows indicate two examples."
},
{
"code": null,
"e": 6152,
"s": 5827,
"text": "In Fig.7 red and blue arrows indicate two calculation instances. The red arrow processes the first atomic operation for kernel element (-1, -1). From Rulebook, we know this atomic operation has input from P1 with position (2, 1) and has output with position (2, 1). This entire atomic operation can be constructed as Fig. 8."
},
{
"code": null,
"e": 6339,
"s": 6152,
"text": "Similarly, the blue arrow indicates another atomic operation, which shares the same output site. The result from the red arrow instance and the blue arrow instance can be added together."
},
{
"code": null,
"e": 6592,
"s": 6339,
"text": "However, in practice, the neural network calculates the sum of the linear transformation with activation function like f(∑ wi xi +b). So we don’t really need the hash table for active output sites, just sum all of the atomic operation results together."
},
{
"code": null,
"e": 6660,
"s": 6592,
"text": "The computation w.r.t the Rulebook can be parallel launched in GPU."
},
{
"code": null,
"e": 7122,
"s": 6660,
"text": "So the sparse convolution is quite efficient because we do not need to scan all the pixels or spatial voxels. We only calculate convolution for the nonzero elements. We use Rulebook instead of im2col to rewrite the sparse convolution into a compact linear transformation problem, or we say a compact matrix multiplication problem. One additional computation cost is building the Rulebook. Fortunately, this building work can be also parallel processed with GPU."
},
{
"code": null,
"e": 7329,
"s": 7122,
"text": "At last, I wrote a SpConv Lite library [4], which was derived from [2]. It was implemented by CUDA and packaged into a python library. I also made a real-time LiDAR object detector [6] based on SpConv Lite."
},
{
"code": null,
"e": 7505,
"s": 7329,
"text": "I wrote this article when my living city Dresden is under lockdown. Merry Christmas 2020 and Happy new year 2021. Hope everyone keeps healthy. Hope 2021 will be a better year."
}
] |
Python Pandas - Environment Setup | Standard Python distribution doesn't come bundled with Pandas module. A lightweight alternative is to install NumPy using popular Python package installer, pip.
pip install pandas
If you install Anaconda Python package, Pandas will be installed by default with the following −
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac.
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac.
Python (x,y) is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from http://python-xy.github.io/)
Python (x,y) is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from http://python-xy.github.io/)
Package managers of respective Linux distributions are used to install one or more packages in SciPy stack.
For Ubuntu Users
sudo apt-get install python-numpy python-scipy python-matplotlibipythonipythonnotebook
python-pandas python-sympy python-nose
For Fedora Users
sudo yum install numpyscipy python-matplotlibipython python-pandas sympy
python-nose atlas-devel
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2604,
"s": 2443,
"text": "Standard Python distribution doesn't come bundled with Pandas module. A lightweight alternative is to install NumPy using popular Python package installer, pip."
},
{
"code": null,
"e": 2624,
"s": 2604,
"text": "pip install pandas\n"
},
{
"code": null,
"e": 2721,
"s": 2624,
"text": "If you install Anaconda Python package, Pandas will be installed by default with the following −"
},
{
"code": null,
"e": 2849,
"s": 2721,
"text": "Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac."
},
{
"code": null,
"e": 2977,
"s": 2849,
"text": "Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac."
},
{
"code": null,
"e": 3135,
"s": 2977,
"text": "Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac."
},
{
"code": null,
"e": 3293,
"s": 3135,
"text": "Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac."
},
{
"code": null,
"e": 3432,
"s": 3293,
"text": "Python (x,y) is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from http://python-xy.github.io/)"
},
{
"code": null,
"e": 3571,
"s": 3432,
"text": "Python (x,y) is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from http://python-xy.github.io/)"
},
{
"code": null,
"e": 3679,
"s": 3571,
"text": "Package managers of respective Linux distributions are used to install one or more packages in SciPy stack."
},
{
"code": null,
"e": 3696,
"s": 3679,
"text": "For Ubuntu Users"
},
{
"code": null,
"e": 3823,
"s": 3696,
"text": "sudo apt-get install python-numpy python-scipy python-matplotlibipythonipythonnotebook\npython-pandas python-sympy python-nose\n"
},
{
"code": null,
"e": 3840,
"s": 3823,
"text": "For Fedora Users"
},
{
"code": null,
"e": 3938,
"s": 3840,
"text": "sudo yum install numpyscipy python-matplotlibipython python-pandas sympy\npython-nose atlas-devel\n"
},
{
"code": null,
"e": 3975,
"s": 3938,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3991,
"s": 3975,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4024,
"s": 3991,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4043,
"s": 4024,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4078,
"s": 4043,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4100,
"s": 4078,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4134,
"s": 4100,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4162,
"s": 4134,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4197,
"s": 4162,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4211,
"s": 4197,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4244,
"s": 4211,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4261,
"s": 4244,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4268,
"s": 4261,
"text": " Print"
},
{
"code": null,
"e": 4279,
"s": 4268,
"text": " Add Notes"
}
] |
Performing mathematical operations in MySQL IF then ELSE is possible? | For performing mathematical operations and working with conditions, you can consider CASE statement. Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FruitName varchar(100),
FruitPrice int
);
Query OK, 0 rows affected (0.26 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FruitName,FruitPrice) values('Orange',250);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(FruitName,FruitPrice) values('Banana',100);
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(FruitName,FruitPrice) values('Apple',150);
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(FruitName,FruitPrice) values('Pomegranate',200);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------------+------------+
| Id | FruitName | FruitPrice |
+----+-------------+------------+
| 1 | Orange | 250 |
| 2 | Banana | 100 |
| 3 | Apple | 150 |
| 4 | Pomegranate | 200 |
+----+-------------+------------+
4 rows in set (0.19 sec)
Following is the query for CASE statement with mathematical operations −
mysql> select Id,FruitName,FruitPrice,
case
when FruitName='Orange'
then FruitPrice/5
else FruitPrice
end as OriginalPrice
from DemoTable;
This will produce the following output −
+----+-------------+------------+---------------+
| Id | FruitName | FruitPrice | OriginalPrice |
+----+-------------+------------+---------------+
| 1 | Orange | 250 | 50.0000 |
| 2 | Banana | 100 | 100 |
| 3 | Apple | 150 | 150 |
| 4 | Pomegranate | 200 | 200 |
+----+-------------+------------+---------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "For performing mathematical operations and working with conditions, you can consider CASE statement. Let us first create a table −"
},
{
"code": null,
"e": 1363,
"s": 1193,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n FruitName varchar(100),\n FruitPrice int\n );\nQuery OK, 0 rows affected (0.26 sec)"
},
{
"code": null,
"e": 1419,
"s": 1363,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1862,
"s": 1419,
"text": "mysql> insert into DemoTable(FruitName,FruitPrice) values('Orange',250);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable(FruitName,FruitPrice) values('Banana',100);\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> insert into DemoTable(FruitName,FruitPrice) values('Apple',150);\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> insert into DemoTable(FruitName,FruitPrice) values('Pomegranate',200);\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 1922,
"s": 1862,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1953,
"s": 1922,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1994,
"s": 1953,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2291,
"s": 1994,
"text": "+----+-------------+------------+\n| Id | FruitName | FruitPrice |\n+----+-------------+------------+\n| 1 | Orange | 250 |\n| 2 | Banana | 100 |\n| 3 | Apple | 150 |\n| 4 | Pomegranate | 200 |\n+----+-------------+------------+\n4 rows in set (0.19 sec)"
},
{
"code": null,
"e": 2364,
"s": 2291,
"text": "Following is the query for CASE statement with mathematical operations −"
},
{
"code": null,
"e": 2521,
"s": 2364,
"text": "mysql> select Id,FruitName,FruitPrice,\n case\n when FruitName='Orange'\n then FruitPrice/5\n else FruitPrice\n end as OriginalPrice\n from DemoTable;"
},
{
"code": null,
"e": 2562,
"s": 2521,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2987,
"s": 2562,
"text": "+----+-------------+------------+---------------+\n| Id | FruitName | FruitPrice | OriginalPrice |\n+----+-------------+------------+---------------+\n| 1 | Orange | 250 | 50.0000 |\n| 2 | Banana | 100 | 100 |\n| 3 | Apple | 150 | 150 |\n| 4 | Pomegranate | 200 | 200 |\n+----+-------------+------------+---------------+\n4 rows in set (0.00 sec)"
}
] |
Connect nodes at same level - GeeksforGeeks | 07 Feb, 2022
Write a function to connect all the adjacent nodes at the same level in a binary tree. Structure of the given Binary Tree node is like following.
C++
C
Javascript
struct node { int data; struct node* left; struct node* right; struct node* nextRight;}
struct node { int data; struct node* left; struct node* right; struct node* nextRight;}
class node { constructor() { this.data = 0; this.left = null; this.right = null; this.nextRight = null; }} // This code is contributed by importantly.
Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.Example:
Input Tree
A
/ \
B C
/ \ \
D E F
Output Tree
A--->NULL
/ \
B-->C-->NULL
/ \ \
D-->E-->F-->NULL
Method 1 (Extend Level Order Traversal or BFS) Consider the method 2 of Level Order Traversal. The method 2 can easily be extended to connect nodes of same level. We can augment queue entries to contain level of nodes also which is 0 for root, 1 for root’s children and so on. So a queue node will now contain a pointer to a tree node and an integer level. When we enqueue a node, we make sure that correct level value for node is being set in queue. To set nextRight, for every node N, we dequeue the next node from queue, if the level number of next node is same, we set the nextRight of N as address of the dequeued node, otherwise we set nextRight of N as NULL. We initialize a node Prev which points at the previous node. While traversing the nodes in the same level we keep track of the previous node and point the nextRight pointer to the current node in every iteration.
C++
Java
C#
Javascript
/* Iterative program to connect all the adjacent nodes at the same level in a binary tree*/#include <iostream>#include<queue>using namespace std; // A Binary Tree Nodeclass node {public: int data; node* left; node* right; node* nextRight; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; this->nextRight = NULL; }};// setting right pointer to next right node/* 10 ----------> NULL / \ 8 --->2 --------> NULL / 3 ----------------> NULL */void connect(node *root) { //Base condition if(root==NULL) return; // Create an empty queue like level order traversal queue<node*> q; q.push(root); while(!q.empty()){ // size indicates no. of nodes at current level int size=q.size(); // for keeping track of previous node node* prev=NULL; while(size--){ node* temp=q.front(); q.pop(); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); if(prev!=NULL) prev->nextRight=temp; prev=temp; } prev->nextRight=NULL; } } int main() { /* Constructed binary tree is 10 / \ 8 2 / 3 */ // Let us create binary tree shown above node* root = new node(10); root->left = new node(8); root->right = new node(2); root->left->left = new node(3); connect(root); // Let us check the values // of nextRight pointers cout << "Following are populated nextRight pointers in the tree" " (-1 is printed if there is no nextRight)\n"; cout << "nextRight of " << root->data << " is " << (root->nextRight ? root->nextRight->data : -1) << endl; cout << "nextRight of " << root->left->data << " is " << (root->left->nextRight ? root->left->nextRight->data : -1) << endl; cout << "nextRight of " << root->right->data << " is " << (root->right->nextRight ? root->right->nextRight->data : -1) << endl; cout << "nextRight of " << root->left->left->data << " is " << (root->left->left->nextRight ? root->left->left->nextRight->data : -1) << endl; return 0;}// this code is contributed by Kapil Poonia
import java.util.*;import java.io.*;class Node { int data; Node left, right, nextRight; Node(int item) { data = item; left = right = nextRight = null; }} public class BinaryTree { Node root; void connect(Node p) { // initialize queue to hold nodes at same level Queue<Node> q = new LinkedList<>(); q.add(root); // adding nodes to the queue Node temp = null; // initializing prev to null while (!q.isEmpty()) { int n = q.size(); for (int i = 0; i < n; i++) { Node prev = temp; temp = q.poll(); // i > 0 because when i is 0 prev points // the last node of previous level, // so we skip it if (i > 0) prev.nextRight = temp; if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } // pointing last node of the nth level to null temp.nextRight = null; } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 10 / \ 8 2 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.connect(tree.root); // Let us check the values of nextRight pointers System.out.println("Following are populated nextRight pointers in " + "the tree" + "(-1 is printed if there is no nextRight)"); int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; System.out.println("nextRight of " + tree.root.data + " is " + a); int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; System.out.println("nextRight of " + tree.root.left.data + " is " + b); int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; System.out.println("nextRight of " + tree.root.right.data + " is " + c); int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; System.out.println("nextRight of " + tree.root.left.left.data + " is " + d); }}// This code has been contributed by Rahul Shakya
// C# program to connect nodes// at same levelusing System;using System.Collections.Generic; class Node{ public int data; public Node left, right, nextRight; public Node(int item) { data = item; left = right = nextRight = null; }} public class BinaryTree{ Node root; void connect(Node p) { // initialize queue to hold nodes at same level Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // adding nodes to tehe queue Node temp = null; // initializing prev to null while (q.Count > 0) { int n = q.Count; for (int i = 0; i < n; i++) { Node prev = temp; temp = q.Dequeue(); // i > 0 because when i is 0 prev points // the last node of previous level, // so we skip it if (i > 0) prev.nextRight = temp; if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } // pointing last node of the nth level to null temp.nextRight = null; } } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 10 / \ 8 2 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.connect(tree.root); // Let us check the values of nextRight pointers Console.WriteLine("Following are populated nextRight pointers in " + "the tree" + "(-1 is printed if there is no nextRight)"); int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.data + " is " + a); int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.left.data + " is " + b); int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.right.data + " is " + c); int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.left.left.data + " is " + d); Console.ReadKey(); }} // This code has been contributed by techno2mahi
<script> class Node{ constructor(item) { this.data = item; this.left = this.right = this.nextRight = null; }} let root; function connect(p){ // initialize queue to hold nodes at same level let q = []; q.push(root); // adding nodes to the queue let temp = null; // initializing prev to null while (q.length!=0) { let n = q.length; for (let i = 0; i < n; i++) { let prev = temp; temp = q.shift(); // i > 0 because when i is 0 prev points // the last node of previous level, // so we skip it if (i > 0) prev.nextRight = temp; if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } // pointing last node of the nth level to null temp.nextRight = null; }} // Driver program to test above functions /* Constructed binary tree is 10 / \ 8 2 / 3 */root = new Node(10);root.left = new Node(8);root.right = new Node(2);root.left.left = new Node(3); // Populates nextRight pointer in all nodesconnect(root); // Let us check the values of nextRight pointersdocument.write("Following are populated nextRight pointers in " + "the tree" + "(-1 is printed if there is no nextRight)<br>");let a = root.nextRight != null ? root.nextRight.data : -1;document.write("nextRight of " + root.data + " is " + a+"<br>");let b = root.left.nextRight != null ? root.left.nextRight.data : -1;document.write("nextRight of " + root.left.data + " is " + b+"<br>");let c = root.right.nextRight != null ? root.right.nextRight.data : -1;document.write("nextRight of " + root.right.data + " is " + c+"<br>");let d = root.left.left.nextRight != null ? root.left.left.nextRight.data : -1;document.write("nextRight of " + root.left.left.data + " is " + d+"<br>");// This code is contributed by avanitrachhadiya2155</script>
Following are populated nextRight pointers in the tree(-1 is printed if there is no nextRight)
nextRight of 10 is -1
nextRight of 8 is 2
nextRight of 2 is -1
nextRight of 3 is -1
Please refer connect Nodes at same Level (Level Order Traversal) for implementation.Time Complexity: O(n)Method 2 (Extend Pre Order Traversal) This approach works only for Complete Binary Trees. In this method we set nextRight in Pre Order fashion to make sure that the nextRight of parent is set before its children. When we are at node p, we set the nextRight of its left and right children. Since the tree is complete tree, nextRight of p’s left child (p->left->nextRight) will always be p’s right child, and nextRight of p’s right child (p->right->nextRight) will always be left child of p’s nextRight (if p is not the rightmost node at its level). If p is the rightmost node, then nextRight of p’s right child will be NULL.
C++
C
Java
Python3
C#
// CPP program to connect nodes// at same level using extended// pre-order traversal#include <bits/stdc++.h>#include <iostream>using namespace std; class node {public: int data; node* left; node* right; node* nextRight; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; this->nextRight = NULL; }}; void connectRecur(node* p); // Sets the nextRight of// root and calls connectRecur()// for other nodesvoid connect(node* p){ // Set the nextRight for root p->nextRight = NULL; // Set the next right for rest of the nodes // (other than root) connectRecur(p);} /* Set next right of all descendants of p.Assumption: p is a complete binary tree */void connectRecur(node* p){ // Base case if (!p) return; // Set the nextRight pointer for p's left child if (p->left) p->left->nextRight = p->right; // Set the nextRight pointer // for p's right child p->nextRight // will be NULL if p is the right // most child at its level if (p->right) p->right->nextRight = (p->nextRight) ? p->nextRight->left : NULL; // Set nextRight for other // nodes in pre order fashion connectRecur(p->left); connectRecur(p->right);} /* Driver code*/int main(){ /* Constructed binary tree is 10 / \ 8 2 / 3 */ node* root = new node(10); root->left = new node(8); root->right = new node(2); root->left->left = new node(3); // Populates nextRight pointer in all nodes connect(root); // Let us check the values // of nextRight pointers cout << "Following are populated nextRight pointers in the tree" " (-1 is printed if there is no nextRight)\n"; cout << "nextRight of " << root->data << " is " << (root->nextRight ? root->nextRight->data : -1) << endl; cout << "nextRight of " << root->left->data << " is " << (root->left->nextRight ? root->left->nextRight->data : -1) << endl; cout << "nextRight of " << root->right->data << " is " << (root->right->nextRight ? root->right->nextRight->data : -1) << endl; cout << "nextRight of " << root->left->left->data << " is " << (root->left->left->nextRight ? root->left->left->nextRight->data : -1) << endl; return 0;} // This code is contributed by rathbhupendra
// C program to connect nodes at same level using extended// pre-order traversal#include <stdio.h>#include <stdlib.h> struct node { int data; struct node* left; struct node* right; struct node* nextRight;}; void connectRecur(struct node* p); // Sets the nextRight of root and calls connectRecur()// for other nodesvoid connect(struct node* p){ // Set the nextRight for root p->nextRight = NULL; // Set the next right for rest of the nodes // (other than root) connectRecur(p);} /* Set next right of all descendants of p. Assumption: p is a complete binary tree */void connectRecur(struct node* p){ // Base case if (!p) return; // Set the nextRight pointer for p's left child if (p->left) p->left->nextRight = p->right; // Set the nextRight pointer for p's right child // p->nextRight will be NULL if p is the right // most child at its level if (p->right) p->right->nextRight = (p->nextRight) ? p->nextRight->left : NULL; // Set nextRight for other nodes in pre order fashion connectRecur(p->left); connectRecur(p->right);} /* UTILITY FUNCTIONS *//* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newnode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; node->nextRight = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 10 / \ 8 2 / 3 */ struct node* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers printf("Following are populated nextRight pointers in the tree " "(-1 is printed if there is no nextRight) \n"); printf("nextRight of %d is %d \n", root->data, root->nextRight ? root->nextRight->data : -1); printf("nextRight of %d is %d \n", root->left->data, root->left->nextRight ? root->left->nextRight->data : -1); printf("nextRight of %d is %d \n", root->right->data, root->right->nextRight ? root->right->nextRight->data : -1); printf("nextRight of %d is %d \n", root->left->left->data, root->left->left->nextRight ? root->left->left->nextRight->data : -1); return 0;}
// JAVA program to connect nodes// at same level using extended// pre-order traversalimport java.util.*;class GFG { static class node { int data; node left; node right; node nextRight; /* * Constructor that allocates a new node with the given data and null left and * right pointers. */ node(int data) { this.data = data; this.left = null; this.right = null; this.nextRight = null; } }; // Sets the nextRight of // root and calls connectRecur() // for other nodes static void connect(node p) { // Set the nextRight for root p.nextRight = null; // Set the next right for rest of the nodes // (other than root) connectRecur(p); } /* * Set next right of all descendants of p. Assumption: p is a complete binary * tree */ static void connectRecur(node p) { // Base case if (p == null) return; // Set the nextRight pointer for p's left child if (p.left != null) p.left.nextRight = p.right; // Set the nextRight pointer // for p's right child p.nextRight // will be null if p is the right // most child at its level if (p.right != null) p.right.nextRight = (p.nextRight) != null ? p.nextRight.left : null; // Set nextRight for other // nodes in pre order fashion connectRecur(p.left); connectRecur(p.right); } /* Driver code */ public static void main(String[] args) { /* * Constructed binary tree is 10 / \ 8 2 / 3 */ node root = new node(10); root.left = new node(8); root.right = new node(2); root.left.left = new node(3); // Populates nextRight pointer in all nodes connect(root); // Let us check the values // of nextRight pointers System.out.print("Following are populated nextRight pointers in the tree" + " (-1 is printed if there is no nextRight)\n"); System.out.print( "nextRight of " + root.data + " is " + (root.nextRight != null ? root.nextRight.data : -1) + "\n"); System.out.print("nextRight of " + root.left.data + " is " + (root.left.nextRight != null ? root.left.nextRight.data : -1) + "\n"); System.out.print("nextRight of " + root.right.data + " is " + (root.right.nextRight != null ? root.right.nextRight.data : -1) + "\n"); System.out.print("nextRight of " + root.left.left.data + " is " + (root.left.left.nextRight != null ? root.left.left.nextRight.data : -1) + "\n"); }} // This code is contributed by umadevi9616
# Python3 program to connect nodes at same# level using extended pre-order traversal class newnode: def __init__(self, data): self.data = data self.left = self.right = self.nextRight = None # Sets the nextRight of root and calls# connectRecur() for other nodesdef connect (p): # Set the nextRight for root p.nextRight = None # Set the next right for rest of # the nodes (other than root) connectRecur(p) # Set next right of all descendants of p.# Assumption: p is a complete binary treedef connectRecur(p): # Base case if (not p): return # Set the nextRight pointer for p's # left child if (p.left): p.left.nextRight = p.right # Set the nextRight pointer for p's right # child p.nextRight will be None if p is # the right most child at its level if (p.right): if p.nextRight: p.right.nextRight = p.nextRight.left else: p.right.nextRight = None # Set nextRight for other nodes in # pre order fashion connectRecur(p.left) connectRecur(p.right) # Driver Codeif __name__ == '__main__': # Constructed binary tree is # 10 # / \ # 8 2 # / # 3 root = newnode(10) root.left = newnode(8) root.right = newnode(2) root.left.left = newnode(3) # Populates nextRight pointer in all nodes connect(root) # Let us check the values of nextRight pointers print("Following are populated nextRight", "pointers in the tree (-1 is printed", "if there is no nextRight)") print("nextRight of", root.data, "is ", end = "") if root.nextRight: print(root.nextRight.data) else: print(-1) print("nextRight of", root.left.data, "is ", end = "") if root.left.nextRight: print(root.left.nextRight.data) else: print(-1) print("nextRight of", root.right.data, "is ", end = "") if root.right.nextRight: print(root.right.nextRight.data) else: print(-1) print("nextRight of", root.left.left.data, "is ", end = "") if root.left.left.nextRight: print(root.left.left.nextRight.data) else: print(-1) # This code is contributed by PranchalK
using System; // C# program to connect nodes at same level using extended// pre-order traversal // A binary tree nodepublic class Node { public int data; public Node left, right, nextRight; public Node(int item) { data = item; left = right = nextRight = null; }} public class BinaryTree { public Node root; // Sets the nextRight of root and calls connectRecur() // for other nodes public virtual void connect(Node p) { // Set the nextRight for root p.nextRight = null; // Set the next right for rest of the nodes (other // than root) connectRecur(p); } /* Set next right of all descendants of p. Assumption: p is a complete binary tree */ public virtual void connectRecur(Node p) { // Base case if (p == null) { return; } // Set the nextRight pointer for p's left child if (p.left != null) { p.left.nextRight = p.right; } // Set the nextRight pointer for p's right child // p->nextRight will be NULL if p is the right most child // at its level if (p.right != null) { p.right.nextRight = (p.nextRight != null) ? p.nextRight.left : null; } // Set nextRight for other nodes in pre order fashion connectRecur(p.left); connectRecur(p.right); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 10 / \ 8 2 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.connect(tree.root); // Let us check the values of nextRight pointers Console.WriteLine("Following are populated nextRight pointers in " + "the tree" + "(-1 is printed if there is no nextRight)"); int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.data + " is " + a); int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.left.data + " is " + b); int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.right.data + " is " + c); int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; Console.WriteLine("nextRight of " + tree.root.left.left.data + " is " + d); }} // This code is contributed by Shrikant13
Following are populated nextRight pointers in the tree (-1 is printed if there is no nextRight)
nextRight of 10 is -1
nextRight of 8 is 2
nextRight of 2 is -1
nextRight of 3 is -1
Thanks to Dhanya for suggesting this approach.Time Complexity: O(n)Why doesn’t method 2 work for trees which are not Complete Binary Trees? Let us consider following tree as an example. In Method 2, we set the nextRight pointer in pre order fashion. When we are at node 4, we set the nextRight of its children which are 8 and 9 (the nextRight of 4 is already set as node 5). nextRight of 8 will simply be set as 9, but nextRight of 9 will be set as NULL which is incorrect. We can’t set the correct nextRight, because when we set nextRight of 9, we only have nextRight of node 4 and ancestors of node 4, we don’t have nextRight of nodes in right subtree of root.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \
8 9 10 11
See Connect nodes at same level using constant extra space for more solutions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
PranchalKatiyar
rathbhupendra
rahul_shak
techno2mahi
importantly
itsok
123kapilpoonia123
avanitrachhadiya2155
umadevi9616
kalrap615
varshagumber28
Accolite
Adobe
Amazon
Boomerang Commerce
Flipkart
Google
Microsoft
Ola Cabs
Oracle
OYO Rooms
Xome
Tree
Flipkart
Accolite
Amazon
Microsoft
OYO Rooms
Ola Cabs
Oracle
Adobe
Google
Boomerang Commerce
Xome
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree
Insertion in a Binary Tree in level order
AVL Tree | Set 2 (Deletion) | [
{
"code": null,
"e": 24631,
"s": 24603,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 24779,
"s": 24631,
"text": "Write a function to connect all the adjacent nodes at the same level in a binary tree. Structure of the given Binary Tree node is like following. "
},
{
"code": null,
"e": 24783,
"s": 24779,
"text": "C++"
},
{
"code": null,
"e": 24785,
"s": 24783,
"text": "C"
},
{
"code": null,
"e": 24796,
"s": 24785,
"text": "Javascript"
},
{
"code": "struct node { int data; struct node* left; struct node* right; struct node* nextRight;}",
"e": 24896,
"s": 24796,
"text": null
},
{
"code": "struct node { int data; struct node* left; struct node* right; struct node* nextRight;}",
"e": 24996,
"s": 24896,
"text": null
},
{
"code": "class node { constructor() { this.data = 0; this.left = null; this.right = null; this.nextRight = null; }} // This code is contributed by importantly.",
"e": 25182,
"s": 24996,
"text": null
},
{
"code": null,
"e": 25330,
"s": 25182,
"text": "Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.Example: "
},
{
"code": null,
"e": 25487,
"s": 25330,
"text": "Input Tree\n A\n / \\\n B C\n / \\ \\\n D E F\n\n\nOutput Tree\n A--->NULL\n / \\\n B-->C-->NULL\n / \\ \\\n D-->E-->F-->NULL"
},
{
"code": null,
"e": 26369,
"s": 25489,
"text": "Method 1 (Extend Level Order Traversal or BFS) Consider the method 2 of Level Order Traversal. The method 2 can easily be extended to connect nodes of same level. We can augment queue entries to contain level of nodes also which is 0 for root, 1 for root’s children and so on. So a queue node will now contain a pointer to a tree node and an integer level. When we enqueue a node, we make sure that correct level value for node is being set in queue. To set nextRight, for every node N, we dequeue the next node from queue, if the level number of next node is same, we set the nextRight of N as address of the dequeued node, otherwise we set nextRight of N as NULL. We initialize a node Prev which points at the previous node. While traversing the nodes in the same level we keep track of the previous node and point the nextRight pointer to the current node in every iteration. "
},
{
"code": null,
"e": 26373,
"s": 26369,
"text": "C++"
},
{
"code": null,
"e": 26378,
"s": 26373,
"text": "Java"
},
{
"code": null,
"e": 26381,
"s": 26378,
"text": "C#"
},
{
"code": null,
"e": 26392,
"s": 26381,
"text": "Javascript"
},
{
"code": "/* Iterative program to connect all the adjacent nodes at the same level in a binary tree*/#include <iostream>#include<queue>using namespace std; // A Binary Tree Nodeclass node {public: int data; node* left; node* right; node* nextRight; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; this->nextRight = NULL; }};// setting right pointer to next right node/* 10 ----------> NULL / \\ 8 --->2 --------> NULL / 3 ----------------> NULL */void connect(node *root) { //Base condition if(root==NULL) return; // Create an empty queue like level order traversal queue<node*> q; q.push(root); while(!q.empty()){ // size indicates no. of nodes at current level int size=q.size(); // for keeping track of previous node node* prev=NULL; while(size--){ node* temp=q.front(); q.pop(); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); if(prev!=NULL) prev->nextRight=temp; prev=temp; } prev->nextRight=NULL; } } int main() { /* Constructed binary tree is 10 / \\ 8 2 / 3 */ // Let us create binary tree shown above node* root = new node(10); root->left = new node(8); root->right = new node(2); root->left->left = new node(3); connect(root); // Let us check the values // of nextRight pointers cout << \"Following are populated nextRight pointers in the tree\" \" (-1 is printed if there is no nextRight)\\n\"; cout << \"nextRight of \" << root->data << \" is \" << (root->nextRight ? root->nextRight->data : -1) << endl; cout << \"nextRight of \" << root->left->data << \" is \" << (root->left->nextRight ? root->left->nextRight->data : -1) << endl; cout << \"nextRight of \" << root->right->data << \" is \" << (root->right->nextRight ? root->right->nextRight->data : -1) << endl; cout << \"nextRight of \" << root->left->left->data << \" is \" << (root->left->left->nextRight ? root->left->left->nextRight->data : -1) << endl; return 0;}// this code is contributed by Kapil Poonia",
"e": 28941,
"s": 26392,
"text": null
},
{
"code": "import java.util.*;import java.io.*;class Node { int data; Node left, right, nextRight; Node(int item) { data = item; left = right = nextRight = null; }} public class BinaryTree { Node root; void connect(Node p) { // initialize queue to hold nodes at same level Queue<Node> q = new LinkedList<>(); q.add(root); // adding nodes to the queue Node temp = null; // initializing prev to null while (!q.isEmpty()) { int n = q.size(); for (int i = 0; i < n; i++) { Node prev = temp; temp = q.poll(); // i > 0 because when i is 0 prev points // the last node of previous level, // so we skip it if (i > 0) prev.nextRight = temp; if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } // pointing last node of the nth level to null temp.nextRight = null; } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 10 / \\ 8 2 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.connect(tree.root); // Let us check the values of nextRight pointers System.out.println(\"Following are populated nextRight pointers in \" + \"the tree\" + \"(-1 is printed if there is no nextRight)\"); int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; System.out.println(\"nextRight of \" + tree.root.data + \" is \" + a); int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; System.out.println(\"nextRight of \" + tree.root.left.data + \" is \" + b); int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; System.out.println(\"nextRight of \" + tree.root.right.data + \" is \" + c); int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; System.out.println(\"nextRight of \" + tree.root.left.left.data + \" is \" + d); }}// This code has been contributed by Rahul Shakya",
"e": 31595,
"s": 28941,
"text": null
},
{
"code": "// C# program to connect nodes// at same levelusing System;using System.Collections.Generic; class Node{ public int data; public Node left, right, nextRight; public Node(int item) { data = item; left = right = nextRight = null; }} public class BinaryTree{ Node root; void connect(Node p) { // initialize queue to hold nodes at same level Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // adding nodes to tehe queue Node temp = null; // initializing prev to null while (q.Count > 0) { int n = q.Count; for (int i = 0; i < n; i++) { Node prev = temp; temp = q.Dequeue(); // i > 0 because when i is 0 prev points // the last node of previous level, // so we skip it if (i > 0) prev.nextRight = temp; if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } // pointing last node of the nth level to null temp.nextRight = null; } } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 10 / \\ 8 2 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.connect(tree.root); // Let us check the values of nextRight pointers Console.WriteLine(\"Following are populated nextRight pointers in \" + \"the tree\" + \"(-1 is printed if there is no nextRight)\"); int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.data + \" is \" + a); int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.left.data + \" is \" + b); int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.right.data + \" is \" + c); int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.left.left.data + \" is \" + d); Console.ReadKey(); }} // This code has been contributed by techno2mahi",
"e": 34328,
"s": 31595,
"text": null
},
{
"code": "<script> class Node{ constructor(item) { this.data = item; this.left = this.right = this.nextRight = null; }} let root; function connect(p){ // initialize queue to hold nodes at same level let q = []; q.push(root); // adding nodes to the queue let temp = null; // initializing prev to null while (q.length!=0) { let n = q.length; for (let i = 0; i < n; i++) { let prev = temp; temp = q.shift(); // i > 0 because when i is 0 prev points // the last node of previous level, // so we skip it if (i > 0) prev.nextRight = temp; if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } // pointing last node of the nth level to null temp.nextRight = null; }} // Driver program to test above functions /* Constructed binary tree is 10 / \\ 8 2 / 3 */root = new Node(10);root.left = new Node(8);root.right = new Node(2);root.left.left = new Node(3); // Populates nextRight pointer in all nodesconnect(root); // Let us check the values of nextRight pointersdocument.write(\"Following are populated nextRight pointers in \" + \"the tree\" + \"(-1 is printed if there is no nextRight)<br>\");let a = root.nextRight != null ? root.nextRight.data : -1;document.write(\"nextRight of \" + root.data + \" is \" + a+\"<br>\");let b = root.left.nextRight != null ? root.left.nextRight.data : -1;document.write(\"nextRight of \" + root.left.data + \" is \" + b+\"<br>\");let c = root.right.nextRight != null ? root.right.nextRight.data : -1;document.write(\"nextRight of \" + root.right.data + \" is \" + c+\"<br>\");let d = root.left.left.nextRight != null ? root.left.left.nextRight.data : -1;document.write(\"nextRight of \" + root.left.left.data + \" is \" + d+\"<br>\");// This code is contributed by avanitrachhadiya2155</script>",
"e": 36517,
"s": 34328,
"text": null
},
{
"code": null,
"e": 36696,
"s": 36517,
"text": "Following are populated nextRight pointers in the tree(-1 is printed if there is no nextRight)\nnextRight of 10 is -1\nnextRight of 8 is 2\nnextRight of 2 is -1\nnextRight of 3 is -1"
},
{
"code": null,
"e": 37429,
"s": 36698,
"text": "Please refer connect Nodes at same Level (Level Order Traversal) for implementation.Time Complexity: O(n)Method 2 (Extend Pre Order Traversal) This approach works only for Complete Binary Trees. In this method we set nextRight in Pre Order fashion to make sure that the nextRight of parent is set before its children. When we are at node p, we set the nextRight of its left and right children. Since the tree is complete tree, nextRight of p’s left child (p->left->nextRight) will always be p’s right child, and nextRight of p’s right child (p->right->nextRight) will always be left child of p’s nextRight (if p is not the rightmost node at its level). If p is the rightmost node, then nextRight of p’s right child will be NULL. "
},
{
"code": null,
"e": 37433,
"s": 37429,
"text": "C++"
},
{
"code": null,
"e": 37435,
"s": 37433,
"text": "C"
},
{
"code": null,
"e": 37440,
"s": 37435,
"text": "Java"
},
{
"code": null,
"e": 37448,
"s": 37440,
"text": "Python3"
},
{
"code": null,
"e": 37451,
"s": 37448,
"text": "C#"
},
{
"code": "// CPP program to connect nodes// at same level using extended// pre-order traversal#include <bits/stdc++.h>#include <iostream>using namespace std; class node {public: int data; node* left; node* right; node* nextRight; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; this->nextRight = NULL; }}; void connectRecur(node* p); // Sets the nextRight of// root and calls connectRecur()// for other nodesvoid connect(node* p){ // Set the nextRight for root p->nextRight = NULL; // Set the next right for rest of the nodes // (other than root) connectRecur(p);} /* Set next right of all descendants of p.Assumption: p is a complete binary tree */void connectRecur(node* p){ // Base case if (!p) return; // Set the nextRight pointer for p's left child if (p->left) p->left->nextRight = p->right; // Set the nextRight pointer // for p's right child p->nextRight // will be NULL if p is the right // most child at its level if (p->right) p->right->nextRight = (p->nextRight) ? p->nextRight->left : NULL; // Set nextRight for other // nodes in pre order fashion connectRecur(p->left); connectRecur(p->right);} /* Driver code*/int main(){ /* Constructed binary tree is 10 / \\ 8 2 / 3 */ node* root = new node(10); root->left = new node(8); root->right = new node(2); root->left->left = new node(3); // Populates nextRight pointer in all nodes connect(root); // Let us check the values // of nextRight pointers cout << \"Following are populated nextRight pointers in the tree\" \" (-1 is printed if there is no nextRight)\\n\"; cout << \"nextRight of \" << root->data << \" is \" << (root->nextRight ? root->nextRight->data : -1) << endl; cout << \"nextRight of \" << root->left->data << \" is \" << (root->left->nextRight ? root->left->nextRight->data : -1) << endl; cout << \"nextRight of \" << root->right->data << \" is \" << (root->right->nextRight ? root->right->nextRight->data : -1) << endl; cout << \"nextRight of \" << root->left->left->data << \" is \" << (root->left->left->nextRight ? root->left->left->nextRight->data : -1) << endl; return 0;} // This code is contributed by rathbhupendra",
"e": 39925,
"s": 37451,
"text": null
},
{
"code": "// C program to connect nodes at same level using extended// pre-order traversal#include <stdio.h>#include <stdlib.h> struct node { int data; struct node* left; struct node* right; struct node* nextRight;}; void connectRecur(struct node* p); // Sets the nextRight of root and calls connectRecur()// for other nodesvoid connect(struct node* p){ // Set the nextRight for root p->nextRight = NULL; // Set the next right for rest of the nodes // (other than root) connectRecur(p);} /* Set next right of all descendants of p. Assumption: p is a complete binary tree */void connectRecur(struct node* p){ // Base case if (!p) return; // Set the nextRight pointer for p's left child if (p->left) p->left->nextRight = p->right; // Set the nextRight pointer for p's right child // p->nextRight will be NULL if p is the right // most child at its level if (p->right) p->right->nextRight = (p->nextRight) ? p->nextRight->left : NULL; // Set nextRight for other nodes in pre order fashion connectRecur(p->left); connectRecur(p->right);} /* UTILITY FUNCTIONS *//* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newnode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; node->nextRight = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 10 / \\ 8 2 / 3 */ struct node* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers printf(\"Following are populated nextRight pointers in the tree \" \"(-1 is printed if there is no nextRight) \\n\"); printf(\"nextRight of %d is %d \\n\", root->data, root->nextRight ? root->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->left->data, root->left->nextRight ? root->left->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->right->data, root->right->nextRight ? root->right->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->left->left->data, root->left->left->nextRight ? root->left->left->nextRight->data : -1); return 0;}",
"e": 42422,
"s": 39925,
"text": null
},
{
"code": "// JAVA program to connect nodes// at same level using extended// pre-order traversalimport java.util.*;class GFG { static class node { int data; node left; node right; node nextRight; /* * Constructor that allocates a new node with the given data and null left and * right pointers. */ node(int data) { this.data = data; this.left = null; this.right = null; this.nextRight = null; } }; // Sets the nextRight of // root and calls connectRecur() // for other nodes static void connect(node p) { // Set the nextRight for root p.nextRight = null; // Set the next right for rest of the nodes // (other than root) connectRecur(p); } /* * Set next right of all descendants of p. Assumption: p is a complete binary * tree */ static void connectRecur(node p) { // Base case if (p == null) return; // Set the nextRight pointer for p's left child if (p.left != null) p.left.nextRight = p.right; // Set the nextRight pointer // for p's right child p.nextRight // will be null if p is the right // most child at its level if (p.right != null) p.right.nextRight = (p.nextRight) != null ? p.nextRight.left : null; // Set nextRight for other // nodes in pre order fashion connectRecur(p.left); connectRecur(p.right); } /* Driver code */ public static void main(String[] args) { /* * Constructed binary tree is 10 / \\ 8 2 / 3 */ node root = new node(10); root.left = new node(8); root.right = new node(2); root.left.left = new node(3); // Populates nextRight pointer in all nodes connect(root); // Let us check the values // of nextRight pointers System.out.print(\"Following are populated nextRight pointers in the tree\" + \" (-1 is printed if there is no nextRight)\\n\"); System.out.print( \"nextRight of \" + root.data + \" is \" + (root.nextRight != null ? root.nextRight.data : -1) + \"\\n\"); System.out.print(\"nextRight of \" + root.left.data + \" is \" + (root.left.nextRight != null ? root.left.nextRight.data : -1) + \"\\n\"); System.out.print(\"nextRight of \" + root.right.data + \" is \" + (root.right.nextRight != null ? root.right.nextRight.data : -1) + \"\\n\"); System.out.print(\"nextRight of \" + root.left.left.data + \" is \" + (root.left.left.nextRight != null ? root.left.left.nextRight.data : -1) + \"\\n\"); }} // This code is contributed by umadevi9616",
"e": 45184,
"s": 42422,
"text": null
},
{
"code": "# Python3 program to connect nodes at same# level using extended pre-order traversal class newnode: def __init__(self, data): self.data = data self.left = self.right = self.nextRight = None # Sets the nextRight of root and calls# connectRecur() for other nodesdef connect (p): # Set the nextRight for root p.nextRight = None # Set the next right for rest of # the nodes (other than root) connectRecur(p) # Set next right of all descendants of p.# Assumption: p is a complete binary treedef connectRecur(p): # Base case if (not p): return # Set the nextRight pointer for p's # left child if (p.left): p.left.nextRight = p.right # Set the nextRight pointer for p's right # child p.nextRight will be None if p is # the right most child at its level if (p.right): if p.nextRight: p.right.nextRight = p.nextRight.left else: p.right.nextRight = None # Set nextRight for other nodes in # pre order fashion connectRecur(p.left) connectRecur(p.right) # Driver Codeif __name__ == '__main__': # Constructed binary tree is # 10 # / \\ # 8 2 # / # 3 root = newnode(10) root.left = newnode(8) root.right = newnode(2) root.left.left = newnode(3) # Populates nextRight pointer in all nodes connect(root) # Let us check the values of nextRight pointers print(\"Following are populated nextRight\", \"pointers in the tree (-1 is printed\", \"if there is no nextRight)\") print(\"nextRight of\", root.data, \"is \", end = \"\") if root.nextRight: print(root.nextRight.data) else: print(-1) print(\"nextRight of\", root.left.data, \"is \", end = \"\") if root.left.nextRight: print(root.left.nextRight.data) else: print(-1) print(\"nextRight of\", root.right.data, \"is \", end = \"\") if root.right.nextRight: print(root.right.nextRight.data) else: print(-1) print(\"nextRight of\", root.left.left.data, \"is \", end = \"\") if root.left.left.nextRight: print(root.left.left.nextRight.data) else: print(-1) # This code is contributed by PranchalK",
"e": 47409,
"s": 45184,
"text": null
},
{
"code": "using System; // C# program to connect nodes at same level using extended// pre-order traversal // A binary tree nodepublic class Node { public int data; public Node left, right, nextRight; public Node(int item) { data = item; left = right = nextRight = null; }} public class BinaryTree { public Node root; // Sets the nextRight of root and calls connectRecur() // for other nodes public virtual void connect(Node p) { // Set the nextRight for root p.nextRight = null; // Set the next right for rest of the nodes (other // than root) connectRecur(p); } /* Set next right of all descendants of p. Assumption: p is a complete binary tree */ public virtual void connectRecur(Node p) { // Base case if (p == null) { return; } // Set the nextRight pointer for p's left child if (p.left != null) { p.left.nextRight = p.right; } // Set the nextRight pointer for p's right child // p->nextRight will be NULL if p is the right most child // at its level if (p.right != null) { p.right.nextRight = (p.nextRight != null) ? p.nextRight.left : null; } // Set nextRight for other nodes in pre order fashion connectRecur(p.left); connectRecur(p.right); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 10 / \\ 8 2 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.connect(tree.root); // Let us check the values of nextRight pointers Console.WriteLine(\"Following are populated nextRight pointers in \" + \"the tree\" + \"(-1 is printed if there is no nextRight)\"); int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.data + \" is \" + a); int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.left.data + \" is \" + b); int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.right.data + \" is \" + c); int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; Console.WriteLine(\"nextRight of \" + tree.root.left.left.data + \" is \" + d); }} // This code is contributed by Shrikant13",
"e": 50222,
"s": 47409,
"text": null
},
{
"code": null,
"e": 50402,
"s": 50222,
"text": "Following are populated nextRight pointers in the tree (-1 is printed if there is no nextRight)\nnextRight of 10 is -1\nnextRight of 8 is 2\nnextRight of 2 is -1\nnextRight of 3 is -1"
},
{
"code": null,
"e": 51069,
"s": 50404,
"text": "Thanks to Dhanya for suggesting this approach.Time Complexity: O(n)Why doesn’t method 2 work for trees which are not Complete Binary Trees? Let us consider following tree as an example. In Method 2, we set the nextRight pointer in pre order fashion. When we are at node 4, we set the nextRight of its children which are 8 and 9 (the nextRight of 4 is already set as node 5). nextRight of 8 will simply be set as 9, but nextRight of 9 will be set as NULL which is incorrect. We can’t set the correct nextRight, because when we set nextRight of 9, we only have nextRight of node 4 and ancestors of node 4, we don’t have nextRight of nodes in right subtree of root. "
},
{
"code": null,
"e": 51212,
"s": 51069,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ / \\ \n 8 9 10 11"
},
{
"code": null,
"e": 51416,
"s": 51212,
"text": "See Connect nodes at same level using constant extra space for more solutions.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 51428,
"s": 51416,
"text": "shrikanth13"
},
{
"code": null,
"e": 51444,
"s": 51428,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 51458,
"s": 51444,
"text": "rathbhupendra"
},
{
"code": null,
"e": 51469,
"s": 51458,
"text": "rahul_shak"
},
{
"code": null,
"e": 51481,
"s": 51469,
"text": "techno2mahi"
},
{
"code": null,
"e": 51493,
"s": 51481,
"text": "importantly"
},
{
"code": null,
"e": 51499,
"s": 51493,
"text": "itsok"
},
{
"code": null,
"e": 51517,
"s": 51499,
"text": "123kapilpoonia123"
},
{
"code": null,
"e": 51538,
"s": 51517,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 51550,
"s": 51538,
"text": "umadevi9616"
},
{
"code": null,
"e": 51560,
"s": 51550,
"text": "kalrap615"
},
{
"code": null,
"e": 51575,
"s": 51560,
"text": "varshagumber28"
},
{
"code": null,
"e": 51584,
"s": 51575,
"text": "Accolite"
},
{
"code": null,
"e": 51590,
"s": 51584,
"text": "Adobe"
},
{
"code": null,
"e": 51597,
"s": 51590,
"text": "Amazon"
},
{
"code": null,
"e": 51616,
"s": 51597,
"text": "Boomerang Commerce"
},
{
"code": null,
"e": 51625,
"s": 51616,
"text": "Flipkart"
},
{
"code": null,
"e": 51632,
"s": 51625,
"text": "Google"
},
{
"code": null,
"e": 51642,
"s": 51632,
"text": "Microsoft"
},
{
"code": null,
"e": 51651,
"s": 51642,
"text": "Ola Cabs"
},
{
"code": null,
"e": 51658,
"s": 51651,
"text": "Oracle"
},
{
"code": null,
"e": 51668,
"s": 51658,
"text": "OYO Rooms"
},
{
"code": null,
"e": 51673,
"s": 51668,
"text": "Xome"
},
{
"code": null,
"e": 51678,
"s": 51673,
"text": "Tree"
},
{
"code": null,
"e": 51687,
"s": 51678,
"text": "Flipkart"
},
{
"code": null,
"e": 51696,
"s": 51687,
"text": "Accolite"
},
{
"code": null,
"e": 51703,
"s": 51696,
"text": "Amazon"
},
{
"code": null,
"e": 51713,
"s": 51703,
"text": "Microsoft"
},
{
"code": null,
"e": 51723,
"s": 51713,
"text": "OYO Rooms"
},
{
"code": null,
"e": 51732,
"s": 51723,
"text": "Ola Cabs"
},
{
"code": null,
"e": 51739,
"s": 51732,
"text": "Oracle"
},
{
"code": null,
"e": 51745,
"s": 51739,
"text": "Adobe"
},
{
"code": null,
"e": 51752,
"s": 51745,
"text": "Google"
},
{
"code": null,
"e": 51771,
"s": 51752,
"text": "Boomerang Commerce"
},
{
"code": null,
"e": 51776,
"s": 51771,
"text": "Xome"
},
{
"code": null,
"e": 51781,
"s": 51776,
"text": "Tree"
},
{
"code": null,
"e": 51879,
"s": 51781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51888,
"s": 51879,
"text": "Comments"
},
{
"code": null,
"e": 51901,
"s": 51888,
"text": "Old Comments"
},
{
"code": null,
"e": 51944,
"s": 51901,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 51977,
"s": 51944,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 51991,
"s": 51977,
"text": "Decision Tree"
},
{
"code": null,
"e": 52074,
"s": 51991,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 52110,
"s": 52074,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 52158,
"s": 52110,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 52193,
"s": 52158,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 52220,
"s": 52193,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 52262,
"s": 52220,
"text": "Insertion in a Binary Tree in level order"
}
] |
How to declare a class in Java? | Following is the syntax to declare a class.
class className {
//Body of the class
}
You can declare a class by writing the name of the next to the class keyword, followed by the flower braces. Within these, you need to define the body (contents) of the class i.e. fields and methods.
To make the class accessible to all (classes) you need to make it public.
public class MyClass {
//contents of the class (fields and methods)
} | [
{
"code": null,
"e": 1106,
"s": 1062,
"text": "Following is the syntax to declare a class."
},
{
"code": null,
"e": 1150,
"s": 1106,
"text": "class className {\n //Body of the class\n}\n"
},
{
"code": null,
"e": 1350,
"s": 1150,
"text": "You can declare a class by writing the name of the next to the class keyword, followed by the flower braces. Within these, you need to define the body (contents) of the class i.e. fields and methods."
},
{
"code": null,
"e": 1424,
"s": 1350,
"text": "To make the class accessible to all (classes) you need to make it public."
},
{
"code": null,
"e": 1497,
"s": 1424,
"text": "public class MyClass {\n //contents of the class (fields and methods)\n}"
}
] |
How to disable browser's back button with JavaScript? | To disable web browsers’ back button, try to run the following code. This is the code for current HTML page,
<html>
<head>
<title>Disable Browser Back Button</title>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<a href = "newpage.html">Next Page</a>
</body>
<script>
$(document).ready(function() {
function disablePrev() { window.history.forward() }
window.onload = disablePrev();
window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
});
</script>
</html>
The following is the code for newpage.html,
<html>
<body>
Go to back page using web browser back button.
</body>
</html>a | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "To disable web browsers’ back button, try to run the following code. This is the code for current HTML page,"
},
{
"code": null,
"e": 1777,
"s": 1171,
"text": "<html>\n <head>\n <title>Disable Browser Back Button</title>\n <script src = \"http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script src = \"http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"></script>\n </head>\n \n <body>\n <a href = \"newpage.html\">Next Page</a>\n </body>\n <script>\n $(document).ready(function() {\n function disablePrev() { window.history.forward() }\n window.onload = disablePrev();\n window.onpageshow = function(evt) { if (evt.persisted) disableBack() }\n });\n </script>\n</html>"
},
{
"code": null,
"e": 1821,
"s": 1777,
"text": "The following is the code for newpage.html,"
},
{
"code": null,
"e": 1911,
"s": 1821,
"text": "<html>\n <body>\n Go to back page using web browser back button.\n </body>\n</html>a"
}
] |
C# | How to set the alignment of Check Mark in CheckBox? - GeeksforGeeks | 15 Oct, 2021
The CheckBox control is the part of windows form which is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to set the horizontal and vertical alignment of the check mark on a CheckBox using the CheckAlign property of the CheckBox. The default value of this property is MiddleLeft. In Windows form, you can set this property in two different ways:1. Design-Time: It is the simplest way to set the CheckAlign property of a CheckBox using the following steps:
Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the CheckBox control to set the alignment of the check mark in CheckBox by using CheckAlign property.
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the CheckAlign property of a CheckBox programmatically using the following syntax:
public System.Drawing.ContentAlignment CheckAlign { get; set; }
Here, ContentAlignment is used to represent the ContentAlignment values. It will throw an InvalidEnumArgumentException if the value of this property is not according to the ContentAlignment values. Following steps are used to set the CheckAlign property of the CheckBox:
Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class.
// Creating checkbox
CheckBox Mycheckbox = new CheckBox();
Step 2: After creating CheckBox, set the CheckAlign property of the CheckBox provided by the CheckBox class.
// Set the CheckAlign property of the CheckBox
Mycheckbox.CheckAlign = ContentAlignment.MiddleCenter;
Step 3 : And last add this checkbox control to form using Add() method.
// Add this checkbox to form
this.Controls.Add(Mycheckbox);
Example:
CSharp
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = "Select city:"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = "Jaipur"; Mycheckbox.CheckAlign = ContentAlignment.MiddleCenter; // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = "Mumbai"; Mycheckbox1.CheckAlign = ContentAlignment.MiddleCenter; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}
Output:
sweetyty
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
Partial Classes in C#
HashSet in C# with Examples
C# | Inheritance
C# | How to insert an element in an Array?
C# | List Class
Lambda Expressions in C#
C# | Generics - Introduction
What is Regular Expression in C#? | [
{
"code": null,
"e": 24222,
"s": 24194,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 24800,
"s": 24222,
"text": "The CheckBox control is the part of windows form which is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to set the horizontal and vertical alignment of the check mark on a CheckBox using the CheckAlign property of the CheckBox. The default value of this property is MiddleLeft. In Windows form, you can set this property in two different ways:1. Design-Time: It is the simplest way to set the CheckAlign property of a CheckBox using the following steps: "
},
{
"code": null,
"e": 24919,
"s": 24800,
"text": "Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp "
},
{
"code": null,
"e": 25081,
"s": 24919,
"text": "Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. "
},
{
"code": null,
"e": 25246,
"s": 25081,
"text": "Step 3: After drag and drop you will go to the properties of the CheckBox control to set the alignment of the check mark in CheckBox by using CheckAlign property. "
},
{
"code": null,
"e": 25256,
"s": 25246,
"text": "Output: "
},
{
"code": null,
"e": 25432,
"s": 25256,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the CheckAlign property of a CheckBox programmatically using the following syntax: "
},
{
"code": null,
"e": 25496,
"s": 25432,
"text": "public System.Drawing.ContentAlignment CheckAlign { get; set; }"
},
{
"code": null,
"e": 25769,
"s": 25496,
"text": "Here, ContentAlignment is used to represent the ContentAlignment values. It will throw an InvalidEnumArgumentException if the value of this property is not according to the ContentAlignment values. Following steps are used to set the CheckAlign property of the CheckBox: "
},
{
"code": null,
"e": 25862,
"s": 25769,
"text": "Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class. "
},
{
"code": null,
"e": 25921,
"s": 25862,
"text": "// Creating checkbox\nCheckBox Mycheckbox = new CheckBox();"
},
{
"code": null,
"e": 26032,
"s": 25921,
"text": "Step 2: After creating CheckBox, set the CheckAlign property of the CheckBox provided by the CheckBox class. "
},
{
"code": null,
"e": 26134,
"s": 26032,
"text": "// Set the CheckAlign property of the CheckBox\nMycheckbox.CheckAlign = ContentAlignment.MiddleCenter;"
},
{
"code": null,
"e": 26208,
"s": 26134,
"text": "Step 3 : And last add this checkbox control to form using Add() method. "
},
{
"code": null,
"e": 26268,
"s": 26208,
"text": "// Add this checkbox to form\nthis.Controls.Add(Mycheckbox);"
},
{
"code": null,
"e": 26278,
"s": 26268,
"text": "Example: "
},
{
"code": null,
"e": 26285,
"s": 26278,
"text": "CSharp"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = \"Select city:\"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = \"Jaipur\"; Mycheckbox.CheckAlign = ContentAlignment.MiddleCenter; // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = \"Mumbai\"; Mycheckbox1.CheckAlign = ContentAlignment.MiddleCenter; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}",
"e": 27682,
"s": 26285,
"text": null
},
{
"code": null,
"e": 27692,
"s": 27682,
"text": "Output: "
},
{
"code": null,
"e": 27703,
"s": 27694,
"text": "sweetyty"
},
{
"code": null,
"e": 27706,
"s": 27703,
"text": "C#"
},
{
"code": null,
"e": 27804,
"s": 27706,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27813,
"s": 27804,
"text": "Comments"
},
{
"code": null,
"e": 27826,
"s": 27813,
"text": "Old Comments"
},
{
"code": null,
"e": 27849,
"s": 27826,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27889,
"s": 27849,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27911,
"s": 27889,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27939,
"s": 27911,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27956,
"s": 27939,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27999,
"s": 27956,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28015,
"s": 27999,
"text": "C# | List Class"
},
{
"code": null,
"e": 28040,
"s": 28015,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 28069,
"s": 28040,
"text": "C# | Generics - Introduction"
}
] |
From inside of a Docker container, how do I connect to the localhost of the machine | Suppose you have an Nginx web server running inside an Nginx container in your host machine. And you have a MySQL database running in your host machine. Now, you want to access the MySQL server in your host machine from the Nginx container. Also, the MySQL is running on your localhost and the host machine does not expose any port to the outside world. Hence, we can conclude that MySQL is bound to be run on localhost only and not accessible to the outside world because it is not bound on the IP address.
In this article, we will explain the different ways through which you can access the MySQL running on your localhost or any other program in your host machine from the container.
To sum up in a short discussion, if you are on Docker for Windows or Mac, you can simply connect to MySQL using host.docker.internal instead of 127.0.0.1. If you started your Docker container in your local Linux machine using --add-host host.docker.internal:host-gateway option, you can even use the host.docker.internal string in your connection in your Linux host.
Now, let’s discuss the solutions in detail.
A simple solution to this in a Linux machine is to use the --network=”host” option along with the Docker run command. After that, the localhost (127.0.0.1) in your Docker container will point to the host Linux machine.This runs a Docker container with the settings of the network set to host.
This container will share the network with the host machine and the container’s localhost will point to the host machine. Please note that any port exposed from your Docker container is now opened in your host machine and that too without having to use the publish options.
You can verify this by listing the IP address using the following commands.
In your local machine -
$ ip addr show eth0
And while running the container -
$ docker run -it --network=host ubuntu:latest ip addr show eth0
On executing these commands, you will find that both the container and the host machine have the same IP address and share the same network stack.
If you are using a Mac host, you can use -
HOSTNAME= docker.for.mac.host.internal
Or
HOSTNAME = docker.for.mac.localhost
in your Docker run command. And then you can use -
mysql -uroot -hdocker.for.mac.localhost
inside your Docker container to access MySQL running in your host.
You can also access the MySQL service running in your host machine in your Docker container using the bridge network mode. For that, you need to ensure that the MySQL service is actively listening for all the connections in the 172.17.42.1 address. You can include the bind-address = 172.17.42.1 in your MySQL config file.
In host mode, you can use -
bind-address = 127.0.0.1 in your MySQL config file and then, you can connect to localhost from your containers.
$ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
To sum up, these are the various ways through which you can easily connect to a MySQL service running inside your host machine from a Docker container. In a gist, you can use the --network=host to bind the localhost with your Docker container and they access the MySQL service inside your container using the hostname “127.0.0.1”. Depending on whether you are using a Mac, Windows, or Linux host machine, you can choose the best possible solution that caters to your own requirements. | [
{
"code": null,
"e": 1570,
"s": 1062,
"text": "Suppose you have an Nginx web server running inside an Nginx container in your host machine. And you have a MySQL database running in your host machine. Now, you want to access the MySQL server in your host machine from the Nginx container. Also, the MySQL is running on your localhost and the host machine does not expose any port to the outside world. Hence, we can conclude that MySQL is bound to be run on localhost only and not accessible to the outside world because it is not bound on the IP address."
},
{
"code": null,
"e": 1749,
"s": 1570,
"text": "In this article, we will explain the different ways through which you can access the MySQL running on your localhost or any other program in your host machine from the container."
},
{
"code": null,
"e": 2116,
"s": 1749,
"text": "To sum up in a short discussion, if you are on Docker for Windows or Mac, you can simply connect to MySQL using host.docker.internal instead of 127.0.0.1. If you started your Docker container in your local Linux machine using --add-host host.docker.internal:host-gateway option, you can even use the host.docker.internal string in your connection in your Linux host."
},
{
"code": null,
"e": 2160,
"s": 2116,
"text": "Now, let’s discuss the solutions in detail."
},
{
"code": null,
"e": 2453,
"s": 2160,
"text": "A simple solution to this in a Linux machine is to use the --network=”host” option along with the Docker run command. After that, the localhost (127.0.0.1) in your Docker container will point to the host Linux machine.This runs a Docker container with the settings of the network set to host."
},
{
"code": null,
"e": 2727,
"s": 2453,
"text": "This container will share the network with the host machine and the container’s localhost will point to the host machine. Please note that any port exposed from your Docker container is now opened in your host machine and that too without having to use the publish options."
},
{
"code": null,
"e": 2803,
"s": 2727,
"text": "You can verify this by listing the IP address using the following commands."
},
{
"code": null,
"e": 2827,
"s": 2803,
"text": "In your local machine -"
},
{
"code": null,
"e": 2847,
"s": 2827,
"text": "$ ip addr show eth0"
},
{
"code": null,
"e": 2881,
"s": 2847,
"text": "And while running the container -"
},
{
"code": null,
"e": 2945,
"s": 2881,
"text": "$ docker run -it --network=host ubuntu:latest ip addr show eth0"
},
{
"code": null,
"e": 3092,
"s": 2945,
"text": "On executing these commands, you will find that both the container and the host machine have the same IP address and share the same network stack."
},
{
"code": null,
"e": 3135,
"s": 3092,
"text": "If you are using a Mac host, you can use -"
},
{
"code": null,
"e": 3174,
"s": 3135,
"text": "HOSTNAME= docker.for.mac.host.internal"
},
{
"code": null,
"e": 3177,
"s": 3174,
"text": "Or"
},
{
"code": null,
"e": 3214,
"s": 3177,
"text": "HOSTNAME = docker.for.mac.localhost\n"
},
{
"code": null,
"e": 3265,
"s": 3214,
"text": "in your Docker run command. And then you can use -"
},
{
"code": null,
"e": 3305,
"s": 3265,
"text": "mysql -uroot -hdocker.for.mac.localhost"
},
{
"code": null,
"e": 3372,
"s": 3305,
"text": "inside your Docker container to access MySQL running in your host."
},
{
"code": null,
"e": 3695,
"s": 3372,
"text": "You can also access the MySQL service running in your host machine in your Docker container using the bridge network mode. For that, you need to ensure that the MySQL service is actively listening for all the connections in the 172.17.42.1 address. You can include the bind-address = 172.17.42.1 in your MySQL config file."
},
{
"code": null,
"e": 3723,
"s": 3695,
"text": "In host mode, you can use -"
},
{
"code": null,
"e": 3835,
"s": 3723,
"text": "bind-address = 127.0.0.1 in your MySQL config file and then, you can connect to localhost from your containers."
},
{
"code": null,
"e": 3907,
"s": 3835,
"text": "$ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p"
},
{
"code": null,
"e": 4392,
"s": 3907,
"text": "To sum up, these are the various ways through which you can easily connect to a MySQL service running inside your host machine from a Docker container. In a gist, you can use the --network=host to bind the localhost with your Docker container and they access the MySQL service inside your container using the hostname “127.0.0.1”. Depending on whether you are using a Mac, Windows, or Linux host machine, you can choose the best possible solution that caters to your own requirements."
}
] |
Explain reference and pointer in C programming? | Explain the concept of reference and pointer in a c programming language using examples.
It is the alternate name for the variable that we declared.
It is the alternate name for the variable that we declared.
It can be accessed by using pass by value.
It can be accessed by using pass by value.
It cannot hold the null values.
It cannot hold the null values.
datatype *variablename
For example, int *a; //a contains the address of int type variable.
It stores the address of variable.
It stores the address of variable.
We can hold the null values using pointer.
We can hold the null values using pointer.
It can be access by using pass by reference.
It can be access by using pass by reference.
No need of initialization while declaring the variable.
No need of initialization while declaring the variable.
pointer variable= & another variable;
Live Demo
#include<stdio.h>
int main(){
int a=2,b=4;
int *p;
printf("add of a=%d\n",&a);
printf("add of b=%d\n",&b);
p=&a; // p points to variable a
printf("a value is =%d\n",a); // prints a value
printf("*p value is =%d\n",*p); //prints a value
printf("p value is =%d\n",p); //prints the address of a
p=&b; //p points to variable b
printf("b value is =%d\n",b); // prints b value
printf("*p value is =%d\n",*p); //prints b value
printf("p value is =%d\n",p); //prints add of b
}
add of a=-748899512
add of b=-748899508
a value is =2
*p value is =2
p value is =-748899512
b value is =4
*p value is =4
p value is =-748899508 | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "Explain the concept of reference and pointer in a c programming language using examples."
},
{
"code": null,
"e": 1211,
"s": 1151,
"text": "It is the alternate name for the variable that we declared."
},
{
"code": null,
"e": 1271,
"s": 1211,
"text": "It is the alternate name for the variable that we declared."
},
{
"code": null,
"e": 1314,
"s": 1271,
"text": "It can be accessed by using pass by value."
},
{
"code": null,
"e": 1357,
"s": 1314,
"text": "It can be accessed by using pass by value."
},
{
"code": null,
"e": 1389,
"s": 1357,
"text": "It cannot hold the null values."
},
{
"code": null,
"e": 1421,
"s": 1389,
"text": "It cannot hold the null values."
},
{
"code": null,
"e": 1444,
"s": 1421,
"text": "datatype *variablename"
},
{
"code": null,
"e": 1512,
"s": 1444,
"text": "For example, int *a; //a contains the address of int type variable."
},
{
"code": null,
"e": 1547,
"s": 1512,
"text": "It stores the address of variable."
},
{
"code": null,
"e": 1582,
"s": 1547,
"text": "It stores the address of variable."
},
{
"code": null,
"e": 1625,
"s": 1582,
"text": "We can hold the null values using pointer."
},
{
"code": null,
"e": 1668,
"s": 1625,
"text": "We can hold the null values using pointer."
},
{
"code": null,
"e": 1713,
"s": 1668,
"text": "It can be access by using pass by reference."
},
{
"code": null,
"e": 1758,
"s": 1713,
"text": "It can be access by using pass by reference."
},
{
"code": null,
"e": 1814,
"s": 1758,
"text": "No need of initialization while declaring the variable."
},
{
"code": null,
"e": 1870,
"s": 1814,
"text": "No need of initialization while declaring the variable."
},
{
"code": null,
"e": 1908,
"s": 1870,
"text": "pointer variable= & another variable;"
},
{
"code": null,
"e": 1919,
"s": 1908,
"text": " Live Demo"
},
{
"code": null,
"e": 2425,
"s": 1919,
"text": "#include<stdio.h>\nint main(){\n int a=2,b=4;\n int *p;\n printf(\"add of a=%d\\n\",&a);\n printf(\"add of b=%d\\n\",&b);\n p=&a; // p points to variable a\n printf(\"a value is =%d\\n\",a); // prints a value\n printf(\"*p value is =%d\\n\",*p); //prints a value\n printf(\"p value is =%d\\n\",p); //prints the address of a\n p=&b; //p points to variable b\n printf(\"b value is =%d\\n\",b); // prints b value\n printf(\"*p value is =%d\\n\",*p); //prints b value\n printf(\"p value is =%d\\n\",p); //prints add of b\n}"
},
{
"code": null,
"e": 2569,
"s": 2425,
"text": "add of a=-748899512\nadd of b=-748899508\na value is =2\n*p value is =2\np value is =-748899512\nb value is =4\n*p value is =4\np value is =-748899508"
}
] |
LISP - Input & Output | Common LISP provides numerous input-output functions. We have already used the format function, and print function for output. In this section, we will look into some of the most commonly used input-output functions provided in LISP.
The following table provides the most commonly used input functions of LISP −
read & optional input-stream eof-error-p eof-value recursive-p
It reads in the printed representation of a Lisp object from input-stream, builds a corresponding Lisp object, and returns the object.
read-preserving-whitespace & optional in-stream eof-error-p eof-value recursive-p
It is used in some specialized situations where it is desirable to determine precisely what character terminated the extended token.
read-line & optional input-stream eof-error-p eof-value recursive-p
It reads in a line of text terminated by a newline.
read-char & optional input-stream eof-error-p eof-value recursive-p
It takes one character from input-stream and returns it as a character object.
unread-char character & optional input-stream
It puts the character most recently read from the input-stream, onto the front of input-stream.
peek-char & optional peek-type input-stream eof-error-p eof-value recursive-p
It returns the next character to be read from input-stream, without actually removing it from the input stream.
listen & optional input-stream
The predicate listen is true if there is a character immediately available from input-stream, and is false if not.
read-char-no-hang & optional input-stream eof-error-p eof-value recursive-p
It is similar to read-char, but if it does not get a character, it does not wait for a character, but returns nil immediately.
clear-input & optional input-stream
It clears any buffered input associated with input-stream.
read-from-string string & optional eof-error-p eof-value & key :start :end :preserve-whitespace
It takes the characters of the string successively and builds a LISP object and returns the object. It also returns the index of the first character in the string not read, or the length of the string (or, length +1), as the case may be.
parse-integer string & key :start :end :radix :junk-allowed
It examines the substring of string delimited by :start and :end (default to the beginning and end of the string). It skips over whitespace characters and then attempts to parse an integer.
read-byte binary-input-stream & optional eof-error-p eof-value
It reads one byte from the binary-input-stream and returns it in the form of an integer.
The read function is used for taking input from the keyboard. It may not take any argument.
For example, consider the code snippet −
(write ( + 15.0 (read)))
Assume the user enters 10.2 from the STDIN Input, it returns,
25.2
The read function reads characters from an input stream and interprets them by parsing as representations of Lisp objects.
Create a new source code file named main.lisp and type the following code in it −
; the function AreaOfCircle
; calculates area of a circle
; when the radius is input from keyboard
(defun AreaOfCircle()
(terpri)
(princ "Enter Radius: ")
(setq radius (read))
(setq area (* 3.1416 radius radius))
(princ "Area: ")
(write area))
(AreaOfCircle)
When you execute the code, it returns the following result −
Enter Radius: 5 (STDIN Input)
Area: 78.53999
Create a new source code file named main.lisp and type the following code in it.
(with-input-from-string (stream "Welcome to Tutorials Point!")
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (read-char stream))
(print (peek-char nil stream nil 'the-end))
(values)
)
When you execute the code, it returns the following result −
#\W
#\e
#\l
#\c
#\o
#\m
#\e
#\Space
#\t
#\o
#\Space
All output functions in LISP take an optional argument called output-stream, where the output is sent. If not mentioned or nil, output-stream defaults to the value of the variable *standard-output*.
The following table provides the most commonly used output functions of LISP −
write object & key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array
write object & key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :right-margin :miser-width :lines :pprint-dispatch
Both write the object to the output stream specified by :stream, which defaults to the value of *standard-output*. Other values default to the corresponding global variables set for printing.
prin1 object & optional output-stream
print object & optional output-stream
pprint object & optional output-stream
princ object & optional output-stream
All these functions outputs the printed representation of object to output-stream. However, the following differences are there −
prin1 returns the object as its value.
prin1 returns the object as its value.
print prints the object with a preceding newline and followed by a space. It returns object.
print prints the object with a preceding newline and followed by a space. It returns object.
pprint is just like print except that the trailing space is omitted.
pprint is just like print except that the trailing space is omitted.
princ is just like prin1 except that the output has no escape character
princ is just like prin1 except that the output has no escape character
write-to-string object & key :escape :radix :base :circle :pretty :level :length :case :gensym :array
write-to-string object & key :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :right-margin :miser-width :lines :pprint-dispatch
prin1-to-string object
princ-to-string object
The object is effectively printed and the output characters are made into a string, which is returned.
write-char character & optional output-stream
It outputs the character to output-stream, and returns character.
write-string string & optional output-stream & key :start :end
It writes the characters of the specified substring of string to the output-stream.
write-line string & optional output-stream & key :start :end
It works the same way as write-string, but outputs a newline afterwards.
terpri & optional output-stream
It outputs a newline to output-stream.
fresh-line & optional output-stream
it outputs a newline only if the stream is not already at the start of a line.
finish-output & optional output-stream
force-output & optional output-stream
clear-output & optional output-stream
The function finish-output attempts to ensure that all output sent to output-stream has reached its destination, and only then returns nil.
The function finish-output attempts to ensure that all output sent to output-stream has reached its destination, and only then returns nil.
The function force-output initiates the emptying of any internal buffers but returns nil without waiting for completion or acknowledgment.
The function force-output initiates the emptying of any internal buffers but returns nil without waiting for completion or acknowledgment.
The function clear-output attempts to abort any outstanding output operation in progress in order to allow as little output as possible to continue to the destination.
The function clear-output attempts to abort any outstanding output operation in progress in order to allow as little output as possible to continue to the destination.
write-byte integer binary-output-stream
It writes one byte, the value of the integer.
Create a new source code file named main.lisp and type the following code in it.
; this program inputs a numbers and doubles it
(defun DoubleNumber()
(terpri)
(princ "Enter Number : ")
(setq n1 (read))
(setq doubled (* 2.0 n1))
(princ "The Number: ")
(write n1)
(terpri)
(princ "The Number Doubled: ")
(write doubled)
)
(DoubleNumber)
When you execute the code, it returns the following result −
Enter Number : 3456.78 (STDIN Input)
The Number: 3456.78
The Number Doubled: 6913.56
The function format is used for producing nicely formatted text. It has the following syntax −
format destination control-string &rest arguments
where,
destination is standard output
control-string holds the characters to be output and the printing directive.
A format directive consists of a tilde (~), optional prefix parameters separated by commas, optional colon (:) and at-sign (@) modifiers, and a single character indicating what kind of directive this is.
The prefix parameters are generally integers, notated as optionally signed decimal numbers.
The following table provides brief description of the commonly used directives −
~A
Is followed by ASCII arguments.
~S
Is followed by S-expressions.
~D
For decimal arguments.
~B
For binary arguments.
~O
For octal arguments.
~X
For hexadecimal arguments.
~C
For character arguments.
~F
For Fixed-format floating-point arguments.
~E
Exponential floating-point arguments.
~$
Dollar and floating point arguments.
~%
A new line is printed.
~*
Next argument is ignored.
~?
Indirection. The next argument must be a string, and the one after it a list.
Let us rewrite the program calculating a circle's area −
Create a new source code file named main.lisp and type the following code in it.
(defun AreaOfCircle()
(terpri)
(princ "Enter Radius: ")
(setq radius (read))
(setq area (* 3.1416 radius radius))
(format t "Radius: = ~F~% Area = ~F" radius area)
)
(AreaOfCircle)
When you execute the code, it returns the following result −
Enter Radius: 10.234 (STDIN Input)
Radius: = 10.234
Area = 329.03473
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2294,
"s": 2060,
"text": "Common LISP provides numerous input-output functions. We have already used the format function, and print function for output. In this section, we will look into some of the most commonly used input-output functions provided in LISP."
},
{
"code": null,
"e": 2372,
"s": 2294,
"text": "The following table provides the most commonly used input functions of LISP −"
},
{
"code": null,
"e": 2435,
"s": 2372,
"text": "read & optional input-stream eof-error-p eof-value recursive-p"
},
{
"code": null,
"e": 2570,
"s": 2435,
"text": "It reads in the printed representation of a Lisp object from input-stream, builds a corresponding Lisp object, and returns the object."
},
{
"code": null,
"e": 2652,
"s": 2570,
"text": "read-preserving-whitespace & optional in-stream eof-error-p eof-value recursive-p"
},
{
"code": null,
"e": 2785,
"s": 2652,
"text": "It is used in some specialized situations where it is desirable to determine precisely what character terminated the extended token."
},
{
"code": null,
"e": 2853,
"s": 2785,
"text": "read-line & optional input-stream eof-error-p eof-value recursive-p"
},
{
"code": null,
"e": 2905,
"s": 2853,
"text": "It reads in a line of text terminated by a newline."
},
{
"code": null,
"e": 2973,
"s": 2905,
"text": "read-char & optional input-stream eof-error-p eof-value recursive-p"
},
{
"code": null,
"e": 3052,
"s": 2973,
"text": "It takes one character from input-stream and returns it as a character object."
},
{
"code": null,
"e": 3098,
"s": 3052,
"text": "unread-char character & optional input-stream"
},
{
"code": null,
"e": 3194,
"s": 3098,
"text": "It puts the character most recently read from the input-stream, onto the front of input-stream."
},
{
"code": null,
"e": 3272,
"s": 3194,
"text": "peek-char & optional peek-type input-stream eof-error-p eof-value recursive-p"
},
{
"code": null,
"e": 3384,
"s": 3272,
"text": "It returns the next character to be read from input-stream, without actually removing it from the input stream."
},
{
"code": null,
"e": 3415,
"s": 3384,
"text": "listen & optional input-stream"
},
{
"code": null,
"e": 3530,
"s": 3415,
"text": "The predicate listen is true if there is a character immediately available from input-stream, and is false if not."
},
{
"code": null,
"e": 3606,
"s": 3530,
"text": "read-char-no-hang & optional input-stream eof-error-p eof-value recursive-p"
},
{
"code": null,
"e": 3733,
"s": 3606,
"text": "It is similar to read-char, but if it does not get a character, it does not wait for a character, but returns nil immediately."
},
{
"code": null,
"e": 3769,
"s": 3733,
"text": "clear-input & optional input-stream"
},
{
"code": null,
"e": 3828,
"s": 3769,
"text": "It clears any buffered input associated with input-stream."
},
{
"code": null,
"e": 3924,
"s": 3828,
"text": "read-from-string string & optional eof-error-p eof-value & key :start :end :preserve-whitespace"
},
{
"code": null,
"e": 4162,
"s": 3924,
"text": "It takes the characters of the string successively and builds a LISP object and returns the object. It also returns the index of the first character in the string not read, or the length of the string (or, length +1), as the case may be."
},
{
"code": null,
"e": 4222,
"s": 4162,
"text": "parse-integer string & key :start :end :radix :junk-allowed"
},
{
"code": null,
"e": 4412,
"s": 4222,
"text": "It examines the substring of string delimited by :start and :end (default to the beginning and end of the string). It skips over whitespace characters and then attempts to parse an integer."
},
{
"code": null,
"e": 4475,
"s": 4412,
"text": "read-byte binary-input-stream & optional eof-error-p eof-value"
},
{
"code": null,
"e": 4564,
"s": 4475,
"text": "It reads one byte from the binary-input-stream and returns it in the form of an integer."
},
{
"code": null,
"e": 4656,
"s": 4564,
"text": "The read function is used for taking input from the keyboard. It may not take any argument."
},
{
"code": null,
"e": 4697,
"s": 4656,
"text": "For example, consider the code snippet −"
},
{
"code": null,
"e": 4723,
"s": 4697,
"text": "(write ( + 15.0 (read)))\n"
},
{
"code": null,
"e": 4785,
"s": 4723,
"text": "Assume the user enters 10.2 from the STDIN Input, it returns,"
},
{
"code": null,
"e": 4791,
"s": 4785,
"text": "25.2\n"
},
{
"code": null,
"e": 4914,
"s": 4791,
"text": "The read function reads characters from an input stream and interprets them by parsing as representations of Lisp objects."
},
{
"code": null,
"e": 4996,
"s": 4914,
"text": "Create a new source code file named main.lisp and type the following code in it −"
},
{
"code": null,
"e": 5256,
"s": 4996,
"text": "; the function AreaOfCircle\n; calculates area of a circle\n; when the radius is input from keyboard\n\n(defun AreaOfCircle()\n(terpri)\n(princ \"Enter Radius: \")\n(setq radius (read))\n(setq area (* 3.1416 radius radius))\n(princ \"Area: \")\n(write area))\n(AreaOfCircle)"
},
{
"code": null,
"e": 5317,
"s": 5256,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 5363,
"s": 5317,
"text": "Enter Radius: 5 (STDIN Input)\nArea: 78.53999\n"
},
{
"code": null,
"e": 5444,
"s": 5363,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 5868,
"s": 5444,
"text": "(with-input-from-string (stream \"Welcome to Tutorials Point!\")\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (read-char stream))\n (print (peek-char nil stream nil 'the-end))\n (values)\n)"
},
{
"code": null,
"e": 5929,
"s": 5868,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 5993,
"s": 5929,
"text": "#\\W \n#\\e \n#\\l \n#\\c \n#\\o \n#\\m \n#\\e \n#\\Space \n#\\t \n#\\o \n#\\Space \n"
},
{
"code": null,
"e": 6192,
"s": 5993,
"text": "All output functions in LISP take an optional argument called output-stream, where the output is sent. If not mentioned or nil, output-stream defaults to the value of the variable *standard-output*."
},
{
"code": null,
"e": 6271,
"s": 6192,
"text": "The following table provides the most commonly used output functions of LISP −"
},
{
"code": null,
"e": 6371,
"s": 6271,
"text": "write object & key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array"
},
{
"code": null,
"e": 6532,
"s": 6371,
"text": "write object & key :stream :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :right-margin :miser-width :lines :pprint-dispatch"
},
{
"code": null,
"e": 6724,
"s": 6532,
"text": "Both write the object to the output stream specified by :stream, which defaults to the value of *standard-output*. Other values default to the corresponding global variables set for printing."
},
{
"code": null,
"e": 6762,
"s": 6724,
"text": "prin1 object & optional output-stream"
},
{
"code": null,
"e": 6800,
"s": 6762,
"text": "print object & optional output-stream"
},
{
"code": null,
"e": 6839,
"s": 6800,
"text": "pprint object & optional output-stream"
},
{
"code": null,
"e": 6877,
"s": 6839,
"text": "princ object & optional output-stream"
},
{
"code": null,
"e": 7007,
"s": 6877,
"text": "All these functions outputs the printed representation of object to output-stream. However, the following differences are there −"
},
{
"code": null,
"e": 7046,
"s": 7007,
"text": "prin1 returns the object as its value."
},
{
"code": null,
"e": 7085,
"s": 7046,
"text": "prin1 returns the object as its value."
},
{
"code": null,
"e": 7178,
"s": 7085,
"text": "print prints the object with a preceding newline and followed by a space. It returns object."
},
{
"code": null,
"e": 7271,
"s": 7178,
"text": "print prints the object with a preceding newline and followed by a space. It returns object."
},
{
"code": null,
"e": 7340,
"s": 7271,
"text": "pprint is just like print except that the trailing space is omitted."
},
{
"code": null,
"e": 7409,
"s": 7340,
"text": "pprint is just like print except that the trailing space is omitted."
},
{
"code": null,
"e": 7481,
"s": 7409,
"text": "princ is just like prin1 except that the output has no escape character"
},
{
"code": null,
"e": 7553,
"s": 7481,
"text": "princ is just like prin1 except that the output has no escape character"
},
{
"code": null,
"e": 7656,
"s": 7553,
"text": "write-to-string object & key :escape :radix :base :circle :pretty :level :length :case :gensym :array "
},
{
"code": null,
"e": 7819,
"s": 7656,
"text": "write-to-string object & key :escape :radix :base :circle :pretty :level :length :case :gensym :array :readably :right-margin :miser-width :lines :pprint-dispatch"
},
{
"code": null,
"e": 7842,
"s": 7819,
"text": "prin1-to-string object"
},
{
"code": null,
"e": 7865,
"s": 7842,
"text": "princ-to-string object"
},
{
"code": null,
"e": 7968,
"s": 7865,
"text": "The object is effectively printed and the output characters are made into a string, which is returned."
},
{
"code": null,
"e": 8014,
"s": 7968,
"text": "write-char character & optional output-stream"
},
{
"code": null,
"e": 8080,
"s": 8014,
"text": "It outputs the character to output-stream, and returns character."
},
{
"code": null,
"e": 8143,
"s": 8080,
"text": "write-string string & optional output-stream & key :start :end"
},
{
"code": null,
"e": 8227,
"s": 8143,
"text": "It writes the characters of the specified substring of string to the output-stream."
},
{
"code": null,
"e": 8288,
"s": 8227,
"text": "write-line string & optional output-stream & key :start :end"
},
{
"code": null,
"e": 8361,
"s": 8288,
"text": "It works the same way as write-string, but outputs a newline afterwards."
},
{
"code": null,
"e": 8393,
"s": 8361,
"text": "terpri & optional output-stream"
},
{
"code": null,
"e": 8432,
"s": 8393,
"text": "It outputs a newline to output-stream."
},
{
"code": null,
"e": 8468,
"s": 8432,
"text": "fresh-line & optional output-stream"
},
{
"code": null,
"e": 8547,
"s": 8468,
"text": "it outputs a newline only if the stream is not already at the start of a line."
},
{
"code": null,
"e": 8586,
"s": 8547,
"text": "finish-output & optional output-stream"
},
{
"code": null,
"e": 8624,
"s": 8586,
"text": "force-output & optional output-stream"
},
{
"code": null,
"e": 8662,
"s": 8624,
"text": "clear-output & optional output-stream"
},
{
"code": null,
"e": 8802,
"s": 8662,
"text": "The function finish-output attempts to ensure that all output sent to output-stream has reached its destination, and only then returns nil."
},
{
"code": null,
"e": 8942,
"s": 8802,
"text": "The function finish-output attempts to ensure that all output sent to output-stream has reached its destination, and only then returns nil."
},
{
"code": null,
"e": 9081,
"s": 8942,
"text": "The function force-output initiates the emptying of any internal buffers but returns nil without waiting for completion or acknowledgment."
},
{
"code": null,
"e": 9220,
"s": 9081,
"text": "The function force-output initiates the emptying of any internal buffers but returns nil without waiting for completion or acknowledgment."
},
{
"code": null,
"e": 9388,
"s": 9220,
"text": "The function clear-output attempts to abort any outstanding output operation in progress in order to allow as little output as possible to continue to the destination."
},
{
"code": null,
"e": 9556,
"s": 9388,
"text": "The function clear-output attempts to abort any outstanding output operation in progress in order to allow as little output as possible to continue to the destination."
},
{
"code": null,
"e": 9596,
"s": 9556,
"text": "write-byte integer binary-output-stream"
},
{
"code": null,
"e": 9642,
"s": 9596,
"text": "It writes one byte, the value of the integer."
},
{
"code": null,
"e": 9723,
"s": 9642,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 10004,
"s": 9723,
"text": "; this program inputs a numbers and doubles it\n(defun DoubleNumber()\n (terpri)\n (princ \"Enter Number : \")\n (setq n1 (read))\n (setq doubled (* 2.0 n1))\n (princ \"The Number: \")\n (write n1)\n (terpri)\n (princ \"The Number Doubled: \")\n (write doubled)\n)\n(DoubleNumber)"
},
{
"code": null,
"e": 10065,
"s": 10004,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 10151,
"s": 10065,
"text": "Enter Number : 3456.78 (STDIN Input)\nThe Number: 3456.78\nThe Number Doubled: 6913.56\n"
},
{
"code": null,
"e": 10246,
"s": 10151,
"text": "The function format is used for producing nicely formatted text. It has the following syntax −"
},
{
"code": null,
"e": 10297,
"s": 10246,
"text": "format destination control-string &rest arguments\n"
},
{
"code": null,
"e": 10304,
"s": 10297,
"text": "where,"
},
{
"code": null,
"e": 10335,
"s": 10304,
"text": "destination is standard output"
},
{
"code": null,
"e": 10412,
"s": 10335,
"text": "control-string holds the characters to be output and the printing directive."
},
{
"code": null,
"e": 10616,
"s": 10412,
"text": "A format directive consists of a tilde (~), optional prefix parameters separated by commas, optional colon (:) and at-sign (@) modifiers, and a single character indicating what kind of directive this is."
},
{
"code": null,
"e": 10708,
"s": 10616,
"text": "The prefix parameters are generally integers, notated as optionally signed decimal numbers."
},
{
"code": null,
"e": 10789,
"s": 10708,
"text": "The following table provides brief description of the commonly used directives −"
},
{
"code": null,
"e": 10792,
"s": 10789,
"text": "~A"
},
{
"code": null,
"e": 10824,
"s": 10792,
"text": "Is followed by ASCII arguments."
},
{
"code": null,
"e": 10827,
"s": 10824,
"text": "~S"
},
{
"code": null,
"e": 10857,
"s": 10827,
"text": "Is followed by S-expressions."
},
{
"code": null,
"e": 10860,
"s": 10857,
"text": "~D"
},
{
"code": null,
"e": 10883,
"s": 10860,
"text": "For decimal arguments."
},
{
"code": null,
"e": 10886,
"s": 10883,
"text": "~B"
},
{
"code": null,
"e": 10908,
"s": 10886,
"text": "For binary arguments."
},
{
"code": null,
"e": 10911,
"s": 10908,
"text": "~O"
},
{
"code": null,
"e": 10932,
"s": 10911,
"text": "For octal arguments."
},
{
"code": null,
"e": 10935,
"s": 10932,
"text": "~X"
},
{
"code": null,
"e": 10962,
"s": 10935,
"text": "For hexadecimal arguments."
},
{
"code": null,
"e": 10965,
"s": 10962,
"text": "~C"
},
{
"code": null,
"e": 10990,
"s": 10965,
"text": "For character arguments."
},
{
"code": null,
"e": 10993,
"s": 10990,
"text": "~F"
},
{
"code": null,
"e": 11036,
"s": 10993,
"text": "For Fixed-format floating-point arguments."
},
{
"code": null,
"e": 11039,
"s": 11036,
"text": "~E"
},
{
"code": null,
"e": 11077,
"s": 11039,
"text": "Exponential floating-point arguments."
},
{
"code": null,
"e": 11080,
"s": 11077,
"text": "~$"
},
{
"code": null,
"e": 11117,
"s": 11080,
"text": "Dollar and floating point arguments."
},
{
"code": null,
"e": 11120,
"s": 11117,
"text": "~%"
},
{
"code": null,
"e": 11143,
"s": 11120,
"text": "A new line is printed."
},
{
"code": null,
"e": 11146,
"s": 11143,
"text": "~*"
},
{
"code": null,
"e": 11172,
"s": 11146,
"text": "Next argument is ignored."
},
{
"code": null,
"e": 11175,
"s": 11172,
"text": "~?"
},
{
"code": null,
"e": 11253,
"s": 11175,
"text": "Indirection. The next argument must be a string, and the one after it a list."
},
{
"code": null,
"e": 11310,
"s": 11253,
"text": "Let us rewrite the program calculating a circle's area −"
},
{
"code": null,
"e": 11391,
"s": 11310,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 11587,
"s": 11391,
"text": "(defun AreaOfCircle()\n (terpri)\n (princ \"Enter Radius: \")\n (setq radius (read))\n (setq area (* 3.1416 radius radius))\n (format t \"Radius: = ~F~% Area = ~F\" radius area)\n)\n(AreaOfCircle)"
},
{
"code": null,
"e": 11648,
"s": 11587,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 11718,
"s": 11648,
"text": "Enter Radius: 10.234 (STDIN Input)\nRadius: = 10.234\nArea = 329.03473\n"
},
{
"code": null,
"e": 11751,
"s": 11718,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 11766,
"s": 11751,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 11773,
"s": 11766,
"text": " Print"
},
{
"code": null,
"e": 11784,
"s": 11773,
"text": " Add Notes"
}
] |
Difference Between Object and Class in C++ | In this post, we will understand the difference between an object and a class with respect to C++ programming language.
It is a building block of code in C++ that helps implement object oriented programming.
It is a type that is defined by the user.
It holds its own data members and member functions.
These data members and member functions can be accessed by creating an instance of the class.
They can be used to manipulate the variables and can be used to define property to tell how the objects in a class have to act.
It can be understood as a blueprint for an object.Example: Consider the class of Employees. There may be many attributes such as name of employee, age, date of birth, title, and so on.These are called the data members.The member functions could be 'draw_salary', 'get_promotion', which perform certain actions with respect to class objects.These would be the common properties shared by all employees.
Example: Consider the class of Employees. There may be many attributes such as name of employee, age, date of birth, title, and so on.
These are called the data members.
The member functions could be 'draw_salary', 'get_promotion', which perform certain actions with respect to class objects.
These would be the common properties shared by all employees.
It is defined using the keyword 'class'.
It is followed by the name of the class.
The class body is defined within flower brackets, and is terminated using a semi-colon.
class class_name {
body_of_class
};
An object is an instance of a class.
When a class is defined, memory is not allocated to it.
The moment an object is created, memory gets allocated to all the attributes of the class.
When a class is defined, the specifics of the object are defined.
If that class has to be put to use, and operations need to be performed, an object needs to be created.
The object has to be explicitly created using the below syntax.
class_name object_name;
The data members and member functions of a class can be accessed by an object with the help of the dot ('.') operator.Example: Assume a class has been created with the required attributes and member functions.Once an object with respect to that class is created, the member functions can be accessed in the below way:
Example: Assume a class has been created with the required attributes and member functions.
Once an object with respect to that class is created, the member functions can be accessed in the below way:
object_name.member_function()
The data members which are public in nature, can be accessed in the same manner, as shown above, i.e using the '.' operator.
Public members are those that are defined using the 'public' keyword.
Private members are those that are defined using the 'private' keyword.
These members can't be accessed directly by the object.
The 'public', 'private' and 'protected' keywords are known as access controls of the data members.
Member functions that are defined inside the class are considered to be inline by default.
The inline functions ae those which are expanded right after the function is defined. They are copied everywhere when the code is compiled (similar to macros). This means that the overhead of calling the function is reduced.
Any non-class function can be made as an inline function by attaching the 'inline' keyword to it. | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "In this post, we will understand the difference between an object and a class with respect to C++ programming language."
},
{
"code": null,
"e": 1270,
"s": 1182,
"text": "It is a building block of code in C++ that helps implement object oriented programming."
},
{
"code": null,
"e": 1312,
"s": 1270,
"text": "It is a type that is defined by the user."
},
{
"code": null,
"e": 1364,
"s": 1312,
"text": "It holds its own data members and member functions."
},
{
"code": null,
"e": 1458,
"s": 1364,
"text": "These data members and member functions can be accessed by creating an instance of the class."
},
{
"code": null,
"e": 1586,
"s": 1458,
"text": "They can be used to manipulate the variables and can be used to define property to tell how the objects in a class have to act."
},
{
"code": null,
"e": 1988,
"s": 1586,
"text": "It can be understood as a blueprint for an object.Example: Consider the class of Employees. There may be many attributes such as name of employee, age, date of birth, title, and so on.These are called the data members.The member functions could be 'draw_salary', 'get_promotion', which perform certain actions with respect to class objects.These would be the common properties shared by all employees."
},
{
"code": null,
"e": 2123,
"s": 1988,
"text": "Example: Consider the class of Employees. There may be many attributes such as name of employee, age, date of birth, title, and so on."
},
{
"code": null,
"e": 2158,
"s": 2123,
"text": "These are called the data members."
},
{
"code": null,
"e": 2281,
"s": 2158,
"text": "The member functions could be 'draw_salary', 'get_promotion', which perform certain actions with respect to class objects."
},
{
"code": null,
"e": 2343,
"s": 2281,
"text": "These would be the common properties shared by all employees."
},
{
"code": null,
"e": 2384,
"s": 2343,
"text": "It is defined using the keyword 'class'."
},
{
"code": null,
"e": 2425,
"s": 2384,
"text": "It is followed by the name of the class."
},
{
"code": null,
"e": 2513,
"s": 2425,
"text": "The class body is defined within flower brackets, and is terminated using a semi-colon."
},
{
"code": null,
"e": 2552,
"s": 2513,
"text": "class class_name {\n body_of_class\n};"
},
{
"code": null,
"e": 2589,
"s": 2552,
"text": "An object is an instance of a class."
},
{
"code": null,
"e": 2645,
"s": 2589,
"text": "When a class is defined, memory is not allocated to it."
},
{
"code": null,
"e": 2736,
"s": 2645,
"text": "The moment an object is created, memory gets allocated to all the attributes of the class."
},
{
"code": null,
"e": 2802,
"s": 2736,
"text": "When a class is defined, the specifics of the object are defined."
},
{
"code": null,
"e": 2906,
"s": 2802,
"text": "If that class has to be put to use, and operations need to be performed, an object needs to be created."
},
{
"code": null,
"e": 2970,
"s": 2906,
"text": "The object has to be explicitly created using the below syntax."
},
{
"code": null,
"e": 2994,
"s": 2970,
"text": "class_name object_name;"
},
{
"code": null,
"e": 3312,
"s": 2994,
"text": "The data members and member functions of a class can be accessed by an object with the help of the dot ('.') operator.Example: Assume a class has been created with the required attributes and member functions.Once an object with respect to that class is created, the member functions can be accessed in the below way:"
},
{
"code": null,
"e": 3404,
"s": 3312,
"text": "Example: Assume a class has been created with the required attributes and member functions."
},
{
"code": null,
"e": 3513,
"s": 3404,
"text": "Once an object with respect to that class is created, the member functions can be accessed in the below way:"
},
{
"code": null,
"e": 3543,
"s": 3513,
"text": "object_name.member_function()"
},
{
"code": null,
"e": 3668,
"s": 3543,
"text": "The data members which are public in nature, can be accessed in the same manner, as shown above, i.e using the '.' operator."
},
{
"code": null,
"e": 3738,
"s": 3668,
"text": "Public members are those that are defined using the 'public' keyword."
},
{
"code": null,
"e": 3810,
"s": 3738,
"text": "Private members are those that are defined using the 'private' keyword."
},
{
"code": null,
"e": 3866,
"s": 3810,
"text": "These members can't be accessed directly by the object."
},
{
"code": null,
"e": 3965,
"s": 3866,
"text": "The 'public', 'private' and 'protected' keywords are known as access controls of the data members."
},
{
"code": null,
"e": 4056,
"s": 3965,
"text": "Member functions that are defined inside the class are considered to be inline by default."
},
{
"code": null,
"e": 4281,
"s": 4056,
"text": "The inline functions ae those which are expanded right after the function is defined. They are copied everywhere when the code is compiled (similar to macros). This means that the overhead of calling the function is reduced."
},
{
"code": null,
"e": 4379,
"s": 4281,
"text": "Any non-class function can be made as an inline function by attaching the 'inline' keyword to it."
}
] |
MFC - Checkboxes | A checkbox is a Windows control that allows the user to set or change the value of an item as true or false.
Create
Creates the Windows button control and attaches it to the CButton object.
DrawItem
Override to draw an owner-drawn CButton object.
GetBitmap
Retrieves the handle of the bitmap previously set with SetBitmap.
GetButtonStyle
Retrieves information about the button control style.
GetCheck
Retrieves the check state of a button control.
GetCursor
Retrieves the handle of the cursor image previously set with SetCursor.
GetIcon
Retrieves the handle of the icon previously set with SetIcon.
GetIdealSize
Retrieves the ideal size of the button control.
GetImageList
Retrieves the image list of the button control.
GetNote
Retrieves the note component of the current command link control.
GetNoteLength
Retrieves the length of the note text for the current command link control.
GetSplitGlyph
Retrieves the glyph associated with the current split button control.
GetSplitImageList
Retrieves the image list for the current split button control.
GetSplitInfo
Retrieves information that defines the current split button control.
GetSplitSize
Retrieves the bounding rectangle of the drop-down component of the current split button control.
GetSplitStyle
Retrieves the split button styles that define the current split button control.
GetState
Retrieves the check state, highlight state, and focus state of a button control.
GetTextMargin
Retrieves the text margin of the button control.
SetBitmap
Specifies a bitmap to be displayed on the button.
SetButtonStyle
Changes the style of a button.
SetCheck
Sets the check state of a button control.
SetCursor
Specifies a cursor image to be displayed on the button.
SetDropDownState
Sets the drop-down state of the current split button control.
SetIcon
Specifies an icon to be displayed on the button.
SetImageList
Sets the image list of the button control.
SetNote
Sets the note on the current command link control.
SetSplitGlyph
Associates a specified glyph with the current split button control.
SetSplitImageList
Associates an image list with the current split button control.
SetSplitInfo
Specifies information that defines the current split button control.
SetSplitSize
Sets the bounding rectangle of the drop-down component of the current split button control.
SetSplitStyle
Sets the style of the current split button control.
SetState
Sets the highlighting state of a button control.
SetTextMargin
Sets the text margin of the button control.
Let us create a new MFC dialog based project.
Once the project is created, you will see the following dialog box in designer window.
Step 1 − Delete the TODO line and drag one checkbox and one Edit control as shown in the following snapshot. Also change the caption of checkbox to Enable Control.
Step 2 − Right-click on the checkbox and select Add Variable.
Step 3 − You can select different options on this dialog box. For checkbox, the CButton variable type is selected by default.
Step 4 − Similarly, the control ID is also selected by default. We now need to select Control in the Category combo box, and type m_enableDisableCheck in the Variable Name edit box and click Finish.
Step 5 − Add Control Variable of Edit control with the settings as shown in the following snapshot.
Step 6 − Observe the header file of the dialog class. You can see that these two variables have been added now.
CButton m_enableDisableCheck;
CEdit m_myEditControl;
Step 7 − Right-click on the checkbox and select Add Variable.
Step 8 − Click Finish to continue.
Step 9 − Add value Variable for Edit control with the settings as shown in the following snapshot.
Step 10 − Observe the header file. You can see that the new variables have been added now.
bool m_enableDisableVal;
CString m_editControlVal;
Step 11 − Now we will add event handler for checkbox.
Step 12 − Right-click the control for which you want to handle the notification event.
Step 13 − Select the event in the Message type box to add to the class selected in the Class list box.
Step 14 − Accept the default name in the Function handler name box, or provide a name of your choice.
Step 15 − Click Add and Edit to add the event handler.
Step 16 − You can now see the following event added at the end of CMFCControlManagementDlg.cpp file.
void CMFCControlManagementDlg::OnBnClickedCheck1() {
// TODO: Add your control notification handler code here
}
Step 17 − This enables/disables the edit control when the checkbox is checked/unchecked.
Step 18 − We have now added the checkbox click event handler. Here is the implementation of event handler for checkbox.
void CMFCControlManagementDlg::OnBnClickedCheck1() {
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if (m_enableDisableVal)
m_myEditControl.EnableWindow(TRUE);
else
m_myEditControl.EnableWindow(FALSE);
}
Step 19 − We need to add the following code to CMFCControlManagementDlg::OnInitDialog(). When the dialog is created, it will manage these controls.
UpdateData(TRUE);
if (m_enableDisableVal)
m_myEditControl.EnableWindow(TRUE);
else
m_myEditControl.EnableWindow(FALSE);
Step 20 − Here is the complete implementation of CMFCControlManagementDlg.cpp file.
// MFCControlManagementDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MFCControlManagement.h"
#include "MFCControlManagementDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx {
public:
CAboutDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX) {
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
CMFCControlManagementDlg::CMFCControlManagementDlg(CWnd* pParent /* = NULL*/)
: CDialogEx(IDD_MFCCONTROLMANAGEMENT_DIALOG, pParent),
m_enableDisableVal(FALSE), m_editControlVal(_T("")) {
m_hIcon = AfxGetApp()→LoadIcon(IDR_MAINFRAME);
}
void CMFCControlManagementDlg::DoDataExchange(CDataExchange* pDX) {
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CHECK1, m_enableDisableCheck);
DDX_Control(pDX, IDC_EDIT1, m_myEditControl);
DDX_Check(pDX, IDC_CHECK1, m_enableDisableVal);
DDX_Text(pDX, IDC_EDIT1, m_editControlVal);
}
BEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1)
END_MESSAGE_MAP()
// CMFCControlManagementDlg message handlers
BOOL CMFCControlManagementDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL) {
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty()) {
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
UpdateData(TRUE);
if (m_enableDisableVal)
m_myEditControl.EnableWindow(TRUE);
else
m_myEditControl.EnableWindow(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
void CMFCControlManagementDlg::OnSysCommand(UINT nID, LPARAM lParam) {
if ((nID & 0xFFF0) == IDM_ABOUTBOX) {
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}else {
CDialogEx::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMFCControlManagementDlg::OnPaint() {
if (IsIconic()) {
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND,
reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}else{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMFCControlManagementDlg::OnQueryDragIcon() {
return static_cast<HCURSOR>(m_hIcon);
}
void CMFCControlManagementDlg::OnBnClickedCheck1(){
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if (m_enableDisableVal)
m_myEditControl.EnableWindow(TRUE);
else
m_myEditControl.EnableWindow(FALSE);
}
Step 21 − When the above code is compiled and executed, you will see the following output. You can now see the checkbox is unchecked by default. This disables the edit control.
Step 22 − Now when you check the checkbox, the edit control is enabled.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2176,
"s": 2067,
"text": "A checkbox is a Windows control that allows the user to set or change the value of an item as true or false."
},
{
"code": null,
"e": 2183,
"s": 2176,
"text": "Create"
},
{
"code": null,
"e": 2257,
"s": 2183,
"text": "Creates the Windows button control and attaches it to the CButton object."
},
{
"code": null,
"e": 2266,
"s": 2257,
"text": "DrawItem"
},
{
"code": null,
"e": 2314,
"s": 2266,
"text": "Override to draw an owner-drawn CButton object."
},
{
"code": null,
"e": 2324,
"s": 2314,
"text": "GetBitmap"
},
{
"code": null,
"e": 2390,
"s": 2324,
"text": "Retrieves the handle of the bitmap previously set with SetBitmap."
},
{
"code": null,
"e": 2405,
"s": 2390,
"text": "GetButtonStyle"
},
{
"code": null,
"e": 2459,
"s": 2405,
"text": "Retrieves information about the button control style."
},
{
"code": null,
"e": 2468,
"s": 2459,
"text": "GetCheck"
},
{
"code": null,
"e": 2515,
"s": 2468,
"text": "Retrieves the check state of a button control."
},
{
"code": null,
"e": 2525,
"s": 2515,
"text": "GetCursor"
},
{
"code": null,
"e": 2597,
"s": 2525,
"text": "Retrieves the handle of the cursor image previously set with SetCursor."
},
{
"code": null,
"e": 2605,
"s": 2597,
"text": "GetIcon"
},
{
"code": null,
"e": 2667,
"s": 2605,
"text": "Retrieves the handle of the icon previously set with SetIcon."
},
{
"code": null,
"e": 2680,
"s": 2667,
"text": "GetIdealSize"
},
{
"code": null,
"e": 2728,
"s": 2680,
"text": "Retrieves the ideal size of the button control."
},
{
"code": null,
"e": 2741,
"s": 2728,
"text": "GetImageList"
},
{
"code": null,
"e": 2789,
"s": 2741,
"text": "Retrieves the image list of the button control."
},
{
"code": null,
"e": 2797,
"s": 2789,
"text": "GetNote"
},
{
"code": null,
"e": 2863,
"s": 2797,
"text": "Retrieves the note component of the current command link control."
},
{
"code": null,
"e": 2877,
"s": 2863,
"text": "GetNoteLength"
},
{
"code": null,
"e": 2953,
"s": 2877,
"text": "Retrieves the length of the note text for the current command link control."
},
{
"code": null,
"e": 2967,
"s": 2953,
"text": "GetSplitGlyph"
},
{
"code": null,
"e": 3037,
"s": 2967,
"text": "Retrieves the glyph associated with the current split button control."
},
{
"code": null,
"e": 3055,
"s": 3037,
"text": "GetSplitImageList"
},
{
"code": null,
"e": 3118,
"s": 3055,
"text": "Retrieves the image list for the current split button control."
},
{
"code": null,
"e": 3131,
"s": 3118,
"text": "GetSplitInfo"
},
{
"code": null,
"e": 3200,
"s": 3131,
"text": "Retrieves information that defines the current split button control."
},
{
"code": null,
"e": 3213,
"s": 3200,
"text": "GetSplitSize"
},
{
"code": null,
"e": 3310,
"s": 3213,
"text": "Retrieves the bounding rectangle of the drop-down component of the current split button control."
},
{
"code": null,
"e": 3324,
"s": 3310,
"text": "GetSplitStyle"
},
{
"code": null,
"e": 3404,
"s": 3324,
"text": "Retrieves the split button styles that define the current split button control."
},
{
"code": null,
"e": 3413,
"s": 3404,
"text": "GetState"
},
{
"code": null,
"e": 3494,
"s": 3413,
"text": "Retrieves the check state, highlight state, and focus state of a button control."
},
{
"code": null,
"e": 3508,
"s": 3494,
"text": "GetTextMargin"
},
{
"code": null,
"e": 3557,
"s": 3508,
"text": "Retrieves the text margin of the button control."
},
{
"code": null,
"e": 3567,
"s": 3557,
"text": "SetBitmap"
},
{
"code": null,
"e": 3617,
"s": 3567,
"text": "Specifies a bitmap to be displayed on the button."
},
{
"code": null,
"e": 3632,
"s": 3617,
"text": "SetButtonStyle"
},
{
"code": null,
"e": 3663,
"s": 3632,
"text": "Changes the style of a button."
},
{
"code": null,
"e": 3672,
"s": 3663,
"text": "SetCheck"
},
{
"code": null,
"e": 3714,
"s": 3672,
"text": "Sets the check state of a button control."
},
{
"code": null,
"e": 3724,
"s": 3714,
"text": "SetCursor"
},
{
"code": null,
"e": 3780,
"s": 3724,
"text": "Specifies a cursor image to be displayed on the button."
},
{
"code": null,
"e": 3797,
"s": 3780,
"text": "SetDropDownState"
},
{
"code": null,
"e": 3859,
"s": 3797,
"text": "Sets the drop-down state of the current split button control."
},
{
"code": null,
"e": 3867,
"s": 3859,
"text": "SetIcon"
},
{
"code": null,
"e": 3916,
"s": 3867,
"text": "Specifies an icon to be displayed on the button."
},
{
"code": null,
"e": 3929,
"s": 3916,
"text": "SetImageList"
},
{
"code": null,
"e": 3972,
"s": 3929,
"text": "Sets the image list of the button control."
},
{
"code": null,
"e": 3980,
"s": 3972,
"text": "SetNote"
},
{
"code": null,
"e": 4031,
"s": 3980,
"text": "Sets the note on the current command link control."
},
{
"code": null,
"e": 4045,
"s": 4031,
"text": "SetSplitGlyph"
},
{
"code": null,
"e": 4113,
"s": 4045,
"text": "Associates a specified glyph with the current split button control."
},
{
"code": null,
"e": 4131,
"s": 4113,
"text": "SetSplitImageList"
},
{
"code": null,
"e": 4195,
"s": 4131,
"text": "Associates an image list with the current split button control."
},
{
"code": null,
"e": 4208,
"s": 4195,
"text": "SetSplitInfo"
},
{
"code": null,
"e": 4277,
"s": 4208,
"text": "Specifies information that defines the current split button control."
},
{
"code": null,
"e": 4290,
"s": 4277,
"text": "SetSplitSize"
},
{
"code": null,
"e": 4382,
"s": 4290,
"text": "Sets the bounding rectangle of the drop-down component of the current split button control."
},
{
"code": null,
"e": 4396,
"s": 4382,
"text": "SetSplitStyle"
},
{
"code": null,
"e": 4448,
"s": 4396,
"text": "Sets the style of the current split button control."
},
{
"code": null,
"e": 4457,
"s": 4448,
"text": "SetState"
},
{
"code": null,
"e": 4506,
"s": 4457,
"text": "Sets the highlighting state of a button control."
},
{
"code": null,
"e": 4520,
"s": 4506,
"text": "SetTextMargin"
},
{
"code": null,
"e": 4564,
"s": 4520,
"text": "Sets the text margin of the button control."
},
{
"code": null,
"e": 4610,
"s": 4564,
"text": "Let us create a new MFC dialog based project."
},
{
"code": null,
"e": 4697,
"s": 4610,
"text": "Once the project is created, you will see the following dialog box in designer window."
},
{
"code": null,
"e": 4861,
"s": 4697,
"text": "Step 1 − Delete the TODO line and drag one checkbox and one Edit control as shown in the following snapshot. Also change the caption of checkbox to Enable Control."
},
{
"code": null,
"e": 4923,
"s": 4861,
"text": "Step 2 − Right-click on the checkbox and select Add Variable."
},
{
"code": null,
"e": 5049,
"s": 4923,
"text": "Step 3 − You can select different options on this dialog box. For checkbox, the CButton variable type is selected by default."
},
{
"code": null,
"e": 5248,
"s": 5049,
"text": "Step 4 − Similarly, the control ID is also selected by default. We now need to select Control in the Category combo box, and type m_enableDisableCheck in the Variable Name edit box and click Finish."
},
{
"code": null,
"e": 5348,
"s": 5248,
"text": "Step 5 − Add Control Variable of Edit control with the settings as shown in the following snapshot."
},
{
"code": null,
"e": 5460,
"s": 5348,
"text": "Step 6 − Observe the header file of the dialog class. You can see that these two variables have been added now."
},
{
"code": null,
"e": 5513,
"s": 5460,
"text": "CButton m_enableDisableCheck;\nCEdit m_myEditControl;"
},
{
"code": null,
"e": 5575,
"s": 5513,
"text": "Step 7 − Right-click on the checkbox and select Add Variable."
},
{
"code": null,
"e": 5610,
"s": 5575,
"text": "Step 8 − Click Finish to continue."
},
{
"code": null,
"e": 5709,
"s": 5610,
"text": "Step 9 − Add value Variable for Edit control with the settings as shown in the following snapshot."
},
{
"code": null,
"e": 5800,
"s": 5709,
"text": "Step 10 − Observe the header file. You can see that the new variables have been added now."
},
{
"code": null,
"e": 5851,
"s": 5800,
"text": "bool m_enableDisableVal;\nCString m_editControlVal;"
},
{
"code": null,
"e": 5905,
"s": 5851,
"text": "Step 11 − Now we will add event handler for checkbox."
},
{
"code": null,
"e": 5992,
"s": 5905,
"text": "Step 12 − Right-click the control for which you want to handle the notification event."
},
{
"code": null,
"e": 6095,
"s": 5992,
"text": "Step 13 − Select the event in the Message type box to add to the class selected in the Class list box."
},
{
"code": null,
"e": 6197,
"s": 6095,
"text": "Step 14 − Accept the default name in the Function handler name box, or provide a name of your choice."
},
{
"code": null,
"e": 6252,
"s": 6197,
"text": "Step 15 − Click Add and Edit to add the event handler."
},
{
"code": null,
"e": 6353,
"s": 6252,
"text": "Step 16 − You can now see the following event added at the end of CMFCControlManagementDlg.cpp file."
},
{
"code": null,
"e": 6468,
"s": 6353,
"text": "void CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n}"
},
{
"code": null,
"e": 6557,
"s": 6468,
"text": "Step 17 − This enables/disables the edit control when the checkbox is checked/unchecked."
},
{
"code": null,
"e": 6677,
"s": 6557,
"text": "Step 18 − We have now added the checkbox click event handler. Here is the implementation of event handler for checkbox."
},
{
"code": null,
"e": 6933,
"s": 6677,
"text": "void CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n}"
},
{
"code": null,
"e": 7081,
"s": 6933,
"text": "Step 19 − We need to add the following code to CMFCControlManagementDlg::OnInitDialog(). When the dialog is created, it will manage these controls."
},
{
"code": null,
"e": 7207,
"s": 7081,
"text": "UpdateData(TRUE);\nif (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\nelse\n m_myEditControl.EnableWindow(FALSE);"
},
{
"code": null,
"e": 7291,
"s": 7207,
"text": "Step 20 − Here is the complete implementation of CMFCControlManagementDlg.cpp file."
},
{
"code": null,
"e": 11515,
"s": 7291,
"text": "// MFCControlManagementDlg.cpp : implementation file\n//\n\n#include \"stdafx.h\"\n#include \"MFCControlManagement.h\"\n#include \"MFCControlManagementDlg.h\"\n#include \"afxdialogex.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n// CAboutDlg dialog used for App About\n\nclass CAboutDlg : public CDialogEx {\n public:\n CAboutDlg();\n\n // Dialog Data\n #ifdef AFX_DESIGN_TIME\n enum { IDD = IDD_ABOUTBOX };\n #endif\n\n protected:\n virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n\t\n // Implementation\n protected:\n DECLARE_MESSAGE_MAP()\n};\n\nCAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {\n\n}\n\nvoid CAboutDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n}\n\nBEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)\nEND_MESSAGE_MAP()\nCMFCControlManagementDlg::CMFCControlManagementDlg(CWnd* pParent /* = NULL*/)\n : CDialogEx(IDD_MFCCONTROLMANAGEMENT_DIALOG, pParent), \n m_enableDisableVal(FALSE), m_editControlVal(_T(\"\")) {\n \n m_hIcon = AfxGetApp()→LoadIcon(IDR_MAINFRAME);\n}\nvoid CMFCControlManagementDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n DDX_Control(pDX, IDC_CHECK1, m_enableDisableCheck);\n DDX_Control(pDX, IDC_EDIT1, m_myEditControl);\n DDX_Check(pDX, IDC_CHECK1, m_enableDisableVal);\n DDX_Text(pDX, IDC_EDIT1, m_editControlVal);\n}\n\nBEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx)\n ON_WM_SYSCOMMAND()\n ON_WM_PAINT()\n ON_WM_QUERYDRAGICON()\n ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1)\nEND_MESSAGE_MAP()\n\n\n// CMFCControlManagementDlg message handlers\n\nBOOL CMFCControlManagementDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\t\n // Add \"About...\" menu item to system menu.\n\t\n // IDM_ABOUTBOX must be in the system command range.\n ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n ASSERT(IDM_ABOUTBOX < 0xF000);\n\t\n CMenu* pSysMenu = GetSystemMenu(FALSE);\n if (pSysMenu != NULL) {\n BOOL bNameValid;\n CString strAboutMenu;\n bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n ASSERT(bNameValid);\n if (!strAboutMenu.IsEmpty()) {\n pSysMenu->AppendMenu(MF_SEPARATOR);\n pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n }\n }\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}\n\nvoid CMFCControlManagementDlg::OnSysCommand(UINT nID, LPARAM lParam) {\n if ((nID & 0xFFF0) == IDM_ABOUTBOX) {\n CAboutDlg dlgAbout;\n dlgAbout.DoModal(); \n }else {\n CDialogEx::OnSysCommand(nID, lParam);\n }\n}\n \n// If you add a minimize button to your dialog, you will need the code below\n// to draw the icon. For MFC applications using the document/view model,\n// this is automatically done for you by the framework.\n\nvoid CMFCControlManagementDlg::OnPaint() {\n if (IsIconic()) {\n CPaintDC dc(this); // device context for painting\n\n SendMessage(WM_ICONERASEBKGND,\n reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);\n\t\t\t\n // Center icon in client rectangle\n int cxIcon = GetSystemMetrics(SM_CXICON);\n int cyIcon = GetSystemMetrics(SM_CYICON);\n CRect rect;\n GetClientRect(&rect);\n int x = (rect.Width() - cxIcon + 1) / 2;\n int y = (rect.Height() - cyIcon + 1) / 2;\n\n // Draw the icon\n dc.DrawIcon(x, y, m_hIcon);\n }else{\n CDialogEx::OnPaint();\n }\n}\n\n// The system calls this function to obtain the cursor to display while the user drags\n// the minimized window.\nHCURSOR CMFCControlManagementDlg::OnQueryDragIcon() {\n return static_cast<HCURSOR>(m_hIcon);\n}\nvoid CMFCControlManagementDlg::OnBnClickedCheck1(){\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n}"
},
{
"code": null,
"e": 11692,
"s": 11515,
"text": "Step 21 − When the above code is compiled and executed, you will see the following output. You can now see the checkbox is unchecked by default. This disables the edit control."
},
{
"code": null,
"e": 11764,
"s": 11692,
"text": "Step 22 − Now when you check the checkbox, the edit control is enabled."
},
{
"code": null,
"e": 11771,
"s": 11764,
"text": " Print"
},
{
"code": null,
"e": 11782,
"s": 11771,
"text": " Add Notes"
}
] |
How to delete elements from an array? | To delete an element at a particular position from an array. Starting from the required position, replace the element in the current position with the element in the next position.
Live Demo
public class DeletingElementsBySwapping {
public static void main(String args[]) {
int [] myArray = {23, 93, 56, 92, 39};
System.out.println("hello");
int size = myArray.length;
int pos = 2;
for (int i = pos; i<size-1; i++) {
myArray[i] = myArray[i+1];
}
for (int i=0; i<size-1; i++) {
System.out.println(myArray[i]);
}
}
}
hello
23
93
92
39
Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project.
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
This package provides a class known as ArrayUtils. Using the remove()method of this class instead of swapping elements, you can delete them.
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class DeletingElements {
public static void main(String args[]) {
int [] myArray = {23, 93, 56, 92, 39};
int [] result = ArrayUtils.remove(myArray, 2);
System.out.println(Arrays.toString(result));
}
}
[23, 93, 92, 39] | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "To delete an element at a particular position from an array. Starting from the required position, replace the element in the current position with the element in the next position."
},
{
"code": null,
"e": 1254,
"s": 1243,
"text": " Live Demo"
},
{
"code": null,
"e": 1581,
"s": 1254,
"text": "public class DeletingElementsBySwapping {\npublic static void main(String args[]) {\nint [] myArray = {23, 93, 56, 92, 39};\nSystem.out.println(\"hello\");\n\nint size = myArray.length;\nint pos = 2;\n\nfor (int i = pos; i<size-1; i++) {\nmyArray[i] = myArray[i+1];\n}\n\nfor (int i=0; i<size-1; i++) {\nSystem.out.println(myArray[i]);\n}\n}\n}"
},
{
"code": null,
"e": 1599,
"s": 1581,
"text": "hello\n23\n93\n92\n39"
},
{
"code": null,
"e": 1739,
"s": 1599,
"text": "Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project."
},
{
"code": null,
"e": 1897,
"s": 1739,
"text": "<dependencies>\n<dependency>\n<groupId>org.apache.commons</groupId>\n<artifactId>commons-lang3</artifactId>\n<version>3.0</version>\n</dependency>\n</dependencies>"
},
{
"code": null,
"e": 2038,
"s": 1897,
"text": "This package provides a class known as ArrayUtils. Using the remove()method of this class instead of swapping elements, you can delete them."
},
{
"code": null,
"e": 2316,
"s": 2038,
"text": "import java.util.Arrays;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class DeletingElements {\npublic static void main(String args[]) {\nint [] myArray = {23, 93, 56, 92, 39};\nint [] result = ArrayUtils.remove(myArray, 2);\nSystem.out.println(Arrays.toString(result));\n}\n}"
},
{
"code": null,
"e": 2333,
"s": 2316,
"text": "[23, 93, 92, 39]"
}
] |
async.queue() Method in Node.js | The async module provides different functionalities to work with asynchronous JavaScript in a nodejs application. The async.queue() method returns a queue that is further used for concurrent processing of processes i.e. multiple processing of items at a time/instant.
Step 1 − Run the following command to initialize the node package manager.
npm init
Step 2 − Installing the async module using the following command.
npm install --save async
Step 3 − Importing the async module using the below statement in your programs .
const async = require('async')
async.queue('function', 'concurrency value')
The above parameters are described as below −
function – This parameter defines the function that will be executed over the element added to the queue.
function – This parameter defines the function that will be executed over the element added to the queue.
concurrency value – This field defines the number of elements to be processed at a time.
concurrency value – This field defines the number of elements to be processed at a time.
The async.queue() method further has multiple methods and properties that will be used while processing async requests.
push(element, callback) - Similar to an ordinary queue, the push method is used for adding an element at the tail of a queue.
push(element, callback) - Similar to an ordinary queue, the push method is used for adding an element at the tail of a queue.
queue.push(item, callback);
length() - The length method is used for returning the number of elements present in a queue at a time.
length() - The length method is used for returning the number of elements present in a queue at a time.
queue.length()
started property - This property returns a boolean value providing information about the queue whether it has started processing its elements or not.
started property - This property returns a boolean value providing information about the queue whether it has started processing its elements or not.
queue.started()
unshift(element, callback) - The unshift property also adds an element to the queue like a push() method. The only difference between the two is – It adds elements at the head whereas push adds it in the tail. This method is used for priority elements.
unshift(element, callback) - The unshift property also adds an element to the queue like a push() method. The only difference between the two is – It adds elements at the head whereas push adds it in the tail. This method is used for priority elements.
queue.unshift(item, callback)
drain() Method - This method issues a callback when the queue has executed all the tasks/elements. It only works when the function is described in an arrow function.
drain() Method - This method issues a callback when the queue has executed all the tasks/elements. It only works when the function is described in an arrow function.
queue.drain(() => {
console.log(“All Tasks are completely executed...”);
}
pause() Method This method holds the execution of remaining elements in the queue. The function will continue after resume() is called.
pause() Method This method holds the execution of remaining elements in the queue. The function will continue after resume() is called.
queue.pause()
resume() Method - This method is used for resuming the execution of elements which were put on hold using the pause() method.
resume() Method - This method is used for resuming the execution of elements which were put on hold using the pause() method.
queue.resume()
kill() Method - This method removes all the remaining elements from the queue and forces it into an idle state.
kill() Method - This method removes all the remaining elements from the queue and forces it into an idle state.
queue.kill()
idle() Method - This method returns a boolean state indicating if the queue is idle or processing something.
idle() Method - This method returns a boolean state indicating if the queue is idle or processing something.
queue.idle
Let's take a look at one example to understand the above concepts better −
// Including the async module
const async = require('async');
// Creating an array for all elements execution
const tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Initializing the queue
const queue = async.queue((task, executed) => {
console.log("Currently Busy Processing Task " + task);
setTimeout(()=>{
// Number of tasks remaining and to be processed
const tasksRemaining = queue.length();
executed(null, {task, tasksRemaining});
}, 1000);
}, 1); // concurrency value = 1
// Queue is idle initially as no elements are there...
console.log(`Queue Started ? ${queue.started}`)
// Adding each task from the tasks list
tasks.forEach((task)=>{
// Adding the task 5 to the head for priority execution
if(task == 5){
queue.unshift(task, (error, {task, tasksRemaining})=>{
if(error){
console.log(`An error occurred while processing task ${task}`);
}else {
console.log(`Finished processing task ${task}. ${tasksRemaining} tasks remaining`);
}
})
// Adding all the tasks at tail to be executed except task 5
} else {
queue.push(task, (error, {task, tasksRemaining})=>{
if(error){
console.log(`An error occurred while processing task ${task}`);
}else {
console.log(`Finished processing task ${task}. ${tasksRemaining}
tasks remaining`);
}
})
}
});
// Executes the callback when the queue is done processing all the tasks
queue.drain(() => {
console.log('All items are succesfully processed !');
})
// Checking if the queue is started after adding tasks
console.log(`Queue Started ? ${queue.started}`)
C:\home\node>> node asyncQueue.js
Queue Started ? False
Queue Started ? True
Currently Busy Processing Task 5
Finished processing task 5. 9 tasks remaining
Currently Busy Processing Task 1
Finished processing task 1. 8 tasks remaining
Currently Busy Processing Task 2
Finished processing task 2. 7 tasks remaining
Currently Busy Processing Task 3
Finished processing task 3. 6 tasks remaining
Currently Busy Processing Task 4
Finished processing task 4. 5 tasks remaining
Currently Busy Processing Task 6
Finished processing task 6. 4 tasks remaining
Currently Busy Processing Task 7
Finished processing task 7. 3 tasks remaining
Currently Busy Processing Task 8
Finished processing task 8. 2 tasks remaining
Currently Busy Processing Task 9
Finished processing task 9. 1 tasks remaining
Currently Busy Processing Task 10
Finished processing task 10. 0 tasks remaining
All items are succesfully processed ! | [
{
"code": null,
"e": 1330,
"s": 1062,
"text": "The async module provides different functionalities to work with asynchronous JavaScript in a nodejs application. The async.queue() method returns a queue that is further used for concurrent processing of processes i.e. multiple processing of items at a time/instant."
},
{
"code": null,
"e": 1405,
"s": 1330,
"text": "Step 1 − Run the following command to initialize the node package manager."
},
{
"code": null,
"e": 1414,
"s": 1405,
"text": "npm init"
},
{
"code": null,
"e": 1480,
"s": 1414,
"text": "Step 2 − Installing the async module using the following command."
},
{
"code": null,
"e": 1505,
"s": 1480,
"text": "npm install --save async"
},
{
"code": null,
"e": 1586,
"s": 1505,
"text": "Step 3 − Importing the async module using the below statement in your programs ."
},
{
"code": null,
"e": 1617,
"s": 1586,
"text": "const async = require('async')"
},
{
"code": null,
"e": 1662,
"s": 1617,
"text": "async.queue('function', 'concurrency value')"
},
{
"code": null,
"e": 1708,
"s": 1662,
"text": "The above parameters are described as below −"
},
{
"code": null,
"e": 1814,
"s": 1708,
"text": "function – This parameter defines the function that will be executed over the element added to the queue."
},
{
"code": null,
"e": 1920,
"s": 1814,
"text": "function – This parameter defines the function that will be executed over the element added to the queue."
},
{
"code": null,
"e": 2009,
"s": 1920,
"text": "concurrency value – This field defines the number of elements to be processed at a time."
},
{
"code": null,
"e": 2098,
"s": 2009,
"text": "concurrency value – This field defines the number of elements to be processed at a time."
},
{
"code": null,
"e": 2218,
"s": 2098,
"text": "The async.queue() method further has multiple methods and properties that will be used while processing async requests."
},
{
"code": null,
"e": 2344,
"s": 2218,
"text": "push(element, callback) - Similar to an ordinary queue, the push method is used for adding an element at the tail of a queue."
},
{
"code": null,
"e": 2470,
"s": 2344,
"text": "push(element, callback) - Similar to an ordinary queue, the push method is used for adding an element at the tail of a queue."
},
{
"code": null,
"e": 2498,
"s": 2470,
"text": "queue.push(item, callback);"
},
{
"code": null,
"e": 2602,
"s": 2498,
"text": "length() - The length method is used for returning the number of elements present in a queue at a time."
},
{
"code": null,
"e": 2706,
"s": 2602,
"text": "length() - The length method is used for returning the number of elements present in a queue at a time."
},
{
"code": null,
"e": 2721,
"s": 2706,
"text": "queue.length()"
},
{
"code": null,
"e": 2871,
"s": 2721,
"text": "started property - This property returns a boolean value providing information about the queue whether it has started processing its elements or not."
},
{
"code": null,
"e": 3021,
"s": 2871,
"text": "started property - This property returns a boolean value providing information about the queue whether it has started processing its elements or not."
},
{
"code": null,
"e": 3037,
"s": 3021,
"text": "queue.started()"
},
{
"code": null,
"e": 3290,
"s": 3037,
"text": "unshift(element, callback) - The unshift property also adds an element to the queue like a push() method. The only difference between the two is – It adds elements at the head whereas push adds it in the tail. This method is used for priority elements."
},
{
"code": null,
"e": 3543,
"s": 3290,
"text": "unshift(element, callback) - The unshift property also adds an element to the queue like a push() method. The only difference between the two is – It adds elements at the head whereas push adds it in the tail. This method is used for priority elements."
},
{
"code": null,
"e": 3573,
"s": 3543,
"text": "queue.unshift(item, callback)"
},
{
"code": null,
"e": 3739,
"s": 3573,
"text": "drain() Method - This method issues a callback when the queue has executed all the tasks/elements. It only works when the function is described in an arrow function."
},
{
"code": null,
"e": 3905,
"s": 3739,
"text": "drain() Method - This method issues a callback when the queue has executed all the tasks/elements. It only works when the function is described in an arrow function."
},
{
"code": null,
"e": 3983,
"s": 3905,
"text": "queue.drain(() => {\n console.log(“All Tasks are completely executed...”);\n}"
},
{
"code": null,
"e": 4120,
"s": 3983,
"text": "pause() Method This method holds the execution of remaining elements in the queue. The function will continue after resume() is called."
},
{
"code": null,
"e": 4257,
"s": 4120,
"text": "pause() Method This method holds the execution of remaining elements in the queue. The function will continue after resume() is called."
},
{
"code": null,
"e": 4271,
"s": 4257,
"text": "queue.pause()"
},
{
"code": null,
"e": 4397,
"s": 4271,
"text": "resume() Method - This method is used for resuming the execution of elements which were put on hold using the pause() method."
},
{
"code": null,
"e": 4523,
"s": 4397,
"text": "resume() Method - This method is used for resuming the execution of elements which were put on hold using the pause() method."
},
{
"code": null,
"e": 4538,
"s": 4523,
"text": "queue.resume()"
},
{
"code": null,
"e": 4650,
"s": 4538,
"text": "kill() Method - This method removes all the remaining elements from the queue and forces it into an idle state."
},
{
"code": null,
"e": 4762,
"s": 4650,
"text": "kill() Method - This method removes all the remaining elements from the queue and forces it into an idle state."
},
{
"code": null,
"e": 4775,
"s": 4762,
"text": "queue.kill()"
},
{
"code": null,
"e": 4884,
"s": 4775,
"text": "idle() Method - This method returns a boolean state indicating if the queue is idle or processing something."
},
{
"code": null,
"e": 4993,
"s": 4884,
"text": "idle() Method - This method returns a boolean state indicating if the queue is idle or processing something."
},
{
"code": null,
"e": 5004,
"s": 4993,
"text": "queue.idle"
},
{
"code": null,
"e": 5079,
"s": 5004,
"text": "Let's take a look at one example to understand the above concepts better −"
},
{
"code": null,
"e": 6765,
"s": 5079,
"text": "// Including the async module\nconst async = require('async');\n\n// Creating an array for all elements execution\nconst tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n// Initializing the queue\nconst queue = async.queue((task, executed) => {\n console.log(\"Currently Busy Processing Task \" + task);\n\n setTimeout(()=>{\n // Number of tasks remaining and to be processed\n const tasksRemaining = queue.length();\n executed(null, {task, tasksRemaining});\n }, 1000);\n\n}, 1); // concurrency value = 1\n\n// Queue is idle initially as no elements are there...\nconsole.log(`Queue Started ? ${queue.started}`)\n\n// Adding each task from the tasks list\ntasks.forEach((task)=>{\n\n // Adding the task 5 to the head for priority execution\n if(task == 5){\n queue.unshift(task, (error, {task, tasksRemaining})=>{\n if(error){\n console.log(`An error occurred while processing task ${task}`);\n }else {\n console.log(`Finished processing task ${task}. ${tasksRemaining} tasks remaining`);\n }\n })\n // Adding all the tasks at tail to be executed except task 5\n } else {\n queue.push(task, (error, {task, tasksRemaining})=>{\n if(error){\n console.log(`An error occurred while processing task ${task}`);\n }else {\n console.log(`Finished processing task ${task}. ${tasksRemaining}\n tasks remaining`);\n }\n })\n }\n});\n\n// Executes the callback when the queue is done processing all the tasks\nqueue.drain(() => {\n console.log('All items are succesfully processed !');\n})\n\n// Checking if the queue is started after adding tasks\nconsole.log(`Queue Started ? ${queue.started}`)"
},
{
"code": null,
"e": 7672,
"s": 6765,
"text": "C:\\home\\node>> node asyncQueue.js\nQueue Started ? False\nQueue Started ? True\nCurrently Busy Processing Task 5\nFinished processing task 5. 9 tasks remaining\nCurrently Busy Processing Task 1\nFinished processing task 1. 8 tasks remaining\nCurrently Busy Processing Task 2\nFinished processing task 2. 7 tasks remaining\nCurrently Busy Processing Task 3\nFinished processing task 3. 6 tasks remaining\nCurrently Busy Processing Task 4\nFinished processing task 4. 5 tasks remaining\nCurrently Busy Processing Task 6\nFinished processing task 6. 4 tasks remaining\nCurrently Busy Processing Task 7\nFinished processing task 7. 3 tasks remaining\nCurrently Busy Processing Task 8\nFinished processing task 8. 2 tasks remaining\nCurrently Busy Processing Task 9\nFinished processing task 9. 1 tasks remaining\nCurrently Busy Processing Task 10\nFinished processing task 10. 0 tasks remaining\nAll items are succesfully processed !"
}
] |
Diagonal product of a matrix - JavaScript | Suppose, we have a 2-D array representing a square matrix like this −
const arr = [
[1, 3, 4, 2],
[4, 5, 3, 5],
[5, 2, 6, 4],
[8, 2, 9, 3]
];
We are required to write a function that takes in this array and returns the product of the element present at the principal Diagonal of the matrix.
For this array the elements present at the principal diagonal are −
1, 5, 6, 3
Hence the output should be −
90
Following is the code −
const arr = [
[1, 3, 4, 2],
[4, 5, 3, 5],
[5, 2, 6, 4],
[8, 2, 9, 3]
];
const diagonalProduct = arr => {
let product = 1;
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr[i].length; j++){
if(i === j){
product *= arr[i][j];
};
};
};
return product;
};
console.log(diagonalProduct(arr));
Following is the output in the console −
90 | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "Suppose, we have a 2-D array representing a square matrix like this −"
},
{
"code": null,
"e": 1216,
"s": 1132,
"text": "const arr = [\n [1, 3, 4, 2],\n [4, 5, 3, 5],\n [5, 2, 6, 4],\n [8, 2, 9, 3]\n];"
},
{
"code": null,
"e": 1365,
"s": 1216,
"text": "We are required to write a function that takes in this array and returns the product of the element present at the principal Diagonal of the matrix."
},
{
"code": null,
"e": 1433,
"s": 1365,
"text": "For this array the elements present at the principal diagonal are −"
},
{
"code": null,
"e": 1444,
"s": 1433,
"text": "1, 5, 6, 3"
},
{
"code": null,
"e": 1473,
"s": 1444,
"text": "Hence the output should be −"
},
{
"code": null,
"e": 1476,
"s": 1473,
"text": "90"
},
{
"code": null,
"e": 1500,
"s": 1476,
"text": "Following is the code −"
},
{
"code": null,
"e": 1863,
"s": 1500,
"text": "const arr = [\n [1, 3, 4, 2],\n [4, 5, 3, 5],\n [5, 2, 6, 4],\n [8, 2, 9, 3]\n];\nconst diagonalProduct = arr => {\n let product = 1;\n for(let i = 0; i < arr.length; i++){\n for(let j = 0; j < arr[i].length; j++){\n if(i === j){\n product *= arr[i][j];\n };\n };\n };\n return product;\n};\nconsole.log(diagonalProduct(arr));"
},
{
"code": null,
"e": 1904,
"s": 1863,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1907,
"s": 1904,
"text": "90"
}
] |
C++ Program to Check Whether an Undirected Graph Contains a Eulerian Cycle | To know about Euler Circuit, we have the idea about Euler Path. The Euler path is a path; by which we can visit every node exactly once. We can use the same edges for multiple times. The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is also connected with the ending vertex of that path.
To detect the circuit, we have to follow these conditions:
The graph must be connected.
Now when no vertices of an undirected graph have odd degree, then it is a Euler Circuit.
The graph has Euler Circuit.
Input The start node u and the visited node to mark which node is visited.
Output Traverse all connected vertices.
Begin
mark u as visited
for all vertex v, if it is adjacent with u, do
if v is not visited, then
traverse(v, visited)
done
End
Input : The graph.
Output : True if the graph is connected.
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End
Input The given Graph.
Output Returns 0, when no Eulerian Circuit, and returns 1 when it has Euler circuit..
Begin
if isConnected() is false, then
return false
define list of degree for each node
oddDegree := 0
for all vertex i in the graph, do
for all vertex j which are connected with i, do
increase degree
done
if degree of vertex i is odd, then
increase oddDegree
done
if oddDegree is 0, then
return 1
else return 0
End
#include<iostream>
#include<vector>
#define NODE 5
using namespace std;
/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{0, 0, 0, 1, 0}};*/ //No Euler circuit, but euler path is present
int graph[NODE][NODE] = {{0, 1, 1, 1, 1},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{1, 0, 0, 1, 0}}; //uncomment to check Euler Circuit as well as path
/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 0, 0},
{1, 1, 0, 0, 1},
{0, 0, 0, 1, 0}};*/ //Uncomment to check Non Eulerian Graph
void traverse(int u, bool visited[]) {
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) {
if(!visited[v]) traverse(v, visited);
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i<NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i<NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int hasEulerianCircuit() {
if(isConnected() == false) //when graph is not connected
return 0;
vector<int> degree(NODE, 0);
int oddDegree = 0;
for(int i = 0; i<NODE; i++) {
for(int j = 0; j<NODE; j++) {
if(graph[i][j])
degree[i]++; //increase degree, when connected edge found
}
if(degree[i] % 2 != 0) //when degree of vertices are odd
oddDegree++; //count odd degree vertices
}
if(oddDegree == 0) { //when oddDegree is 0, it is Euler circuit
return 1;
}
return 0;
}
int main() {
if(hasEulerianCircuit()) {
cout << "The graph has Eulerian Circuit." << endl;
} else {
cout << "The graph has No Eulerian Circuit." << endl;
}
}
The graph has Eulerian Circuit. | [
{
"code": null,
"e": 1394,
"s": 1062,
"text": "To know about Euler Circuit, we have the idea about Euler Path. The Euler path is a path; by which we can visit every node exactly once. We can use the same edges for multiple times. The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is also connected with the ending vertex of that path."
},
{
"code": null,
"e": 1453,
"s": 1394,
"text": "To detect the circuit, we have to follow these conditions:"
},
{
"code": null,
"e": 1482,
"s": 1453,
"text": "The graph must be connected."
},
{
"code": null,
"e": 1571,
"s": 1482,
"text": "Now when no vertices of an undirected graph have odd degree, then it is a Euler Circuit."
},
{
"code": null,
"e": 1600,
"s": 1571,
"text": "The graph has Euler Circuit."
},
{
"code": null,
"e": 1675,
"s": 1600,
"text": "Input The start node u and the visited node to mark which node is visited."
},
{
"code": null,
"e": 1715,
"s": 1675,
"text": "Output Traverse all connected vertices."
},
{
"code": null,
"e": 1869,
"s": 1715,
"text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd"
},
{
"code": null,
"e": 1888,
"s": 1869,
"text": "Input : The graph."
},
{
"code": null,
"e": 1929,
"s": 1888,
"text": "Output : True if the graph is connected."
},
{
"code": null,
"e": 2161,
"s": 1929,
"text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd"
},
{
"code": null,
"e": 2184,
"s": 2161,
"text": "Input The given Graph."
},
{
"code": null,
"e": 2270,
"s": 2184,
"text": "Output Returns 0, when no Eulerian Circuit, and returns 1 when it has Euler circuit.."
},
{
"code": null,
"e": 2657,
"s": 2270,
"text": "Begin\n if isConnected() is false, then\n return false\n define list of degree for each node\n oddDegree := 0\n for all vertex i in the graph, do\n for all vertex j which are connected with i, do\n increase degree\n done\n if degree of vertex i is odd, then\n increase oddDegree\n done\n if oddDegree is 0, then\n return 1\n else return 0\nEnd"
},
{
"code": null,
"e": 4645,
"s": 2657,
"text": "#include<iostream>\n#include<vector>\n#define NODE 5\nusing namespace std;\n/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},\n {1, 0, 1, 0, 0},\n {1, 1, 0, 0, 0},\n {1, 0, 0, 0, 1},\n {0, 0, 0, 1, 0}};*/ //No Euler circuit, but euler path is present\nint graph[NODE][NODE] = {{0, 1, 1, 1, 1},\n {1, 0, 1, 0, 0},\n {1, 1, 0, 0, 0},\n {1, 0, 0, 0, 1},\n {1, 0, 0, 1, 0}}; //uncomment to check Euler Circuit as well as path\n/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},\n {1, 0, 1, 1, 0},\n {1, 1, 0, 0, 0},\n {1, 1, 0, 0, 1},\n {0, 0, 0, 1, 0}};*/ //Uncomment to check Non Eulerian Graph\nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v]) traverse(v, visited);\n }\n }\n}\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n traverse(u, vis);\n for(int i = 0; i<NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\nint hasEulerianCircuit() {\n if(isConnected() == false) //when graph is not connected\n return 0;\n vector<int> degree(NODE, 0);\n int oddDegree = 0;\n for(int i = 0; i<NODE; i++) {\n for(int j = 0; j<NODE; j++) {\n if(graph[i][j])\n degree[i]++; //increase degree, when connected edge found\n }\n if(degree[i] % 2 != 0) //when degree of vertices are odd\n oddDegree++; //count odd degree vertices\n }\n if(oddDegree == 0) { //when oddDegree is 0, it is Euler circuit\n return 1;\n }\n return 0;\n}\nint main() {\n if(hasEulerianCircuit()) {\n cout << \"The graph has Eulerian Circuit.\" << endl;\n } else {\n cout << \"The graph has No Eulerian Circuit.\" << endl;\n }\n}"
},
{
"code": null,
"e": 4677,
"s": 4645,
"text": "The graph has Eulerian Circuit."
}
] |
C - Header Files | A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler.
Including a header file is equal to copying the content of the header file but we do not do it because it will be error-prone and it is not a good idea to copy the content of a header file in the source files, especially if we have multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global variables, and function prototypes in the header files and include that header file wherever it is required.
Both the user and the system header files are included using the preprocessing directive #include. It has the following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of system directories. You can prepend directories to this list with the -I option while compiling your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. You can prepend directories to this list with the -I option while compiling your source code.
The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current source file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the #include directive. For example, if you have a header file header.h as follows −
char *test (void);
and a main program called program.c that uses the header file, like this −
int x;
#include "header.h"
int main (void) {
puts (test ());
}
the compiler will see the same token stream as it would if program.c read.
int x;
char *test (void);
int main (void) {
puts (test ());
}
If a header file happens to be included twice, the compiler will process its contents twice and it will result in an error. The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this −
#ifndef HEADER_FILE
#define HEADER_FILE
the entire header file file
#endif
This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice.
Sometimes it is necessary to select one of the several different header files to be included into your program. For instance, they might specify configuration parameters to be used on different sorts of operating systems. You could do this with a series of conditionals as follows −
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif
But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for the header name. This is called a computed include. Instead of writing a header name as the direct argument of #include, you simply put a macro name there −
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H
SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D option.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2349,
"s": 2084,
"text": "A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler."
},
{
"code": null,
"e": 2550,
"s": 2349,
"text": "You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler."
},
{
"code": null,
"e": 2818,
"s": 2550,
"text": "Including a header file is equal to copying the content of the header file but we do not do it because it will be error-prone and it is not a good idea to copy the content of a header file in the source files, especially if we have multiple source files in a program."
},
{
"code": null,
"e": 3028,
"s": 2818,
"text": "A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global variables, and function prototypes in the header files and include that header file wherever it is required."
},
{
"code": null,
"e": 3160,
"s": 3028,
"text": "Both the user and the system header files are included using the preprocessing directive #include. It has the following two forms −"
},
{
"code": null,
"e": 3177,
"s": 3160,
"text": "#include <file>\n"
},
{
"code": null,
"e": 3392,
"s": 3177,
"text": "This form is used for system header files. It searches for a file named 'file' in a standard list of system directories. You can prepend directories to this list with the -I option while compiling your source code."
},
{
"code": null,
"e": 3409,
"s": 3392,
"text": "#include \"file\"\n"
},
{
"code": null,
"e": 3641,
"s": 3409,
"text": "This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. You can prepend directories to this list with the -I option while compiling your source code."
},
{
"code": null,
"e": 4066,
"s": 3641,
"text": "The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current source file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the #include directive. For example, if you have a header file header.h as follows −"
},
{
"code": null,
"e": 4086,
"s": 4066,
"text": "char *test (void);\n"
},
{
"code": null,
"e": 4161,
"s": 4086,
"text": "and a main program called program.c that uses the header file, like this −"
},
{
"code": null,
"e": 4228,
"s": 4161,
"text": "int x;\n#include \"header.h\"\n\nint main (void) {\n puts (test ());\n}"
},
{
"code": null,
"e": 4303,
"s": 4228,
"text": "the compiler will see the same token stream as it would if program.c read."
},
{
"code": null,
"e": 4369,
"s": 4303,
"text": "int x;\nchar *test (void);\n\nint main (void) {\n puts (test ());\n}"
},
{
"code": null,
"e": 4607,
"s": 4369,
"text": "If a header file happens to be included twice, the compiler will process its contents twice and it will result in an error. The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this −"
},
{
"code": null,
"e": 4684,
"s": 4607,
"text": "#ifndef HEADER_FILE\n#define HEADER_FILE\n\nthe entire header file file\n\n#endif"
},
{
"code": null,
"e": 4942,
"s": 4684,
"text": "This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice."
},
{
"code": null,
"e": 5225,
"s": 4942,
"text": "Sometimes it is necessary to select one of the several different header files to be included into your program. For instance, they might specify configuration parameters to be used on different sorts of operating systems. You could do this with a series of conditionals as follows −"
},
{
"code": null,
"e": 5334,
"s": 5225,
"text": "#if SYSTEM_1\n # include \"system_1.h\"\n#elif SYSTEM_2\n # include \"system_2.h\"\n#elif SYSTEM_3\n ...\n#endif"
},
{
"code": null,
"e": 5591,
"s": 5334,
"text": "But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for the header name. This is called a computed include. Instead of writing a header name as the direct argument of #include, you simply put a macro name there −"
},
{
"code": null,
"e": 5644,
"s": 5591,
"text": "#define SYSTEM_H \"system_1.h\"\n...\n#include SYSTEM_H\n"
},
{
"code": null,
"e": 5835,
"s": 5644,
"text": "SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D option."
},
{
"code": null,
"e": 5842,
"s": 5835,
"text": " Print"
},
{
"code": null,
"e": 5853,
"s": 5842,
"text": " Add Notes"
}
] |
Minimum number of deletions and insertions. | Practice | GeeksforGeeks | Given two strings str1 and str2. The task is to remove or insert the minimum number of characters from/in str1 so as to transform it into str2. It could be possible that the same character needs to be removed/deleted from one point of str1 and inserted to some another point.
Example 1:
Input: str1 = "heap", str2 = "pea"
Output: 3
Explanation: 2 deletions and 1 insertion
p and h deleted from heap. Then, p is
inserted at the beginning One thing to
note, though p was required yet it was
removed/deleted first from its position
and then it is inserted to some other
position. Thus, p contributes one to the
deletion_count and one to the
insertion_count.
Example 2:
Input : str1 = "geeksforgeeks"
str2 = "geeks"
Output: 8
Explanation: 8 deletions
Your Task:
You don't need to read or print anything. Your task is to complete the function minOperations() which takes both strings as input parameter and returns the minimum number of operation required.
Expected Time Complexity: O(|str1|*|str2|)
Expected Space Complexity: O(|str1|*|str2|)
Constraints:
1 ≤ |str1|, |str2| ≤ 1000
All the characters are lower case English alphabets
0
apurvkumarak2 days ago
C++ Solution
class Solution{
private :
int lcs(string & s1,string & s2,int m,int n,vector<vector<int>> & dp){
if ( m == 0 || n == 0){
return 0;
}
if(dp[m][n] != -1){
return dp[m][n];
}
if(s1[m-1] == s2[n-1]){
return 1 + lcs(s1,s2,m-1,n-1,dp);
}
int res = max(lcs(s1,s2,m-1,n,dp),lcs(s1,s2,m,n-1,dp));
dp[m][n]=res;
return res;
}
public:
int minOperations(string str1, string str2) {
vector<vector<int>> dp(str1.size()+1,vector<int> (str2.size()+1,-1));
int res = this->lcs(str1,str2,str1.size(),str2.size(),dp);
res = (str1.size() - res) + (str2.size() - res);
return res;
}
};
0
uratabhi2 weeks ago
int n = str1.size(); int m = str2.size(); std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (str1[i - 1] == str2[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1]; } else { dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } } } return n+m-2*dp[n][m];
+1
gargharshit5671 month ago
C++ Direct DP Solution withouth doing calculations after lcs
class Solution{
public:
int minOperations(string str1, string str2)
{
// Your code goes here
int n= str1.length();
int m= str2.length();
int dp[n+1][m+1];
for(int i=0;i<n+1;i++)dp[i][0]=i;
for(int i=1;i<m+1;i++)dp[0][i]=i;
for(int i=1;i<n+1;i++){
for(int j=1;j<m+1;j++)
{
if(str1[i-1] == str2[j-1]){
dp[i][j]= dp[i-1][j-1];
}
else
{
dp[i][j] = min(dp[i-1][j-1]+2, min(dp[i-1][j]+1,dp[i][j-1]+1));
}
}
}
return dp[n][m];
}
};
0
shrustis1761 month ago
C++ solution
class Solution{public:int lcs(int x, int y, string s1, string s2) { // your code here int t[x+1][y+1]; int i,j; for(i=0; i<x+1; i++) for(j=0; j<y+1; j++) if( i==0 || j==0) t[i][j]=0; for(i=1; i<x+1; i++) for(j=1; j<y+1; j++) { if(s1[i-1] == s2[j-1]) t[i][j] = 1+t[i-1][j-1]; else t[i][j] = max(t[i-1][j], t[i][j-1]); } return t[x][y];} int minOperations(string str1, string str2) { // Your code goes here int n = str1.length(); int m = str2.length(); int len = lcs(n,m,str1, str2); int del= n-len; int ins= m-len; return del+ins;} };
0
gulshan991 month ago
simple idea :
1 find lcm
2 deletion will be(str1.length()-lcm +str2.length()-lcm)
public:
int minOperations(string str1, string str2)
{
// Your code goes here
int n=str1.length(),m=str2.length();
int dp[n+1][m+1];
for(int i=0;i<=n;i++)
{
dp[i][0]=0;
}
for(int j=0;j<=m;j++)
{
dp[0][j]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(str1[i-1]==str2[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
}
else{
dp[i][j]= max(dp[i-1][j],dp[i][j-1]);
}
}
}
return n-dp[n][m]+m-dp[n][m];
}
0
ayushkumar54511 month ago
int dp[1001][1001];int del_ins(string &a,string &b,int n,int m){ for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } } return dp[n][m];}int minOperations(string str1, string str2) { // Your code goes here int n=str1.size(); int m=str2.size(); int x=del_ins(str1,str2,n,m); int y=del_ins(str1,str2,n,m); int k=n-x; int z=m-y; return k+z; }
0
mailtoamandeepsingh281 month ago
C++ solution
int minOperations(string str1, string str2) { if(str1==str2) return 0; int n = str1.length(); int m = str2.length(); vector<vector<int>>dp(n+1, vector<int>(m+1, -1)); for(int i=0;i<=n;i++) dp[i][0] = 0; for(int i=0;i<=m;i++) dp[0][i] = 0; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(str1[i-1]==str2[j-1]){ dp[i][j] = 1+dp[i-1][j-1]; } else{ dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } int lcs = dp[n][m]; return n+m-2*lcs;}
0
annanyamathur2 months ago
int memo[1001][1001];int matched(string a,string b,int n,int m){ if(memo[n][m]==-1) { if(n==0 ||m==0) memo[n][m]=0; else{if(a[n-1]==b[m-1]) memo[n][m]=1+matched(a,b,n-1,m-1); else memo[n][m]= max(matched(a,b,n-1,m),matched(a,b,n,m-1));}} return memo[n][m]; }int minOperations(string a, string b) { int n=a.size(), m=b.size(); for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { memo[i][j]=-1; } } int res=matched(a,b,n,m), ans=(n-res)+(m-res); //cout<<res<<endl; return ans; }
+1
tirtha19025682 months ago
JAVA SOLUTION
class Solution
{
public int minOperations(String str1, String str2)
{
int m = str1.length();
int n = str2.length();
// LCS
int[][]dp = new int[m+1][n+1];
for(int i=1;i<dp.length;i++){
for(int j=1;j<dp[0].length;j++){
if(str1.charAt(i-1) == str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1]+1;
}
else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
int lcs = dp[m][n];
int insert = n - Math.abs(lcs);
int delete = m - Math.abs(lcs);
return insert + delete;
}
}
0
chessnoobdj2 months ago
C++
int minOperations(string s1, string s2)
{
int n = s1.size(), m = s2.size();
vector <vector<int>> dp(n+1, vector<int> (m+1, 0));
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
if(s1[i-1] == s2[j-1])
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return n+m-2*(dp[n][m]);
}
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": 514,
"s": 238,
"text": "Given two strings str1 and str2. The task is to remove or insert the minimum number of characters from/in str1 so as to transform it into str2. It could be possible that the same character needs to be removed/deleted from one point of str1 and inserted to some another point."
},
{
"code": null,
"e": 525,
"s": 514,
"text": "Example 1:"
},
{
"code": null,
"e": 900,
"s": 525,
"text": "Input: str1 = \"heap\", str2 = \"pea\"\nOutput: 3\nExplanation: 2 deletions and 1 insertion\np and h deleted from heap. Then, p is \ninserted at the beginning One thing to \nnote, though p was required yet it was \nremoved/deleted first from its position \nand then it is inserted to some other \nposition. Thus, p contributes one to the \ndeletion_count and one to the \ninsertion_count."
},
{
"code": null,
"e": 911,
"s": 900,
"text": "Example 2:"
},
{
"code": null,
"e": 993,
"s": 911,
"text": "Input : str1 = \"geeksforgeeks\"\nstr2 = \"geeks\"\nOutput: 8\nExplanation: 8 deletions\n"
},
{
"code": null,
"e": 1200,
"s": 995,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function minOperations() which takes both strings as input parameter and returns the minimum number of operation required."
},
{
"code": null,
"e": 1287,
"s": 1200,
"text": "Expected Time Complexity: O(|str1|*|str2|)\nExpected Space Complexity: O(|str1|*|str2|)"
},
{
"code": null,
"e": 1378,
"s": 1287,
"text": "Constraints:\n1 ≤ |str1|, |str2| ≤ 1000\nAll the characters are lower case English alphabets"
},
{
"code": null,
"e": 1380,
"s": 1378,
"text": "0"
},
{
"code": null,
"e": 1403,
"s": 1380,
"text": "apurvkumarak2 days ago"
},
{
"code": null,
"e": 1417,
"s": 1403,
"text": "C++ Solution "
},
{
"code": null,
"e": 2131,
"s": 1417,
"text": " class Solution{\n private : \n int lcs(string & s1,string & s2,int m,int n,vector<vector<int>> & dp){\n if ( m == 0 || n == 0){\n return 0;\n }\n if(dp[m][n] != -1){\n return dp[m][n];\n }\n if(s1[m-1] == s2[n-1]){\n return 1 + lcs(s1,s2,m-1,n-1,dp);\n }\n int res = max(lcs(s1,s2,m-1,n,dp),lcs(s1,s2,m,n-1,dp));\n dp[m][n]=res;\n return res;\n }\n\tpublic:\n\tint minOperations(string str1, string str2) { \n\t vector<vector<int>> dp(str1.size()+1,vector<int> (str2.size()+1,-1));\n\t int res = this->lcs(str1,str2,str1.size(),str2.size(),dp);\n\t res = (str1.size() - res) + (str2.size() - res);\n\t return res;\n\t}\n};"
},
{
"code": null,
"e": 2133,
"s": 2131,
"text": "0"
},
{
"code": null,
"e": 2153,
"s": 2133,
"text": "uratabhi2 weeks ago"
},
{
"code": null,
"e": 2281,
"s": 2153,
"text": " int n = str1.size(); int m = str2.size(); std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1, 0));"
},
{
"code": null,
"e": 2613,
"s": 2281,
"text": " for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (str1[i - 1] == str2[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1]; } else { dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } } } return n+m-2*dp[n][m];"
},
{
"code": null,
"e": 2616,
"s": 2613,
"text": "+1"
},
{
"code": null,
"e": 2642,
"s": 2616,
"text": "gargharshit5671 month ago"
},
{
"code": null,
"e": 2703,
"s": 2642,
"text": "C++ Direct DP Solution withouth doing calculations after lcs"
},
{
"code": null,
"e": 2723,
"s": 2707,
"text": "class Solution{"
},
{
"code": null,
"e": 2732,
"s": 2723,
"text": "\tpublic:"
},
{
"code": null,
"e": 2778,
"s": 2732,
"text": "\tint minOperations(string str1, string str2) "
},
{
"code": null,
"e": 2782,
"s": 2778,
"text": "\t{ "
},
{
"code": null,
"e": 2810,
"s": 2782,
"text": "\t // Your code goes here"
},
{
"code": null,
"e": 2837,
"s": 2810,
"text": "\t int n= str1.length();"
},
{
"code": null,
"e": 2864,
"s": 2837,
"text": "\t int m= str2.length();"
},
{
"code": null,
"e": 2887,
"s": 2864,
"text": "\t int dp[n+1][m+1];"
},
{
"code": null,
"e": 2926,
"s": 2887,
"text": "\t for(int i=0;i<n+1;i++)dp[i][0]=i;"
},
{
"code": null,
"e": 2965,
"s": 2926,
"text": "\t for(int i=1;i<m+1;i++)dp[0][i]=i;"
},
{
"code": null,
"e": 3000,
"s": 2971,
"text": "\t for(int i=1;i<n+1;i++){"
},
{
"code": null,
"e": 3032,
"s": 3000,
"text": "\t for(int j=1;j<m+1;j++)"
},
{
"code": null,
"e": 3043,
"s": 3032,
"text": "\t {"
},
{
"code": null,
"e": 3084,
"s": 3043,
"text": "\t if(str1[i-1] == str2[j-1]){"
},
{
"code": null,
"e": 3125,
"s": 3084,
"text": "\t dp[i][j]= dp[i-1][j-1];"
},
{
"code": null,
"e": 3140,
"s": 3125,
"text": "\t }"
},
{
"code": null,
"e": 3158,
"s": 3140,
"text": "\t else"
},
{
"code": null,
"e": 3173,
"s": 3158,
"text": "\t {"
},
{
"code": null,
"e": 3254,
"s": 3173,
"text": "\t dp[i][j] = min(dp[i-1][j-1]+2, min(dp[i-1][j]+1,dp[i][j-1]+1));"
},
{
"code": null,
"e": 3269,
"s": 3254,
"text": "\t }"
},
{
"code": null,
"e": 3280,
"s": 3269,
"text": "\t }"
},
{
"code": null,
"e": 3287,
"s": 3280,
"text": "\t }"
},
{
"code": null,
"e": 3309,
"s": 3287,
"text": "\t return dp[n][m];"
},
{
"code": null,
"e": 3312,
"s": 3309,
"text": "\t}"
},
{
"code": null,
"e": 3315,
"s": 3312,
"text": "};"
},
{
"code": null,
"e": 3319,
"s": 3317,
"text": "0"
},
{
"code": null,
"e": 3342,
"s": 3319,
"text": "shrustis1761 month ago"
},
{
"code": null,
"e": 3355,
"s": 3342,
"text": "C++ solution"
},
{
"code": null,
"e": 4074,
"s": 3357,
"text": "class Solution{public:int lcs(int x, int y, string s1, string s2) { // your code here int t[x+1][y+1]; int i,j; for(i=0; i<x+1; i++) for(j=0; j<y+1; j++) if( i==0 || j==0) t[i][j]=0; for(i=1; i<x+1; i++) for(j=1; j<y+1; j++) { if(s1[i-1] == s2[j-1]) t[i][j] = 1+t[i-1][j-1]; else t[i][j] = max(t[i-1][j], t[i][j-1]); } return t[x][y];} int minOperations(string str1, string str2) { // Your code goes here int n = str1.length(); int m = str2.length(); int len = lcs(n,m,str1, str2); int del= n-len; int ins= m-len; return del+ins;} };"
},
{
"code": null,
"e": 4076,
"s": 4074,
"text": "0"
},
{
"code": null,
"e": 4097,
"s": 4076,
"text": "gulshan991 month ago"
},
{
"code": null,
"e": 4187,
"s": 4097,
"text": " simple idea : \n 1 find lcm\n 2 deletion will be(str1.length()-lcm +str2.length()-lcm)"
},
{
"code": null,
"e": 4879,
"s": 4187,
"text": "\tpublic:\n\tint minOperations(string str1, string str2) \n\t{ \n\t // Your code goes here\n\t int n=str1.length(),m=str2.length();\n int dp[n+1][m+1];\n for(int i=0;i<=n;i++)\n {\n dp[i][0]=0;\n }\n for(int j=0;j<=m;j++)\n {\n dp[0][j]=0;\n }\n \n for(int i=1;i<=n;i++)\n {\n for(int j=1;j<=m;j++)\n {\n if(str1[i-1]==str2[j-1])\n {\n dp[i][j]=dp[i-1][j-1]+1;\n }\n else{\n dp[i][j]= max(dp[i-1][j],dp[i][j-1]);\n }\n }\n }\n return n-dp[n][m]+m-dp[n][m];\n\t \n\t} "
},
{
"code": null,
"e": 4881,
"s": 4879,
"text": "0"
},
{
"code": null,
"e": 4907,
"s": 4881,
"text": "ayushkumar54511 month ago"
},
{
"code": null,
"e": 5577,
"s": 4907,
"text": " int dp[1001][1001];int del_ins(string &a,string &b,int n,int m){ for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } } return dp[n][m];}int minOperations(string str1, string str2) { // Your code goes here int n=str1.size(); int m=str2.size(); int x=del_ins(str1,str2,n,m); int y=del_ins(str1,str2,n,m); int k=n-x; int z=m-y; return k+z; } "
},
{
"code": null,
"e": 5579,
"s": 5577,
"text": "0"
},
{
"code": null,
"e": 5612,
"s": 5579,
"text": "mailtoamandeepsingh281 month ago"
},
{
"code": null,
"e": 5625,
"s": 5612,
"text": "C++ solution"
},
{
"code": null,
"e": 6232,
"s": 5625,
"text": " int minOperations(string str1, string str2) { if(str1==str2) return 0; int n = str1.length(); int m = str2.length(); vector<vector<int>>dp(n+1, vector<int>(m+1, -1)); for(int i=0;i<=n;i++) dp[i][0] = 0; for(int i=0;i<=m;i++) dp[0][i] = 0; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(str1[i-1]==str2[j-1]){ dp[i][j] = 1+dp[i-1][j-1]; } else{ dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } int lcs = dp[n][m]; return n+m-2*lcs;}"
},
{
"code": null,
"e": 6234,
"s": 6232,
"text": "0"
},
{
"code": null,
"e": 6260,
"s": 6234,
"text": "annanyamathur2 months ago"
},
{
"code": null,
"e": 6804,
"s": 6260,
"text": "int memo[1001][1001];int matched(string a,string b,int n,int m){ if(memo[n][m]==-1) { if(n==0 ||m==0) memo[n][m]=0; else{if(a[n-1]==b[m-1]) memo[n][m]=1+matched(a,b,n-1,m-1); else memo[n][m]= max(matched(a,b,n-1,m),matched(a,b,n,m-1));}} return memo[n][m]; }int minOperations(string a, string b) { int n=a.size(), m=b.size(); for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { memo[i][j]=-1; } } int res=matched(a,b,n,m), ans=(n-res)+(m-res); //cout<<res<<endl; return ans; } "
},
{
"code": null,
"e": 6807,
"s": 6804,
"text": "+1"
},
{
"code": null,
"e": 6833,
"s": 6807,
"text": "tirtha19025682 months ago"
},
{
"code": null,
"e": 6847,
"s": 6833,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 7468,
"s": 6849,
"text": "class Solution\n{\npublic int minOperations(String str1, String str2) \n{ \n int m = str1.length();\n int n = str2.length();\n \n // LCS\n int[][]dp = new int[m+1][n+1];\n for(int i=1;i<dp.length;i++){\n for(int j=1;j<dp[0].length;j++){\n if(str1.charAt(i-1) == str2.charAt(j-1)){\n dp[i][j] = dp[i-1][j-1]+1;\n }\n else{\n dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n }\n \n \n int lcs = dp[m][n];\n int insert = n - Math.abs(lcs);\n int delete = m - Math.abs(lcs);\n return insert + delete;\n } \n \n}"
},
{
"code": null,
"e": 7470,
"s": 7468,
"text": "0"
},
{
"code": null,
"e": 7494,
"s": 7470,
"text": "chessnoobdj2 months ago"
},
{
"code": null,
"e": 7498,
"s": 7494,
"text": "C++"
},
{
"code": null,
"e": 7911,
"s": 7498,
"text": "int minOperations(string s1, string s2) \n\t{\n\t int n = s1.size(), m = s2.size();\n\t vector <vector<int>> dp(n+1, vector<int> (m+1, 0));\n\t for(int i=1; i<=n; i++){\n\t for(int j=1; j<=m; j++){\n\t if(s1[i-1] == s2[j-1])\n\t dp[i][j] = 1 + dp[i-1][j-1];\n\t else\n\t dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n\t }\n\t }\n\t return n+m-2*(dp[n][m]);\n\t} "
},
{
"code": null,
"e": 8057,
"s": 7911,
"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": 8093,
"s": 8057,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8103,
"s": 8093,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8113,
"s": 8103,
"text": "\nContest\n"
},
{
"code": null,
"e": 8176,
"s": 8113,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8324,
"s": 8176,
"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": 8532,
"s": 8324,
"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": 8638,
"s": 8532,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Database Management Systems | Set 4 - GeeksforGeeks | 07 Apr, 2022
Following Questions have been asked in GATE 2011 exam.
1. Consider a relational table with a single record for each registered student with the following attributes.
1. Registration_Number:< Unique registration number for each registered student 2. UID: Unique Identity number, unique at the national level for each citizen 3. BankAccount_Number: Unique account number at the bank. A student can have multiple accounts or joint accounts. This attributes stores the primary account number 4. Name: Name of the Student 5. Hostel_Room: Room number of the hostel
Which of the following options is INCORRECT? (A) BankAccount_Number is a candidate key (B) Registration_Number can be a primary key (C) UID is a candidate key if all students are from the same country (D) If S is a superkey such that S ∩ UID is NULL then S ∪ UID is also a superkey
Answer (A)
A Candidate Key value must uniquely identify the corresponding row in table. BankAccount_Number is not a candidate key. As per the question “A student can have multiple accounts or joint accounts. This attributes stores the primary account number”. If two students have a joint account and if the joint account is their primary account, then BankAccount_Number value cannot uniquely identify a row.
2) Consider a relational table r with sufficient number of records, having attributes A1, A2,..., An and let 1 <= p <= n. Two queries Q1 and Q2 are given below.
The database can be configured to do ordered indexing on Ap or hashing on Ap. Which of the following statements is TRUE? (A) Ordered indexing will always outperform hashing for both queries (B) Hashing will always outperform ordered indexing for both queries (C) Hashing will outperform ordered indexing on Q1, but not on Q2 (D) Hashing will outperform ordered indexing on Q2, but not on Q1.
Answer (C)
If record are accessed for a particular value from table, hashing will do better. If records are accessed in a range of values, ordered indexing will perform better. See this for more details.
3) Database table by name Loan_Records is given below.
Borrower Bank_Manager Loan_Amount
Ramesh Sunderajan 10000.00
Suresh Ramgopal 5000.00
Mahesh Sunderajan 7000.00
What is the output of the following SQL query?
SELECT Count(*)
FROM ( (SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S
NATURAL JOIN (SELECT Bank_Manager,
Loan_Amount
FROM Loan_Records) AS T );
(A) 3 (B) 9 (C) 5 (D) 6
Answer (C)
Following will be contents of temporary table S
Borrower Bank_Manager
--------------------------
Ramesh Sunderajan
Suresh Ramgopal
Mahesh Sunderajan
Following will be contents of temporary table T
Bank_Manager Loan_Amount
---------------------------
Sunderajan 10000.00
Ramgopal 5000.00
Sunderajan 7000.00
Following will be the result of natural join of above two tables. The key thing to note is that the natural join happens on column name with same name which is Bank_Manager in the above example. “Sunderajan” appears two times in Bank_Manager column, so their will be four entries with Bank_Manager as “Sunderajan”.
Borrower Bank_Manager Loan_Amount
------------------------------------
Ramesh Sunderajan 10000.00
Ramesh Sunderajan 7000.00
Suresh Ramgopal 5000.00
Mahesh Sunderajan 10000.00
Mahesh Sunderajan 7000.00
4) Consider a database table T containing two columns X and Y each of type integer. After the creation of the table, one record (X=1, Y=1) is inserted in the table.
Let MX and My denote the respective maximum values of X and Y among all records in the table at any point in time. Using MX and MY, new records are inserted in the table 128 times with X and Y values being MX+1, 2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and MY change. What will be the output of the following SQL query after the steps mentioned above are carried out?
SELECT Y FROM T WHERE X=7;
(A) 127 (B) 255 (C) 129 (D) 257
Answer (A)
X Y
-------
1 1
2 3
3 7
4 15
5 31
6 63
7 127
......
......
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
naimishrastogi
om_mishra
GATE-CS-2011
DBMS
GATE CS
MCQ
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
LRU Cache Implementation | [
{
"code": null,
"e": 29235,
"s": 29207,
"text": "\n07 Apr, 2022"
},
{
"code": null,
"e": 29291,
"s": 29235,
"text": "Following Questions have been asked in GATE 2011 exam. "
},
{
"code": null,
"e": 29403,
"s": 29291,
"text": "1. Consider a relational table with a single record for each registered student with the following attributes. "
},
{
"code": null,
"e": 29797,
"s": 29403,
"text": "1. Registration_Number:< Unique registration number for each registered student 2. UID: Unique Identity number, unique at the national level for each citizen 3. BankAccount_Number: Unique account number at the bank. A student can have multiple accounts or joint accounts. This attributes stores the primary account number 4. Name: Name of the Student 5. Hostel_Room: Room number of the hostel "
},
{
"code": null,
"e": 30080,
"s": 29797,
"text": "Which of the following options is INCORRECT? (A) BankAccount_Number is a candidate key (B) Registration_Number can be a primary key (C) UID is a candidate key if all students are from the same country (D) If S is a superkey such that S ∩ UID is NULL then S ∪ UID is also a superkey "
},
{
"code": null,
"e": 30092,
"s": 30080,
"text": "Answer (A) "
},
{
"code": null,
"e": 30492,
"s": 30092,
"text": "A Candidate Key value must uniquely identify the corresponding row in table. BankAccount_Number is not a candidate key. As per the question “A student can have multiple accounts or joint accounts. This attributes stores the primary account number”. If two students have a joint account and if the joint account is their primary account, then BankAccount_Number value cannot uniquely identify a row. "
},
{
"code": null,
"e": 30655,
"s": 30492,
"text": "2) Consider a relational table r with sufficient number of records, having attributes A1, A2,..., An and let 1 <= p <= n. Two queries Q1 and Q2 are given below. "
},
{
"code": null,
"e": 31048,
"s": 30655,
"text": "The database can be configured to do ordered indexing on Ap or hashing on Ap. Which of the following statements is TRUE? (A) Ordered indexing will always outperform hashing for both queries (B) Hashing will always outperform ordered indexing for both queries (C) Hashing will outperform ordered indexing on Q1, but not on Q2 (D) Hashing will outperform ordered indexing on Q2, but not on Q1. "
},
{
"code": null,
"e": 31060,
"s": 31048,
"text": "Answer (C) "
},
{
"code": null,
"e": 31254,
"s": 31060,
"text": "If record are accessed for a particular value from table, hashing will do better. If records are accessed in a range of values, ordered indexing will perform better. See this for more details. "
},
{
"code": null,
"e": 31310,
"s": 31254,
"text": "3) Database table by name Loan_Records is given below. "
},
{
"code": null,
"e": 31458,
"s": 31310,
"text": "Borrower Bank_Manager Loan_Amount\n Ramesh Sunderajan 10000.00\n Suresh Ramgopal 5000.00\n Mahesh Sunderajan 7000.00"
},
{
"code": null,
"e": 31506,
"s": 31458,
"text": "What is the output of the following SQL query? "
},
{
"code": null,
"e": 31735,
"s": 31506,
"text": "SELECT Count(*) \nFROM ( (SELECT Borrower, Bank_Manager \n FROM Loan_Records) AS S \n NATURAL JOIN (SELECT Bank_Manager, \n Loan_Amount \n FROM Loan_Records) AS T ); "
},
{
"code": null,
"e": 31760,
"s": 31735,
"text": "(A) 3 (B) 9 (C) 5 (D) 6 "
},
{
"code": null,
"e": 31772,
"s": 31760,
"text": "Answer (C) "
},
{
"code": null,
"e": 31821,
"s": 31772,
"text": "Following will be contents of temporary table S "
},
{
"code": null,
"e": 31943,
"s": 31821,
"text": "Borrower Bank_Manager\n--------------------------\n Ramesh Sunderajan\n Suresh Ramgopal\n Mahesh Sunderajan"
},
{
"code": null,
"e": 31993,
"s": 31943,
"text": "Following will be contents of temporary table T "
},
{
"code": null,
"e": 32121,
"s": 31993,
"text": "Bank_Manager Loan_Amount\n---------------------------\nSunderajan 10000.00\nRamgopal 5000.00\nSunderajan 7000.00"
},
{
"code": null,
"e": 32437,
"s": 32121,
"text": "Following will be the result of natural join of above two tables. The key thing to note is that the natural join happens on column name with same name which is Bank_Manager in the above example. “Sunderajan” appears two times in Bank_Manager column, so their will be four entries with Bank_Manager as “Sunderajan”. "
},
{
"code": null,
"e": 32678,
"s": 32437,
"text": "Borrower Bank_Manager Loan_Amount\n------------------------------------\nRamesh Sunderajan 10000.00\nRamesh Sunderajan 7000.00\nSuresh Ramgopal 5000.00\nMahesh Sunderajan 10000.00\nMahesh Sunderajan 7000.00"
},
{
"code": null,
"e": 32844,
"s": 32678,
"text": "4) Consider a database table T containing two columns X and Y each of type integer. After the creation of the table, one record (X=1, Y=1) is inserted in the table. "
},
{
"code": null,
"e": 33258,
"s": 32844,
"text": "Let MX and My denote the respective maximum values of X and Y among all records in the table at any point in time. Using MX and MY, new records are inserted in the table 128 times with X and Y values being MX+1, 2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and MY change. What will be the output of the following SQL query after the steps mentioned above are carried out? "
},
{
"code": null,
"e": 33285,
"s": 33258,
"text": "SELECT Y FROM T WHERE X=7;"
},
{
"code": null,
"e": 33318,
"s": 33285,
"text": "(A) 127 (B) 255 (C) 129 (D) 257 "
},
{
"code": null,
"e": 33331,
"s": 33318,
"text": "Answer (A) "
},
{
"code": null,
"e": 33423,
"s": 33331,
"text": " X Y\n-------\n 1 1\n 2 3\n 3 7\n 4 15\n 5 31\n 6 63\n 7 127\n ......\n ......"
},
{
"code": null,
"e": 33538,
"s": 33423,
"text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. "
},
{
"code": null,
"e": 33688,
"s": 33538,
"text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. "
},
{
"code": null,
"e": 33703,
"s": 33688,
"text": "naimishrastogi"
},
{
"code": null,
"e": 33713,
"s": 33703,
"text": "om_mishra"
},
{
"code": null,
"e": 33726,
"s": 33713,
"text": "GATE-CS-2011"
},
{
"code": null,
"e": 33731,
"s": 33726,
"text": "DBMS"
},
{
"code": null,
"e": 33739,
"s": 33731,
"text": "GATE CS"
},
{
"code": null,
"e": 33743,
"s": 33739,
"text": "MCQ"
},
{
"code": null,
"e": 33748,
"s": 33743,
"text": "DBMS"
},
{
"code": null,
"e": 33846,
"s": 33748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33855,
"s": 33846,
"text": "Comments"
},
{
"code": null,
"e": 33868,
"s": 33855,
"text": "Old Comments"
},
{
"code": null,
"e": 33915,
"s": 33868,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 33933,
"s": 33915,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 33974,
"s": 33933,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 34005,
"s": 33974,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 34058,
"s": 34005,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 34078,
"s": 34058,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 34105,
"s": 34078,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 34118,
"s": 34105,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 34167,
"s": 34118,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Can we convert MD5 to SHA256 in a MySQL table with user password column? | Use SHA2() to convert the MD5 password to SHA256. It calculates the SHA-2 family of hash functions i.e. SHA-224, SHA-256, SHA-384, and SHA-512).
Let us first create a table −
mysql> create table DemoTable818(UserPassword text);
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable818 values(MD5('John_123'));
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable818 values(MD5('999Carol@22'));
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable818;
This will produce the following output −
+----------------------------------+
| UserPassword |
+----------------------------------+
| 47c7d0987db4e59e2264ce9fefce4977 |
| 950aa70edd5b686a807b3bfffdf2248c |
+----------------------------------+
2 rows in set (0.00 sec)
Following is the query to convert MD5 to SHA256 −
mysql> update DemoTable818 set UserPassword=SHA2(UserPassword,256);
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable818;
This will produce the following output −
+------------------------------------------------------------------+
| UserPassword |
+------------------------------------------------------------------+
| 8b68c46294a9ccb2449324c24fe774f95b7c14e4b56fc51c7f8e6c5b01c7020f |
| 9cc80741546051ae3de7d31246327968c98af3c65125376acb7b49a0760d42a3 |
+------------------------------------------------------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "Use SHA2() to convert the MD5 password to SHA256. It calculates the SHA-2 family of hash functions i.e. SHA-224, SHA-256, SHA-384, and SHA-512)."
},
{
"code": null,
"e": 1237,
"s": 1207,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1327,
"s": 1237,
"text": "mysql> create table DemoTable818(UserPassword text);\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 1383,
"s": 1327,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1572,
"s": 1383,
"text": "mysql> insert into DemoTable818 values(MD5('John_123'));\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable818 values(MD5('999Carol@22'));\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1632,
"s": 1572,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1666,
"s": 1632,
"text": "mysql> select *from DemoTable818;"
},
{
"code": null,
"e": 1707,
"s": 1666,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1954,
"s": 1707,
"text": "+----------------------------------+\n| UserPassword |\n+----------------------------------+\n| 47c7d0987db4e59e2264ce9fefce4977 |\n| 950aa70edd5b686a807b3bfffdf2248c |\n+----------------------------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2004,
"s": 1954,
"text": "Following is the query to convert MD5 to SHA256 −"
},
{
"code": null,
"e": 2148,
"s": 2004,
"text": "mysql> update DemoTable818 set UserPassword=SHA2(UserPassword,256);\nQuery OK, 2 rows affected (0.19 sec)\nRows matched: 2 Changed: 2 Warnings: 0"
},
{
"code": null,
"e": 2192,
"s": 2148,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2226,
"s": 2192,
"text": "mysql> select *from DemoTable818;"
},
{
"code": null,
"e": 2267,
"s": 2226,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2706,
"s": 2267,
"text": "+------------------------------------------------------------------+\n| UserPassword |\n+------------------------------------------------------------------+\n| 8b68c46294a9ccb2449324c24fe774f95b7c14e4b56fc51c7f8e6c5b01c7020f |\n| 9cc80741546051ae3de7d31246327968c98af3c65125376acb7b49a0760d42a3 |\n+------------------------------------------------------------------+\n2 rows in set (0.00 sec)"
}
] |
CNN Sentiment Analysis. Convolutional neural networks, or CNNs... | by Rita Kurban | Towards Data Science | Convolutional neural networks, or CNNs, form the backbone of multiple modern computer vision systems. Image classification, object detection, semantic segmentation — all these tasks can be tackled by CNNs successfully. At first glance, it seems to be counterintuitive to use the same technique for a task as different as Natural Language Processing. This post is my attempt to explain the intuition behind this approach using the famous IMDb dataset.
After reading this post, you will:
Learn how to preprocess text using torchtextUnderstand the idea behind convolutionsLearn how to represent text as imagesBuild a basic CNN Sentiment Analysis model in PyTorch
Learn how to preprocess text using torchtext
Understand the idea behind convolutions
Learn how to represent text as images
Build a basic CNN Sentiment Analysis model in PyTorch
Let’s get started!
The IMDb dataset for binary sentiment classification contains a set of 25,000 highly polar movie reviews for training and 25,000 for testing. Luckily, it is a part of torchtext, so it is straightforward to load and pre-process it in PyTorch:
# Create an instance that turns text into tensorsTEXT = data.Field(tokenize = 'spacy', batch_first = True)LABEL = data.LabelField(dtype = torch.float)# Load data from torchtexttrain_data, test_data = datasets.IMDB.splits(TEXT, LABEL)train_data, valid_data = train_data.split()# Select only the most important 30000 wordsMAX_VOCAB_SIZE = 30_000# Build vocabularyTEXT.build_vocab(train_data, max_size = MAX_VOCAB_SIZE, # Load pretrained embeddings vectors = "glove.6B.100d", unk_init = torch.Tensor.normal_)LABEL.build_vocab(train_data)
The data.Fieldclass defines a datatype together with instructions for converting it to Tensor. In this case, we are using SpaCy tokenizer to segment text into individual tokens (words). After that, we build a vocabulary so that we can convert our tokens into integer numbers later. The vocabulary is constructed with all words present in our train dataset. Additionally, we load pre-trained GloVe embeddings so that we don’t need to train our own word vectors from scratch. If you’re wondering what word embeddings are, they are a form of word representation that bridges the human understanding of language to that of a machine. To learn more, read this article. Since we will be training our model in batches, we will also create data iterators that output a specific number of samples at a time:
# Create PyTorch iterators to use in trainingtrain_iterator, valid_iterator, test_iterator = data.BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, device = device)
BucketIterator is a module in torchtext that is specifically optimized to minimize the amount of padding needed while producing freshly shuffled batches for each new epoch. Now we are done with text preprocessing, so it’s time to learn more about CNNs.
Convolutions are sliding window functions applied to a matrix that achieve specific results (e. g., image blur, edge detection.) The sliding window is called a kernel, filter, or feature detector. The visualization shows six 3×3 kernels that multiply their values element-wise with the original matrix, then sum them up. To get the full convolution, we do this for each element by sliding the filter over the entire matrix:
CNNs are just several layers of convolutions with activation functions like ReLU that make it possible to model non-linear relationships. By applying this set of dot products, we can extract relevant information from images, starting from edges on shallower levels to identifying the entire objects on deeper levels of neural networks. Unlike traditional neural networks that simply flatten the input, CNNs can extract spatial relationships that are especially useful for image data. But how about the text?
Remember the word embeddings we discussed above? That’s where they come into play. Images are just some points in space, just like the word vectors are. By representing each word with a vector of numbers of a specific length and stacking a bunch of words on top of each other, we get an “image.” Computer vision filters usually have the same width and height and slide over local parts of an image. In NLP, we typically use filters that slide over word embeddings — matrix rows. Therefore, filters usually have the same width as the length of the word embeddings. The height varies but is generally from 1 to 5, which corresponds to different n-grams. N-grams are just a bunch of subsequent words. By analyzing sequences, we can better understand the meaning of a sentence. For example, the word “like” alone has an opposite meaning compared to the bi-gram “don’t like”; the latter gives us a better understanding of the real meaning. In a way, by analyzing n-grams, we are capturing the spatial relationships in texts, which makes it easier for the model to understand the sentiment. The visualization below summarizes the concepts we just covered:
Let’s now build a binary CNN classifier. We will base our model on the built-in PyTorch nn.Module:
class CNN_Text(nn.Module): ''' Define network architecture and forward path. ''' def __init__(self, vocab_size, vector_size, n_filters, filter_sizes, output_dim, dropout, pad_idx): super().__init__() # Create word embeddings from the input words self.embedding = nn.Embedding(vocab_size, vector_size, padding_idx = pad_idx) # Specify convolutions with filters of different sizes (fs) self.convs = nn.ModuleList([nn.Conv2d(in_channels = 1, out_channels = n_filters, kernel_size = (fs, vector_size)) for fs in filter_sizes]) # Add a fully connected layer for final predicitons self.linear = nn.Linear(len(filter_sizes) \ * n_filters, output_dim) # Drop some of the nodes to increase robustness in training self.dropout = nn.Dropout(dropout) def forward(self, text): '''Forward path of the network.''' # Get word embeddings and formt them for convolutions embedded = self.embedding(text).unsqueeze(1) # Perform convolutions and apply activation functions conved = [F.relu(conv(embedded)).squeeze(3) for conv in self.convs] # Pooling layer to reduce dimensionality pooled = [F.max_pool1d(conv, conv.shape[2]).squeeze(2) for conv in conved] # Dropout layer cat = self.dropout(torch.cat(pooled, dim = 1)) return self.linear(cat)
In the initfunction, we specify different layer types: embedding, convolution, dropout, and linear. All these layers are integrated into PyTorch and are very easy to use. The only tricky part is calculating the correct number of dimensions. In the case of the linear layer, it will be equal to the number of filters you use (I use 100, but you can pick any other number) multiplied by the number of different filter sizes (5 in my case.) We can think of the weights of this linear layer as “weighting up the evidence” from each of the 500 n-grams. The forward function specifies the order in which these layers should be applied. Notice that we also use max-pooling layers. The idea behind max-pooling is that the maximum value is the “most important” feature for determining the sentiment of the review, which corresponds to the “most important” n-gram is identified through backpropagation. Max-pooling is also useful for reducing the number of parameters and computations in the network.
Once we specified our network architecture, let’s load the pre-trained GloVe embeddings we imported before:
# Initialize weights with pre-trained embeddingsmodel.embedding.weight.data.copy_(TEXT.vocab.vectors)# Zero the initial weights of the UNKnown and padding tokens.UNK_IDX = TEXT.vocab.stoi[TEXT.unk_token]# The string token used as padding. Default: “<pad>”.PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token]model.embedding.weight.data[UNK_IDX] = torch.zeros(EMBEDDING_DIM)model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM)model = model.to(device)
The second part of this code chunk sets the unknown vectors (the ones that are not present in the vocabulary) and the padding vectors (used in case the input size is smaller than the height of the largest filter) to zeros. We’re now ready to train and evaluate our model.
You can find the full training and evaluation code in this notebook:
Before training the model, we need to specify the network optimizer and the loss function. Adam and binary cross-entropy are popular choices for classification problems. To train our model, we get the model predictions, calculate how accurate they are using the loss function, and backpropagate through the network to optimize weights before the next run. We perform all these actions in the model.train() mode. To evaluate the model, don’t forget to turn the model.eval() mode on to make sure we’re not dropping half of the nodes with the dropout (while improving the robustness in the training phase, it will hurt during evaluation). We also don’t need to calculate the gradient in the evaluation phase so that we can turn it off with the help of the torch.no_grad() mode.
After training the model for several epochs (use GPU to speed it up), I got the following losses and accuracies:
The graph indicates signs of overfitting since both training loss and accuracy keep improving while the validation loss and accuracy get worse. To avoid using the overfitted model, we only save the model in case the validation loss increased. In this case, the validation loss was the highest after the third epoch. In the training loop, this part looks as follows:
if valid_loss < best_valid_loss: best_valid_loss = valid_loss torch.save(model.state_dict(), 'CNN-model.pt')
The performance of this model on the previously unseen test set is quite good: 85.43%. Finally, let’s predict the sentiment of some polar reviews using the CNN-model. To do so, we need to write a function that tokenizes user input and turns it into a tensor. After that, we get predictions using the model we just trained:
def sentiment(model, sentence, min_len = 5): '''Predict user-defined review sentiment.''' model.eval() tokenized = [tok.text for tok in nlp.tokenizer(sentence)] if len(tokenized) < min_len: tokenized += ['<pad>'] * (min_len - len(tokenized)) # Map words to word embeddings indexed = [TEXT.vocab.stoi[t] for t in tokenized] tensor = torch.LongTensor(indexed).to(device) tensor = tensor.unsqueeze(0) # Get predicitons prediction = torch.sigmoid(model(tensor)) return prediction.item()
In the original dataset, we have labels “pos” and “negs” that got mapped to 0 and 1, respectively. Let’s see how well our model performs on positive, negative, and neutral reviews:
reviews = ['This is the best movie I have ever watched!', 'This is an okay movie', 'This was a waste of time! I hated this movie.']scores = [sentiment(model, review) for review in reviews]
The model predictions are 0.007, 0.493, and 0.971 respectively, which is pretty good! Let’s try some tricker examples:
tricky_reviews = ['This is not the best movie I have ever watched!', 'Some would say it is an okay movie, but I found it terrific.', 'This was a waste of time! I did not like this movie.']scores = [sentiment(model, review) for review in tricky_reviews]scores
Unfortunately, since the model has been trained on polar reviews, it finds it quite hard to classify tricky statements. For example, the first tricky review got a score of 0.05, which is quite confident ‘yes’ even though negation is present in the sentence. Try playing around with different n-grams to see whether some of them are more important then others, maybe a model with bi-grams and 3-grams would perform better than a combination of different n-grams we used.
In this post, we went through the concept of convolutions and discussed how they can be used to work with text. We also learned how to preprocess datasets from PyTorch and built a binary classification model for sentiment analysis. Despite being fooled by tricky examples, the model performs quite well. I hope you enjoyed reading this post and feel free to reach out to me if you have any questions!
Britz, D. (2015). Understanding Convolutional Neural Networks for NLP. Retrieved from: http://www.wildml.com/2015/11/understanding-convolutional-neural-networks-for-nlp/
Lopez, M. M., & Kalita, J. (2017). Deep Learning applied to NLP. arXiv preprint arXiv:1703.03091. Retrieved from: https://arxiv.org/pdf/1703.03091.pdf
Trevett, B. (2019). Convolutional Sentiment Analysis. Retrieved from: https://github.com/bentrevett/pytorch-sentiment-analysis/blob/master/4%20-%20Convolutional%20Sentiment%20Analysis.ipynb | [
{
"code": null,
"e": 623,
"s": 172,
"text": "Convolutional neural networks, or CNNs, form the backbone of multiple modern computer vision systems. Image classification, object detection, semantic segmentation — all these tasks can be tackled by CNNs successfully. At first glance, it seems to be counterintuitive to use the same technique for a task as different as Natural Language Processing. This post is my attempt to explain the intuition behind this approach using the famous IMDb dataset."
},
{
"code": null,
"e": 658,
"s": 623,
"text": "After reading this post, you will:"
},
{
"code": null,
"e": 832,
"s": 658,
"text": "Learn how to preprocess text using torchtextUnderstand the idea behind convolutionsLearn how to represent text as imagesBuild a basic CNN Sentiment Analysis model in PyTorch"
},
{
"code": null,
"e": 877,
"s": 832,
"text": "Learn how to preprocess text using torchtext"
},
{
"code": null,
"e": 917,
"s": 877,
"text": "Understand the idea behind convolutions"
},
{
"code": null,
"e": 955,
"s": 917,
"text": "Learn how to represent text as images"
},
{
"code": null,
"e": 1009,
"s": 955,
"text": "Build a basic CNN Sentiment Analysis model in PyTorch"
},
{
"code": null,
"e": 1028,
"s": 1009,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1270,
"s": 1028,
"text": "The IMDb dataset for binary sentiment classification contains a set of 25,000 highly polar movie reviews for training and 25,000 for testing. Luckily, it is a part of torchtext, so it is straightforward to load and pre-process it in PyTorch:"
},
{
"code": null,
"e": 1872,
"s": 1270,
"text": "# Create an instance that turns text into tensorsTEXT = data.Field(tokenize = 'spacy', batch_first = True)LABEL = data.LabelField(dtype = torch.float)# Load data from torchtexttrain_data, test_data = datasets.IMDB.splits(TEXT, LABEL)train_data, valid_data = train_data.split()# Select only the most important 30000 wordsMAX_VOCAB_SIZE = 30_000# Build vocabularyTEXT.build_vocab(train_data, max_size = MAX_VOCAB_SIZE, # Load pretrained embeddings vectors = \"glove.6B.100d\", unk_init = torch.Tensor.normal_)LABEL.build_vocab(train_data)"
},
{
"code": null,
"e": 2671,
"s": 1872,
"text": "The data.Fieldclass defines a datatype together with instructions for converting it to Tensor. In this case, we are using SpaCy tokenizer to segment text into individual tokens (words). After that, we build a vocabulary so that we can convert our tokens into integer numbers later. The vocabulary is constructed with all words present in our train dataset. Additionally, we load pre-trained GloVe embeddings so that we don’t need to train our own word vectors from scratch. If you’re wondering what word embeddings are, they are a form of word representation that bridges the human understanding of language to that of a machine. To learn more, read this article. Since we will be training our model in batches, we will also create data iterators that output a specific number of samples at a time:"
},
{
"code": null,
"e": 2882,
"s": 2671,
"text": "# Create PyTorch iterators to use in trainingtrain_iterator, valid_iterator, test_iterator = data.BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, device = device)"
},
{
"code": null,
"e": 3135,
"s": 2882,
"text": "BucketIterator is a module in torchtext that is specifically optimized to minimize the amount of padding needed while producing freshly shuffled batches for each new epoch. Now we are done with text preprocessing, so it’s time to learn more about CNNs."
},
{
"code": null,
"e": 3559,
"s": 3135,
"text": "Convolutions are sliding window functions applied to a matrix that achieve specific results (e. g., image blur, edge detection.) The sliding window is called a kernel, filter, or feature detector. The visualization shows six 3×3 kernels that multiply their values element-wise with the original matrix, then sum them up. To get the full convolution, we do this for each element by sliding the filter over the entire matrix:"
},
{
"code": null,
"e": 4067,
"s": 3559,
"text": "CNNs are just several layers of convolutions with activation functions like ReLU that make it possible to model non-linear relationships. By applying this set of dot products, we can extract relevant information from images, starting from edges on shallower levels to identifying the entire objects on deeper levels of neural networks. Unlike traditional neural networks that simply flatten the input, CNNs can extract spatial relationships that are especially useful for image data. But how about the text?"
},
{
"code": null,
"e": 5217,
"s": 4067,
"text": "Remember the word embeddings we discussed above? That’s where they come into play. Images are just some points in space, just like the word vectors are. By representing each word with a vector of numbers of a specific length and stacking a bunch of words on top of each other, we get an “image.” Computer vision filters usually have the same width and height and slide over local parts of an image. In NLP, we typically use filters that slide over word embeddings — matrix rows. Therefore, filters usually have the same width as the length of the word embeddings. The height varies but is generally from 1 to 5, which corresponds to different n-grams. N-grams are just a bunch of subsequent words. By analyzing sequences, we can better understand the meaning of a sentence. For example, the word “like” alone has an opposite meaning compared to the bi-gram “don’t like”; the latter gives us a better understanding of the real meaning. In a way, by analyzing n-grams, we are capturing the spatial relationships in texts, which makes it easier for the model to understand the sentiment. The visualization below summarizes the concepts we just covered:"
},
{
"code": null,
"e": 5316,
"s": 5217,
"text": "Let’s now build a binary CNN classifier. We will base our model on the built-in PyTorch nn.Module:"
},
{
"code": null,
"e": 7040,
"s": 5316,
"text": "class CNN_Text(nn.Module): ''' Define network architecture and forward path. ''' def __init__(self, vocab_size, vector_size, n_filters, filter_sizes, output_dim, dropout, pad_idx): super().__init__() # Create word embeddings from the input words self.embedding = nn.Embedding(vocab_size, vector_size, padding_idx = pad_idx) # Specify convolutions with filters of different sizes (fs) self.convs = nn.ModuleList([nn.Conv2d(in_channels = 1, out_channels = n_filters, kernel_size = (fs, vector_size)) for fs in filter_sizes]) # Add a fully connected layer for final predicitons self.linear = nn.Linear(len(filter_sizes) \\ * n_filters, output_dim) # Drop some of the nodes to increase robustness in training self.dropout = nn.Dropout(dropout) def forward(self, text): '''Forward path of the network.''' # Get word embeddings and formt them for convolutions embedded = self.embedding(text).unsqueeze(1) # Perform convolutions and apply activation functions conved = [F.relu(conv(embedded)).squeeze(3) for conv in self.convs] # Pooling layer to reduce dimensionality pooled = [F.max_pool1d(conv, conv.shape[2]).squeeze(2) for conv in conved] # Dropout layer cat = self.dropout(torch.cat(pooled, dim = 1)) return self.linear(cat)"
},
{
"code": null,
"e": 8031,
"s": 7040,
"text": "In the initfunction, we specify different layer types: embedding, convolution, dropout, and linear. All these layers are integrated into PyTorch and are very easy to use. The only tricky part is calculating the correct number of dimensions. In the case of the linear layer, it will be equal to the number of filters you use (I use 100, but you can pick any other number) multiplied by the number of different filter sizes (5 in my case.) We can think of the weights of this linear layer as “weighting up the evidence” from each of the 500 n-grams. The forward function specifies the order in which these layers should be applied. Notice that we also use max-pooling layers. The idea behind max-pooling is that the maximum value is the “most important” feature for determining the sentiment of the review, which corresponds to the “most important” n-gram is identified through backpropagation. Max-pooling is also useful for reducing the number of parameters and computations in the network."
},
{
"code": null,
"e": 8139,
"s": 8031,
"text": "Once we specified our network architecture, let’s load the pre-trained GloVe embeddings we imported before:"
},
{
"code": null,
"e": 8591,
"s": 8139,
"text": "# Initialize weights with pre-trained embeddingsmodel.embedding.weight.data.copy_(TEXT.vocab.vectors)# Zero the initial weights of the UNKnown and padding tokens.UNK_IDX = TEXT.vocab.stoi[TEXT.unk_token]# The string token used as padding. Default: “<pad>”.PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token]model.embedding.weight.data[UNK_IDX] = torch.zeros(EMBEDDING_DIM)model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM)model = model.to(device)"
},
{
"code": null,
"e": 8863,
"s": 8591,
"text": "The second part of this code chunk sets the unknown vectors (the ones that are not present in the vocabulary) and the padding vectors (used in case the input size is smaller than the height of the largest filter) to zeros. We’re now ready to train and evaluate our model."
},
{
"code": null,
"e": 8932,
"s": 8863,
"text": "You can find the full training and evaluation code in this notebook:"
},
{
"code": null,
"e": 9707,
"s": 8932,
"text": "Before training the model, we need to specify the network optimizer and the loss function. Adam and binary cross-entropy are popular choices for classification problems. To train our model, we get the model predictions, calculate how accurate they are using the loss function, and backpropagate through the network to optimize weights before the next run. We perform all these actions in the model.train() mode. To evaluate the model, don’t forget to turn the model.eval() mode on to make sure we’re not dropping half of the nodes with the dropout (while improving the robustness in the training phase, it will hurt during evaluation). We also don’t need to calculate the gradient in the evaluation phase so that we can turn it off with the help of the torch.no_grad() mode."
},
{
"code": null,
"e": 9820,
"s": 9707,
"text": "After training the model for several epochs (use GPU to speed it up), I got the following losses and accuracies:"
},
{
"code": null,
"e": 10186,
"s": 9820,
"text": "The graph indicates signs of overfitting since both training loss and accuracy keep improving while the validation loss and accuracy get worse. To avoid using the overfitted model, we only save the model in case the validation loss increased. In this case, the validation loss was the highest after the third epoch. In the training loop, this part looks as follows:"
},
{
"code": null,
"e": 10309,
"s": 10186,
"text": "if valid_loss < best_valid_loss: best_valid_loss = valid_loss torch.save(model.state_dict(), 'CNN-model.pt')"
},
{
"code": null,
"e": 10632,
"s": 10309,
"text": "The performance of this model on the previously unseen test set is quite good: 85.43%. Finally, let’s predict the sentiment of some polar reviews using the CNN-model. To do so, we need to write a function that tokenizes user input and turns it into a tensor. After that, we get predictions using the model we just trained:"
},
{
"code": null,
"e": 11155,
"s": 10632,
"text": "def sentiment(model, sentence, min_len = 5): '''Predict user-defined review sentiment.''' model.eval() tokenized = [tok.text for tok in nlp.tokenizer(sentence)] if len(tokenized) < min_len: tokenized += ['<pad>'] * (min_len - len(tokenized)) # Map words to word embeddings indexed = [TEXT.vocab.stoi[t] for t in tokenized] tensor = torch.LongTensor(indexed).to(device) tensor = tensor.unsqueeze(0) # Get predicitons prediction = torch.sigmoid(model(tensor)) return prediction.item()"
},
{
"code": null,
"e": 11336,
"s": 11155,
"text": "In the original dataset, we have labels “pos” and “negs” that got mapped to 0 and 1, respectively. Let’s see how well our model performs on positive, negative, and neutral reviews:"
},
{
"code": null,
"e": 11547,
"s": 11336,
"text": "reviews = ['This is the best movie I have ever watched!', 'This is an okay movie', 'This was a waste of time! I hated this movie.']scores = [sentiment(model, review) for review in reviews]"
},
{
"code": null,
"e": 11666,
"s": 11547,
"text": "The model predictions are 0.007, 0.493, and 0.971 respectively, which is pretty good! Let’s try some tricker examples:"
},
{
"code": null,
"e": 11947,
"s": 11666,
"text": "tricky_reviews = ['This is not the best movie I have ever watched!', 'Some would say it is an okay movie, but I found it terrific.', 'This was a waste of time! I did not like this movie.']scores = [sentiment(model, review) for review in tricky_reviews]scores"
},
{
"code": null,
"e": 12417,
"s": 11947,
"text": "Unfortunately, since the model has been trained on polar reviews, it finds it quite hard to classify tricky statements. For example, the first tricky review got a score of 0.05, which is quite confident ‘yes’ even though negation is present in the sentence. Try playing around with different n-grams to see whether some of them are more important then others, maybe a model with bi-grams and 3-grams would perform better than a combination of different n-grams we used."
},
{
"code": null,
"e": 12818,
"s": 12417,
"text": "In this post, we went through the concept of convolutions and discussed how they can be used to work with text. We also learned how to preprocess datasets from PyTorch and built a binary classification model for sentiment analysis. Despite being fooled by tricky examples, the model performs quite well. I hope you enjoyed reading this post and feel free to reach out to me if you have any questions!"
},
{
"code": null,
"e": 12988,
"s": 12818,
"text": "Britz, D. (2015). Understanding Convolutional Neural Networks for NLP. Retrieved from: http://www.wildml.com/2015/11/understanding-convolutional-neural-networks-for-nlp/"
},
{
"code": null,
"e": 13139,
"s": 12988,
"text": "Lopez, M. M., & Kalita, J. (2017). Deep Learning applied to NLP. arXiv preprint arXiv:1703.03091. Retrieved from: https://arxiv.org/pdf/1703.03091.pdf"
}
] |
Style Your Pandas DataFrames. Let’s create something more than plain... | by Soner Yıldırım | Towards Data Science | Data visualizations are great tools to infer meaningful results from plain data. They are widely-used in exploratory data analysis process in order to better understand the data at hand. What if we integrate a few visualization structures into pandas dataframes? I think it makes them look better than plain numbers. Furthermore, we may add some informative power on the display of a dataframe.
We can achieve this by using Style property of pandas dataframes. Style property returns a styler object which provides many options for formatting and displaying dataframes. In this post, we will walk through several examples and see how a dataframe can be displayed in different styles.
There are built-in style functions that we can use by adjusting parameters. We can also write our own style functions and pass it to the styler object which then implement styles before rendering.
There are two ways to use styler objects. One is element-wise styling that can be done with applymap method. The other one is column- or row-wise styling which requires to use apply method.
Let’s first create a sample dataframe with numpy and pandas.
df = pd.DataFrame({'A':np.linspace(1,8,8), 'B':np.random.random(8), 'C':np.random.randn(8), 'D':np.random.randn(8), 'E':np.random.randint(-5,5,8)})df.iloc[[1,5],[1,3]] = np.nandf
It looks plain and simple. We can write a function that displays some values with a different color based on a condition. For instance, we can choose to display negative values with red. Here is the function to accomplish this task.
def color_negative_values(val): color = 'red' if val < 0 else 'black' return 'color: %s' % color
Then we just pass it to applymap method.
df.style.applymap(color_negative_values)
Applymap executes element-wise operations whereas apply does it based on columns or rows. Here is a function that changes the background color of the max value in a column.
def color_max(s): is_max = s == s.max() return ['background-color: lightblue' if v else '' for v in is_max]
We just need to pass it to apply method.
df.style.apply(color_max)
We can also apply this function to rows by setting axis parameter as 1.
df.style.apply(color_max, axis=1)
Maximum value of each row is colored. They happened to be in column “A” in this case.
We can combine different style functions by chain operations.
df.style.applymap(color_negative_values).apply(color_max)
Style functions can be partially applied to a dataframe by selecting particular rows or columns using subset parameter.
df.style.apply(color_max, subset=['B','C'])
Color_max function is applied to columns “B” and “C”.
In addition to customized functions, pandas have some built-in style functions that might satisfy common tasks. For instance, highlight_null function marks missing values.
df.style.highlight_null(null_color='yellow')
We can change the color with null_color parameter. Another useful built-in function is background_gradient which marks cell proportional to the values with some help from seaborn.
import seaborn as snscm = sns.light_palette("green", as_cmap=True)df.style.background_gradient(cmap=cm)
The bigger the value, the darker the background color. Missing values are separated from the rest.
Highlight_max and highlight_min functions mark the maximum and minimum values in a column or row like our custom color_max function.
df.style.highlight_min(color='lightgreen', axis=1)
df.style.highlight_max()
Default value of axis parameter is 0 which does column-wise operations.
Set_properties function allows to combine multiple style selections.
df.style.set_properties(**{'background-color': 'lightblue', 'color': 'black', 'border-color': 'white'})
Another highly useful function is bar which plots bars over the cells whose lenghts are proportional to the values in the cells.
df.style.bar(color='lightgreen')
By using align parameter, we can show negative and positive values with different colors.
df.style.bar(align='mid', color=['red', 'lightgreen'])
The style functions we used here are pretty simple ones. However, we can also create more complex style functions that enhance the informative power of dataframes. We may want to use same styling on all the dataframes we work on. Pandas offers a way to transfer styles between dataframes.
We first save the style to a styler object.
style = df.style.applymap(color_negative_values).apply(color_max)style
Let’s create another sample dataframe to work on.
df2 = pd.DataFrame({'col1':np.random.random(8), 'col2':np.random.randn(8), 'col3':np.random.randint(-5,5,8)})df2
We can then create another styler object and use same styles saved in the previous styler object.
style2 = df2.stylestyle2.use(style.export())style2
We have covered
How to create custom styling functions and apply to dataframes
How to use built-in style functions
How to transfer styles from one styler object to another
There are other styling and formatting options available that can be accessed on the styling section of pandas user guide.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 567,
"s": 172,
"text": "Data visualizations are great tools to infer meaningful results from plain data. They are widely-used in exploratory data analysis process in order to better understand the data at hand. What if we integrate a few visualization structures into pandas dataframes? I think it makes them look better than plain numbers. Furthermore, we may add some informative power on the display of a dataframe."
},
{
"code": null,
"e": 856,
"s": 567,
"text": "We can achieve this by using Style property of pandas dataframes. Style property returns a styler object which provides many options for formatting and displaying dataframes. In this post, we will walk through several examples and see how a dataframe can be displayed in different styles."
},
{
"code": null,
"e": 1053,
"s": 856,
"text": "There are built-in style functions that we can use by adjusting parameters. We can also write our own style functions and pass it to the styler object which then implement styles before rendering."
},
{
"code": null,
"e": 1243,
"s": 1053,
"text": "There are two ways to use styler objects. One is element-wise styling that can be done with applymap method. The other one is column- or row-wise styling which requires to use apply method."
},
{
"code": null,
"e": 1304,
"s": 1243,
"text": "Let’s first create a sample dataframe with numpy and pandas."
},
{
"code": null,
"e": 1555,
"s": 1304,
"text": "df = pd.DataFrame({'A':np.linspace(1,8,8), 'B':np.random.random(8), 'C':np.random.randn(8), 'D':np.random.randn(8), 'E':np.random.randint(-5,5,8)})df.iloc[[1,5],[1,3]] = np.nandf"
},
{
"code": null,
"e": 1788,
"s": 1555,
"text": "It looks plain and simple. We can write a function that displays some values with a different color based on a condition. For instance, we can choose to display negative values with red. Here is the function to accomplish this task."
},
{
"code": null,
"e": 1887,
"s": 1788,
"text": "def color_negative_values(val): color = 'red' if val < 0 else 'black' return 'color: %s' % color"
},
{
"code": null,
"e": 1928,
"s": 1887,
"text": "Then we just pass it to applymap method."
},
{
"code": null,
"e": 1969,
"s": 1928,
"text": "df.style.applymap(color_negative_values)"
},
{
"code": null,
"e": 2142,
"s": 1969,
"text": "Applymap executes element-wise operations whereas apply does it based on columns or rows. Here is a function that changes the background color of the max value in a column."
},
{
"code": null,
"e": 2259,
"s": 2142,
"text": "def color_max(s): is_max = s == s.max() return ['background-color: lightblue' if v else '' for v in is_max]"
},
{
"code": null,
"e": 2300,
"s": 2259,
"text": "We just need to pass it to apply method."
},
{
"code": null,
"e": 2326,
"s": 2300,
"text": "df.style.apply(color_max)"
},
{
"code": null,
"e": 2398,
"s": 2326,
"text": "We can also apply this function to rows by setting axis parameter as 1."
},
{
"code": null,
"e": 2432,
"s": 2398,
"text": "df.style.apply(color_max, axis=1)"
},
{
"code": null,
"e": 2518,
"s": 2432,
"text": "Maximum value of each row is colored. They happened to be in column “A” in this case."
},
{
"code": null,
"e": 2580,
"s": 2518,
"text": "We can combine different style functions by chain operations."
},
{
"code": null,
"e": 2638,
"s": 2580,
"text": "df.style.applymap(color_negative_values).apply(color_max)"
},
{
"code": null,
"e": 2758,
"s": 2638,
"text": "Style functions can be partially applied to a dataframe by selecting particular rows or columns using subset parameter."
},
{
"code": null,
"e": 2802,
"s": 2758,
"text": "df.style.apply(color_max, subset=['B','C'])"
},
{
"code": null,
"e": 2856,
"s": 2802,
"text": "Color_max function is applied to columns “B” and “C”."
},
{
"code": null,
"e": 3028,
"s": 2856,
"text": "In addition to customized functions, pandas have some built-in style functions that might satisfy common tasks. For instance, highlight_null function marks missing values."
},
{
"code": null,
"e": 3073,
"s": 3028,
"text": "df.style.highlight_null(null_color='yellow')"
},
{
"code": null,
"e": 3253,
"s": 3073,
"text": "We can change the color with null_color parameter. Another useful built-in function is background_gradient which marks cell proportional to the values with some help from seaborn."
},
{
"code": null,
"e": 3357,
"s": 3253,
"text": "import seaborn as snscm = sns.light_palette(\"green\", as_cmap=True)df.style.background_gradient(cmap=cm)"
},
{
"code": null,
"e": 3456,
"s": 3357,
"text": "The bigger the value, the darker the background color. Missing values are separated from the rest."
},
{
"code": null,
"e": 3589,
"s": 3456,
"text": "Highlight_max and highlight_min functions mark the maximum and minimum values in a column or row like our custom color_max function."
},
{
"code": null,
"e": 3640,
"s": 3589,
"text": "df.style.highlight_min(color='lightgreen', axis=1)"
},
{
"code": null,
"e": 3665,
"s": 3640,
"text": "df.style.highlight_max()"
},
{
"code": null,
"e": 3737,
"s": 3665,
"text": "Default value of axis parameter is 0 which does column-wise operations."
},
{
"code": null,
"e": 3806,
"s": 3737,
"text": "Set_properties function allows to combine multiple style selections."
},
{
"code": null,
"e": 3962,
"s": 3806,
"text": "df.style.set_properties(**{'background-color': 'lightblue', 'color': 'black', 'border-color': 'white'})"
},
{
"code": null,
"e": 4091,
"s": 3962,
"text": "Another highly useful function is bar which plots bars over the cells whose lenghts are proportional to the values in the cells."
},
{
"code": null,
"e": 4124,
"s": 4091,
"text": "df.style.bar(color='lightgreen')"
},
{
"code": null,
"e": 4214,
"s": 4124,
"text": "By using align parameter, we can show negative and positive values with different colors."
},
{
"code": null,
"e": 4269,
"s": 4214,
"text": "df.style.bar(align='mid', color=['red', 'lightgreen'])"
},
{
"code": null,
"e": 4558,
"s": 4269,
"text": "The style functions we used here are pretty simple ones. However, we can also create more complex style functions that enhance the informative power of dataframes. We may want to use same styling on all the dataframes we work on. Pandas offers a way to transfer styles between dataframes."
},
{
"code": null,
"e": 4602,
"s": 4558,
"text": "We first save the style to a styler object."
},
{
"code": null,
"e": 4673,
"s": 4602,
"text": "style = df.style.applymap(color_negative_values).apply(color_max)style"
},
{
"code": null,
"e": 4723,
"s": 4673,
"text": "Let’s create another sample dataframe to work on."
},
{
"code": null,
"e": 4872,
"s": 4723,
"text": "df2 = pd.DataFrame({'col1':np.random.random(8), 'col2':np.random.randn(8), 'col3':np.random.randint(-5,5,8)})df2"
},
{
"code": null,
"e": 4970,
"s": 4872,
"text": "We can then create another styler object and use same styles saved in the previous styler object."
},
{
"code": null,
"e": 5021,
"s": 4970,
"text": "style2 = df2.stylestyle2.use(style.export())style2"
},
{
"code": null,
"e": 5037,
"s": 5021,
"text": "We have covered"
},
{
"code": null,
"e": 5100,
"s": 5037,
"text": "How to create custom styling functions and apply to dataframes"
},
{
"code": null,
"e": 5136,
"s": 5100,
"text": "How to use built-in style functions"
},
{
"code": null,
"e": 5193,
"s": 5136,
"text": "How to transfer styles from one styler object to another"
},
{
"code": null,
"e": 5316,
"s": 5193,
"text": "There are other styling and formatting options available that can be accessed on the styling section of pandas user guide."
}
] |
Deep Reinforcement Learning for Drones in 3D realistic environments | by Aqeel Anwar | Towards Data Science | A complete code to get you started with implementing Deep Reinforcement Learning in a realistically looking environment using Unreal Gaming Engine and Python.
Note 1: The Github repository DRLwithTL mentioned in the article has been outdated. Please use the following more detailed repository instead https://github.com/aqeelanwar/PEDRA
Note 2: A more detailed article on drone reinforcement learning can be found here
Last week, I made a GitHub repository public that contains a stand-alone detailed python code implementing deep reinforcement learning on a drone in a 3D simulated environment using Unreal Gaming Engine. I decided to cover a detailed documentation in this article. The 3D environments are made on Epic Unreal Gaming engine, and Python is used to interface with the environments and carry out Deep reinforcement learning using TensorFlow.
At the end of this article, you will have a working platform on your machine capable of implementing Deep Reinforcement Learning in a realistically looking environment for a Drone. You will be able to
Design your custom environments
Interface it with your Python code
Use/modify existing Python code for DRL
For this article, the underlying objective will be drone autonomous navigation. There are no start or end positions, rather the drone has to navigate as long as it can without colliding into obstacles. The code can be modified to any user-defined objective.
The complete simulation consists of three major parts
3D Simulation Platform — To create and run simulated environments
Interface Platform — To simulate drone physics and interface between Unreal and Python
DRL python code Platform — Contains the DRL code based on TensorFlow
There are multiple options to select each of these three platforms. But for this article, we will select the following
3D simulation Platform — Unreal Engine [1]
Interface Platform — AirSim [2]
DRL python code Platform — DRLwithTL GitHub repository [3]
The rest of the article will be divided into three steps
Step1 — Installing the platforms
Step2 — Running the python code
Step3 — Control/Modify the code parameters
It’s advisable to make a new virtual environment for this project and install the dependencies. Following steps can be taken to download get started with these platforms.
Clone the repository: The repository containing the DRL code can be cloned using
Clone the repository: The repository containing the DRL code can be cloned using
git clone https://github.com/aqeelanwar/DRLwithTL.git
2. Download Imagenet weights for Alexnet: The DNN when initialized uses Imagenet learned weights for AlexNet instead of random weights. This given the DNN a better starting point for training and help in convergence.
The following link can be used to download the imagenet.npy file.
Download imagenet.npy
Once downloaded, create a folder ‘models’ in DRLwithTL root folder, and place the downloaded file there.
models/imagenet.py
2. Install required packages: The provided requirements.txt file can be used to install all the required packages. Use the following command
cd DRLwithTLpip install -r requirements.txt
This will install the required packages in the activated python environment.
3. Install Epic Unreal Engine: You can follow the guidelines in the link below to install Unreal Engine on your platform
Instructions on installing Unreal engine
4. Install AirSim: AirSim is an open-source plugin for Unreal Engine developed by Microsoft for agents (drones and cars) with physically and visually realistic simulations. In order to interface between Python and the simulated environment, AirSim needs to be installed. It can be downloaded from the link below
Instructions on installing AirSim
Once everything is installed properly, we can move onto the next step of running the code.
Once you have the required packages and software downloaded and running, you can take the following steps to run the code
You can either manually create your environment using Unreal Engine or can download one of the sample environments from the link below and run it.
Download Environments
Following environments are available for download at the link above
Indoor Long Environment
Indoor Twist Environment
Indoor VanLeer Environment
Indoor Techno Environment
Indoor Pyramid Environment
Indoor FrogEyes Environment
The link above will help you download the packaged version of the environment for 64-bit windows. Run the executable file (.exe) to start the environment. If you are having trouble with running the environment, make sure your settings.json file in Documents/AirSim has been configured properly. You can try using the keys F, M, and backslash to change the camera view in the environment. Also, keys 1,2,3, and 0 can be used to look at FPV, segmentation map, depth map, and toggle sub-window views.
The RL parameters for the DRL simulation can be set using the provided config file and are explained in the last section.
cd DRLwithTL\configsnotepad config.cfg (# for Windows)
The DRL code can be started using the following command
cd DRLwithTLpython main.py
Running main.py carries out the following steps
Attempt to load the config fileAttempt to connect with the Unreal Engine (the indoor_long environment must be running for python to connect with the environment, otherwise connection refused warning will appear — The code won’t proceed unless a connection is established)Attempt to create two instances of the DNN (Double DQN is being used) and initialize them with the selected weights.Attempt to initialize Pygame screen for user interfaceStart the DRL algorithm
Attempt to load the config file
Attempt to connect with the Unreal Engine (the indoor_long environment must be running for python to connect with the environment, otherwise connection refused warning will appear — The code won’t proceed unless a connection is established)
Attempt to create two instances of the DNN (Double DQN is being used) and initialize them with the selected weights.
Attempt to initialize Pygame screen for user interface
Start the DRL algorithm
At this point, the drone can be seen moving around in the environment collecting data-points. The block diagram below shows the DRL algorithm used.
During simulation, RL parameters such as epsilon, learning rate, average Q values, loss, and return can be viewed on the tensorboard. The path of the tensorboard log files depends on the env_type, env_name, and train_type set in the config file and is given by
models/trained/<env_type>/<env_name>/Imagenet/ # Generic pathmodels/trained/Indoor/indoor_long/Imagenet/ # Example path
Once identified where the log files are stored, the following command can be used on the terminal to activate tensorboard.
cd models/trained/Indoor/indoor_long/Imagenet/tensorboard --logdir <train_type> # Generictensorboard --logdir e2e # Example
The terminal will display the local URL that can be opened up on any browser, and the tensorboard display will appear plotting the DRL parameters on run-time.
DRL is notorious to be data-hungry. For complex tasks such as drone autonomous navigation in a realistically looking environment using the front camera only, the simulation can take hours of training (typically from 8 to 12 hours on a GTX1080 GPU) before the DRL can converge. In the middle of the simulation, if you feel that you need to change a few DRL parameters, you can do that by using the PyGame screen that appears during your simulation. This can be done using the following steps
Change the config file to reflect the modifications (for example decrease the learning rate) and save it.Select the Pygame screen, and hit ‘backspace’. This will pause the simulation.Hit the ‘L’ key. This will load the updated parameters and will print it on the terminal.Hit the ‘backspace’ key to resume the simulation.
Change the config file to reflect the modifications (for example decrease the learning rate) and save it.
Select the Pygame screen, and hit ‘backspace’. This will pause the simulation.
Hit the ‘L’ key. This will load the updated parameters and will print it on the terminal.
Hit the ‘backspace’ key to resume the simulation.
Right now the simulation only updates the learning rate. Other variables can be updated too by editing the aux_function.py file for the module check_user_input at the following lines.
cfg variable at line 187 has all the updated parameters, you only need to assign it to the corresponding variable and return the value for it to be activated.
The code gives you the control to
Change the DRL configurationsChange the Deep Neural Network (DNN)Modify the drone action space
Change the DRL configurations
Change the Deep Neural Network (DNN)
Modify the drone action space
The provided config file can be used to set the DRL parameters before starting the simulation.
num_actions: Number of actions in the action space. The code uses perception-based action space [4] by dividing the camera frame into grid of sqrt(num_actions)*sqrt(num_actions).
train_type: Determines the number of layers to be trained in the DNN. The supported values are e2e, last4, last3, last2. More values can be de
wait_before_train: This parameter is used to set up the iteration at which the training should begin. The simulation collects this many data-points before it starts the training phase.
max_iters: Determines the maximum number of iterations used for DRL. The simulation stops when these many iterations have been completed.
buffer_len: is used to set the size of the experience replay buffer. The simulation keeps on collecting the data points and starts storing them in the replay buffer. Data-points are sampled from this replay buffer and used for training.
batch_size: Determines the batch size in one training iteration.
epsilon_saturation: Epsilon greedy method is used to transition from exploration to exploitation phase. When the number of iterations approaches this value, epsilon approaches 0.9 i.e. 90% of actions are predicted through the DNN (exploitation) and only 10% are random (exploration)
crash_threshold: This value is used along with the depth map to determine when the drone is considered to be virtually crashed. When the average depth to the closest obstacle in the center dynamic window on the depth map falls below this value, a reward of -1 is assigned to the data-tuple.
Q_clip: If set to True, the Q values are clipped if beyond a certain value. Helps in the convergence of DRL.
train_interval: This value determines how often training happens. For example, if set to 3, training happens after every 3 iterations.
update_target_interval: The simulation uses a Double DQN approach to help to converge DRL loss. update_target_interval determines how often the simulation shifts between the two Q-networks.
dropout_rate: Determines how often connections will be dropped out to avoid over-fitting.
switch_env_steps: Determines how often the drone changes its initial positions. These initial positions are set in environments/initial_positions.py under the corresponding environment name.
epsilon_model: linear or exponential
The DNN used for mapping the Q values to their states can be modified in the following python file.
network/network.py #Location of DNN
Different DNN topologies can be defined in this python file as a class. The code comes with three different versions of the modified AlexNet network. More networks can be defined according to the user needs if required. Once a new network is defined, netowork/agent.py file can be modified to use the required network on line 30 as shown below
The current version of the code supports perception-based action space. Changing the num_actions parameter in the config file changes the number of bins the front-facing camera is divided into.
If an entirely different type of action space needs to be used, the user can define it by modifying the following module
Module: take_actionLocation: network/agent.py
If modified, this module should be able to map the action number (say 0,1, 2, ..., num_actions) to a corresponding yaw and pitch value of the drone.
This article was aimed at getting you started with a working platform for a Deep reinforcement learning platform on a realistic 3D environment. The article also mentions the parts of codes that can be modified according to user needs. The complete code in working can be seen in paper [4].
https://www.unrealengine.comhttps://github.com/microsoft/airsimhttps://github.com/aqeelanwar/DRLwithTL.githttp://arxiv.org/abs/1910.05547
https://www.unrealengine.com
https://github.com/microsoft/airsim
https://github.com/aqeelanwar/DRLwithTL.git
http://arxiv.org/abs/1910.05547
If this article was helpful to you, feel free to clap, share and respond to it. If want to learn more about Machine Learning and Data Science, follow me @Aqeel Anwar or connect with me on LinkedIn. | [
{
"code": null,
"e": 331,
"s": 172,
"text": "A complete code to get you started with implementing Deep Reinforcement Learning in a realistically looking environment using Unreal Gaming Engine and Python."
},
{
"code": null,
"e": 509,
"s": 331,
"text": "Note 1: The Github repository DRLwithTL mentioned in the article has been outdated. Please use the following more detailed repository instead https://github.com/aqeelanwar/PEDRA"
},
{
"code": null,
"e": 591,
"s": 509,
"text": "Note 2: A more detailed article on drone reinforcement learning can be found here"
},
{
"code": null,
"e": 1029,
"s": 591,
"text": "Last week, I made a GitHub repository public that contains a stand-alone detailed python code implementing deep reinforcement learning on a drone in a 3D simulated environment using Unreal Gaming Engine. I decided to cover a detailed documentation in this article. The 3D environments are made on Epic Unreal Gaming engine, and Python is used to interface with the environments and carry out Deep reinforcement learning using TensorFlow."
},
{
"code": null,
"e": 1230,
"s": 1029,
"text": "At the end of this article, you will have a working platform on your machine capable of implementing Deep Reinforcement Learning in a realistically looking environment for a Drone. You will be able to"
},
{
"code": null,
"e": 1262,
"s": 1230,
"text": "Design your custom environments"
},
{
"code": null,
"e": 1297,
"s": 1262,
"text": "Interface it with your Python code"
},
{
"code": null,
"e": 1337,
"s": 1297,
"text": "Use/modify existing Python code for DRL"
},
{
"code": null,
"e": 1595,
"s": 1337,
"text": "For this article, the underlying objective will be drone autonomous navigation. There are no start or end positions, rather the drone has to navigate as long as it can without colliding into obstacles. The code can be modified to any user-defined objective."
},
{
"code": null,
"e": 1649,
"s": 1595,
"text": "The complete simulation consists of three major parts"
},
{
"code": null,
"e": 1715,
"s": 1649,
"text": "3D Simulation Platform — To create and run simulated environments"
},
{
"code": null,
"e": 1802,
"s": 1715,
"text": "Interface Platform — To simulate drone physics and interface between Unreal and Python"
},
{
"code": null,
"e": 1871,
"s": 1802,
"text": "DRL python code Platform — Contains the DRL code based on TensorFlow"
},
{
"code": null,
"e": 1990,
"s": 1871,
"text": "There are multiple options to select each of these three platforms. But for this article, we will select the following"
},
{
"code": null,
"e": 2033,
"s": 1990,
"text": "3D simulation Platform — Unreal Engine [1]"
},
{
"code": null,
"e": 2065,
"s": 2033,
"text": "Interface Platform — AirSim [2]"
},
{
"code": null,
"e": 2124,
"s": 2065,
"text": "DRL python code Platform — DRLwithTL GitHub repository [3]"
},
{
"code": null,
"e": 2181,
"s": 2124,
"text": "The rest of the article will be divided into three steps"
},
{
"code": null,
"e": 2214,
"s": 2181,
"text": "Step1 — Installing the platforms"
},
{
"code": null,
"e": 2246,
"s": 2214,
"text": "Step2 — Running the python code"
},
{
"code": null,
"e": 2289,
"s": 2246,
"text": "Step3 — Control/Modify the code parameters"
},
{
"code": null,
"e": 2460,
"s": 2289,
"text": "It’s advisable to make a new virtual environment for this project and install the dependencies. Following steps can be taken to download get started with these platforms."
},
{
"code": null,
"e": 2541,
"s": 2460,
"text": "Clone the repository: The repository containing the DRL code can be cloned using"
},
{
"code": null,
"e": 2622,
"s": 2541,
"text": "Clone the repository: The repository containing the DRL code can be cloned using"
},
{
"code": null,
"e": 2676,
"s": 2622,
"text": "git clone https://github.com/aqeelanwar/DRLwithTL.git"
},
{
"code": null,
"e": 2893,
"s": 2676,
"text": "2. Download Imagenet weights for Alexnet: The DNN when initialized uses Imagenet learned weights for AlexNet instead of random weights. This given the DNN a better starting point for training and help in convergence."
},
{
"code": null,
"e": 2959,
"s": 2893,
"text": "The following link can be used to download the imagenet.npy file."
},
{
"code": null,
"e": 2981,
"s": 2959,
"text": "Download imagenet.npy"
},
{
"code": null,
"e": 3086,
"s": 2981,
"text": "Once downloaded, create a folder ‘models’ in DRLwithTL root folder, and place the downloaded file there."
},
{
"code": null,
"e": 3105,
"s": 3086,
"text": "models/imagenet.py"
},
{
"code": null,
"e": 3246,
"s": 3105,
"text": "2. Install required packages: The provided requirements.txt file can be used to install all the required packages. Use the following command"
},
{
"code": null,
"e": 3290,
"s": 3246,
"text": "cd DRLwithTLpip install -r requirements.txt"
},
{
"code": null,
"e": 3367,
"s": 3290,
"text": "This will install the required packages in the activated python environment."
},
{
"code": null,
"e": 3488,
"s": 3367,
"text": "3. Install Epic Unreal Engine: You can follow the guidelines in the link below to install Unreal Engine on your platform"
},
{
"code": null,
"e": 3529,
"s": 3488,
"text": "Instructions on installing Unreal engine"
},
{
"code": null,
"e": 3841,
"s": 3529,
"text": "4. Install AirSim: AirSim is an open-source plugin for Unreal Engine developed by Microsoft for agents (drones and cars) with physically and visually realistic simulations. In order to interface between Python and the simulated environment, AirSim needs to be installed. It can be downloaded from the link below"
},
{
"code": null,
"e": 3875,
"s": 3841,
"text": "Instructions on installing AirSim"
},
{
"code": null,
"e": 3966,
"s": 3875,
"text": "Once everything is installed properly, we can move onto the next step of running the code."
},
{
"code": null,
"e": 4088,
"s": 3966,
"text": "Once you have the required packages and software downloaded and running, you can take the following steps to run the code"
},
{
"code": null,
"e": 4235,
"s": 4088,
"text": "You can either manually create your environment using Unreal Engine or can download one of the sample environments from the link below and run it."
},
{
"code": null,
"e": 4257,
"s": 4235,
"text": "Download Environments"
},
{
"code": null,
"e": 4325,
"s": 4257,
"text": "Following environments are available for download at the link above"
},
{
"code": null,
"e": 4349,
"s": 4325,
"text": "Indoor Long Environment"
},
{
"code": null,
"e": 4374,
"s": 4349,
"text": "Indoor Twist Environment"
},
{
"code": null,
"e": 4401,
"s": 4374,
"text": "Indoor VanLeer Environment"
},
{
"code": null,
"e": 4427,
"s": 4401,
"text": "Indoor Techno Environment"
},
{
"code": null,
"e": 4454,
"s": 4427,
"text": "Indoor Pyramid Environment"
},
{
"code": null,
"e": 4482,
"s": 4454,
"text": "Indoor FrogEyes Environment"
},
{
"code": null,
"e": 4980,
"s": 4482,
"text": "The link above will help you download the packaged version of the environment for 64-bit windows. Run the executable file (.exe) to start the environment. If you are having trouble with running the environment, make sure your settings.json file in Documents/AirSim has been configured properly. You can try using the keys F, M, and backslash to change the camera view in the environment. Also, keys 1,2,3, and 0 can be used to look at FPV, segmentation map, depth map, and toggle sub-window views."
},
{
"code": null,
"e": 5102,
"s": 4980,
"text": "The RL parameters for the DRL simulation can be set using the provided config file and are explained in the last section."
},
{
"code": null,
"e": 5172,
"s": 5102,
"text": "cd DRLwithTL\\configsnotepad config.cfg (# for Windows)"
},
{
"code": null,
"e": 5228,
"s": 5172,
"text": "The DRL code can be started using the following command"
},
{
"code": null,
"e": 5255,
"s": 5228,
"text": "cd DRLwithTLpython main.py"
},
{
"code": null,
"e": 5303,
"s": 5255,
"text": "Running main.py carries out the following steps"
},
{
"code": null,
"e": 5768,
"s": 5303,
"text": "Attempt to load the config fileAttempt to connect with the Unreal Engine (the indoor_long environment must be running for python to connect with the environment, otherwise connection refused warning will appear — The code won’t proceed unless a connection is established)Attempt to create two instances of the DNN (Double DQN is being used) and initialize them with the selected weights.Attempt to initialize Pygame screen for user interfaceStart the DRL algorithm"
},
{
"code": null,
"e": 5800,
"s": 5768,
"text": "Attempt to load the config file"
},
{
"code": null,
"e": 6041,
"s": 5800,
"text": "Attempt to connect with the Unreal Engine (the indoor_long environment must be running for python to connect with the environment, otherwise connection refused warning will appear — The code won’t proceed unless a connection is established)"
},
{
"code": null,
"e": 6158,
"s": 6041,
"text": "Attempt to create two instances of the DNN (Double DQN is being used) and initialize them with the selected weights."
},
{
"code": null,
"e": 6213,
"s": 6158,
"text": "Attempt to initialize Pygame screen for user interface"
},
{
"code": null,
"e": 6237,
"s": 6213,
"text": "Start the DRL algorithm"
},
{
"code": null,
"e": 6385,
"s": 6237,
"text": "At this point, the drone can be seen moving around in the environment collecting data-points. The block diagram below shows the DRL algorithm used."
},
{
"code": null,
"e": 6646,
"s": 6385,
"text": "During simulation, RL parameters such as epsilon, learning rate, average Q values, loss, and return can be viewed on the tensorboard. The path of the tensorboard log files depends on the env_type, env_name, and train_type set in the config file and is given by"
},
{
"code": null,
"e": 6773,
"s": 6646,
"text": "models/trained/<env_type>/<env_name>/Imagenet/ # Generic pathmodels/trained/Indoor/indoor_long/Imagenet/ # Example path"
},
{
"code": null,
"e": 6896,
"s": 6773,
"text": "Once identified where the log files are stored, the following command can be used on the terminal to activate tensorboard."
},
{
"code": null,
"e": 7059,
"s": 6896,
"text": "cd models/trained/Indoor/indoor_long/Imagenet/tensorboard --logdir <train_type> # Generictensorboard --logdir e2e # Example"
},
{
"code": null,
"e": 7218,
"s": 7059,
"text": "The terminal will display the local URL that can be opened up on any browser, and the tensorboard display will appear plotting the DRL parameters on run-time."
},
{
"code": null,
"e": 7709,
"s": 7218,
"text": "DRL is notorious to be data-hungry. For complex tasks such as drone autonomous navigation in a realistically looking environment using the front camera only, the simulation can take hours of training (typically from 8 to 12 hours on a GTX1080 GPU) before the DRL can converge. In the middle of the simulation, if you feel that you need to change a few DRL parameters, you can do that by using the PyGame screen that appears during your simulation. This can be done using the following steps"
},
{
"code": null,
"e": 8031,
"s": 7709,
"text": "Change the config file to reflect the modifications (for example decrease the learning rate) and save it.Select the Pygame screen, and hit ‘backspace’. This will pause the simulation.Hit the ‘L’ key. This will load the updated parameters and will print it on the terminal.Hit the ‘backspace’ key to resume the simulation."
},
{
"code": null,
"e": 8137,
"s": 8031,
"text": "Change the config file to reflect the modifications (for example decrease the learning rate) and save it."
},
{
"code": null,
"e": 8216,
"s": 8137,
"text": "Select the Pygame screen, and hit ‘backspace’. This will pause the simulation."
},
{
"code": null,
"e": 8306,
"s": 8216,
"text": "Hit the ‘L’ key. This will load the updated parameters and will print it on the terminal."
},
{
"code": null,
"e": 8356,
"s": 8306,
"text": "Hit the ‘backspace’ key to resume the simulation."
},
{
"code": null,
"e": 8540,
"s": 8356,
"text": "Right now the simulation only updates the learning rate. Other variables can be updated too by editing the aux_function.py file for the module check_user_input at the following lines."
},
{
"code": null,
"e": 8699,
"s": 8540,
"text": "cfg variable at line 187 has all the updated parameters, you only need to assign it to the corresponding variable and return the value for it to be activated."
},
{
"code": null,
"e": 8733,
"s": 8699,
"text": "The code gives you the control to"
},
{
"code": null,
"e": 8828,
"s": 8733,
"text": "Change the DRL configurationsChange the Deep Neural Network (DNN)Modify the drone action space"
},
{
"code": null,
"e": 8858,
"s": 8828,
"text": "Change the DRL configurations"
},
{
"code": null,
"e": 8895,
"s": 8858,
"text": "Change the Deep Neural Network (DNN)"
},
{
"code": null,
"e": 8925,
"s": 8895,
"text": "Modify the drone action space"
},
{
"code": null,
"e": 9020,
"s": 8925,
"text": "The provided config file can be used to set the DRL parameters before starting the simulation."
},
{
"code": null,
"e": 9199,
"s": 9020,
"text": "num_actions: Number of actions in the action space. The code uses perception-based action space [4] by dividing the camera frame into grid of sqrt(num_actions)*sqrt(num_actions)."
},
{
"code": null,
"e": 9342,
"s": 9199,
"text": "train_type: Determines the number of layers to be trained in the DNN. The supported values are e2e, last4, last3, last2. More values can be de"
},
{
"code": null,
"e": 9527,
"s": 9342,
"text": "wait_before_train: This parameter is used to set up the iteration at which the training should begin. The simulation collects this many data-points before it starts the training phase."
},
{
"code": null,
"e": 9665,
"s": 9527,
"text": "max_iters: Determines the maximum number of iterations used for DRL. The simulation stops when these many iterations have been completed."
},
{
"code": null,
"e": 9902,
"s": 9665,
"text": "buffer_len: is used to set the size of the experience replay buffer. The simulation keeps on collecting the data points and starts storing them in the replay buffer. Data-points are sampled from this replay buffer and used for training."
},
{
"code": null,
"e": 9967,
"s": 9902,
"text": "batch_size: Determines the batch size in one training iteration."
},
{
"code": null,
"e": 10250,
"s": 9967,
"text": "epsilon_saturation: Epsilon greedy method is used to transition from exploration to exploitation phase. When the number of iterations approaches this value, epsilon approaches 0.9 i.e. 90% of actions are predicted through the DNN (exploitation) and only 10% are random (exploration)"
},
{
"code": null,
"e": 10541,
"s": 10250,
"text": "crash_threshold: This value is used along with the depth map to determine when the drone is considered to be virtually crashed. When the average depth to the closest obstacle in the center dynamic window on the depth map falls below this value, a reward of -1 is assigned to the data-tuple."
},
{
"code": null,
"e": 10650,
"s": 10541,
"text": "Q_clip: If set to True, the Q values are clipped if beyond a certain value. Helps in the convergence of DRL."
},
{
"code": null,
"e": 10785,
"s": 10650,
"text": "train_interval: This value determines how often training happens. For example, if set to 3, training happens after every 3 iterations."
},
{
"code": null,
"e": 10975,
"s": 10785,
"text": "update_target_interval: The simulation uses a Double DQN approach to help to converge DRL loss. update_target_interval determines how often the simulation shifts between the two Q-networks."
},
{
"code": null,
"e": 11065,
"s": 10975,
"text": "dropout_rate: Determines how often connections will be dropped out to avoid over-fitting."
},
{
"code": null,
"e": 11256,
"s": 11065,
"text": "switch_env_steps: Determines how often the drone changes its initial positions. These initial positions are set in environments/initial_positions.py under the corresponding environment name."
},
{
"code": null,
"e": 11293,
"s": 11256,
"text": "epsilon_model: linear or exponential"
},
{
"code": null,
"e": 11393,
"s": 11293,
"text": "The DNN used for mapping the Q values to their states can be modified in the following python file."
},
{
"code": null,
"e": 11435,
"s": 11393,
"text": "network/network.py #Location of DNN"
},
{
"code": null,
"e": 11779,
"s": 11435,
"text": "Different DNN topologies can be defined in this python file as a class. The code comes with three different versions of the modified AlexNet network. More networks can be defined according to the user needs if required. Once a new network is defined, netowork/agent.py file can be modified to use the required network on line 30 as shown below"
},
{
"code": null,
"e": 11973,
"s": 11779,
"text": "The current version of the code supports perception-based action space. Changing the num_actions parameter in the config file changes the number of bins the front-facing camera is divided into."
},
{
"code": null,
"e": 12094,
"s": 11973,
"text": "If an entirely different type of action space needs to be used, the user can define it by modifying the following module"
},
{
"code": null,
"e": 12144,
"s": 12094,
"text": "Module: take_actionLocation: network/agent.py"
},
{
"code": null,
"e": 12293,
"s": 12144,
"text": "If modified, this module should be able to map the action number (say 0,1, 2, ..., num_actions) to a corresponding yaw and pitch value of the drone."
},
{
"code": null,
"e": 12583,
"s": 12293,
"text": "This article was aimed at getting you started with a working platform for a Deep reinforcement learning platform on a realistic 3D environment. The article also mentions the parts of codes that can be modified according to user needs. The complete code in working can be seen in paper [4]."
},
{
"code": null,
"e": 12721,
"s": 12583,
"text": "https://www.unrealengine.comhttps://github.com/microsoft/airsimhttps://github.com/aqeelanwar/DRLwithTL.githttp://arxiv.org/abs/1910.05547"
},
{
"code": null,
"e": 12750,
"s": 12721,
"text": "https://www.unrealengine.com"
},
{
"code": null,
"e": 12786,
"s": 12750,
"text": "https://github.com/microsoft/airsim"
},
{
"code": null,
"e": 12830,
"s": 12786,
"text": "https://github.com/aqeelanwar/DRLwithTL.git"
},
{
"code": null,
"e": 12862,
"s": 12830,
"text": "http://arxiv.org/abs/1910.05547"
}
] |
Regular Expression \E Metacharacter in Java. | The subexpression/metacharacter “\E” ends the quoting begun with \Q. i.e. you can escape metacharacters in the regular expressions by placing them in between \Q and \E. For example, the expression [aeiou] matches the strings with vowel letters in it.
Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
public static void main( String args[] ) {
String regex = "[aeiou]";
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
}else {
System.out.println("Match not occurred");
}
}
}
Enter input string:
sample
Match occurred
But, if you use the same expression with in \Q and \E as \Q[aeiou]\E It matches the same sequence of characters “[aeiou]” in the given string. In short the meta characters loses their meaning and will be treated as normal characters.
Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
public static void main( String args[] ) {
String regex = "\\Q[aeiou]\\E";
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
Enter input string:
sample
Match not occurred
Enter input string:
The letters [aeiou] are vowels in English alphabet
Match occurred | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "The subexpression/metacharacter “\\E” ends the quoting begun with \\Q. i.e. you can escape metacharacters in the regular expressions by placing them in between \\Q and \\E. For example, the expression [aeiou] matches the strings with vowel letters in it."
},
{
"code": null,
"e": 1324,
"s": 1313,
"text": " Live Demo"
},
{
"code": null,
"e": 1934,
"s": 1324,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class SampleProgram {\n public static void main( String args[] ) {\n String regex = \"[aeiou]\";\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string: \");\n String input = sc.nextLine();\n //Creating a Pattern object\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(input);\n if(matcher.find()) {\n System.out.println(\"Match occurred\");\n }else {\n System.out.println(\"Match not occurred\");\n }\n }\n}"
},
{
"code": null,
"e": 1976,
"s": 1934,
"text": "Enter input string:\nsample\nMatch occurred"
},
{
"code": null,
"e": 2210,
"s": 1976,
"text": "But, if you use the same expression with in \\Q and \\E as \\Q[aeiou]\\E It matches the same sequence of characters “[aeiou]” in the given string. In short the meta characters loses their meaning and will be treated as normal characters."
},
{
"code": null,
"e": 2221,
"s": 2210,
"text": " Live Demo"
},
{
"code": null,
"e": 2838,
"s": 2221,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class SampleProgram {\n public static void main( String args[] ) {\n String regex = \"\\\\Q[aeiou]\\\\E\";\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string: \");\n String input = sc.nextLine();\n //Creating a Pattern object\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(input);\n if(matcher.find()) {\n System.out.println(\"Match occurred\");\n } else {\n System.out.println(\"Match not occurred\");\n }\n }\n}"
},
{
"code": null,
"e": 2884,
"s": 2838,
"text": "Enter input string:\nsample\nMatch not occurred"
},
{
"code": null,
"e": 2970,
"s": 2884,
"text": "Enter input string:\nThe letters [aeiou] are vowels in English alphabet\nMatch occurred"
}
] |
A very brief introduction to Fuzzy Logic and Fuzzy Systems | by Carmel Gafa | Towards Data Science | Many tasks are simple for humans, but they create a continuous challenge for machines. Examples of such systems include walking through a cluttered environment, lifting fragile objects or parking a car. The ability of humans to deal with vague and imprecise data makes such tasks easy for us. Therefore if we aim to replicate the control actions of a human operator, we must be able to model the activities of the operator and not of the plant itself. Our model must be built so that it is capable of dealing with vague information.
Fuzzy logic-based systems do precisely that; they excel where systems are particularly complex and have been used successfully in many applications ranging from voice and handwriting recognition to subway train speed control.
This article focuses on the basic ideas of fuzzy sets and systems.
Classical logic is based on the crisp set, where a group of distinct objects are considered as a collection. For example, the colours white and red are both separate objects in their own right, but they can be regarded as a collection using the notation {red, white}. Crisp sets are, by convention designated a capital letter hence the above example can be described by,
F = {red, white}
A crisp subset can be defined from a more extensive set where the elements of the set belong to the subset according to some condition. For example, set A can be defined as the set of numbers that are greater or equal to 4 and smaller or equal to 12. This statement can be described using the following notation:
A ={i | i is an integer and 4<= i <= 12}
A graphical representation of the subset above is possible if we introduce the notion of the characteristic or indicator function of a set, that is, in this case, the function defined over the set of integers, that we shall call X, that indicates the membership of elements in subset A in X. This is achieved by assigning a value of 1 to the elements of X in A, and a value of 0 to the elements of X not in A. In our example, therefore, the indicator function for this set is:
Graphically this can be displayed as follows:
The intersection of two sets is the set containing all elements of that are common to both sets. The union of two sets is the set containing all elements that are in either of the sets.The negation of a set A is the set containing all elements that are not in A.
Fuzzy sets were introduced by Lotfi Zadeh (1921–2017) in 1965.
Unlike crisp sets, a fuzzy set allows partial belonging to a set, that is defined by a degree of membership, denoted by μ, that can take any value from 0 (element does not belong at all in the set) to 1 (element belongs fully to the set).
It is evident that if we remove all the values of belonging except from 0 and 1, the fuzzy set will collapse to a crisp set that was described in the previous section.
The membership function of the set is the relationship between the elements of the set and their degree-of-belonging. An illustration of how membership functions can be applied to temperature is shown below.
In the example above, the fuzzy sets describe temperatures of an engine ranging from very cold to very hot. The value, μ, is the amount of membership in the set. One can notice, for example, that at a temperature of 80 degrees, the engine can be described as being hot to a factor of 0.8, and very hot to a factor of 0.2.
In the previous section, the union, intersection and negation operators of crisp sets were discussed as they provide a way to express conjunction and disjunction (and/or) that are pivotal to reasoning.
The most common method of computing the union of two fuzzy sets is by applying the maximum operator on the sets. Other methods do exist, including the use of the product operator on the two sets. Similarly, the most common method of computing the intersection of two fuzzy sets is by applying the minimum operator on the sets. The complement of a fuzzy set is calculated by subtracting the set membership function from 1.
One crucial observation is that an element can have a degree of belonging both in a set and in the complement of the set. Hence, as an example, element x can be both in A and also in ‘not-A’.
A fuzzy system is a repository of fuzzy expert knowledge that can reason data in vague terms instead of precise Boolean logic. The expert knowledge is a collection of fuzzy membership functions and a set of fuzzy rules, known as the rule-base, having the form:
IF (conditions are fulfilled) THEN (consequences are inferred)
The basic configuration of a fuzzy system is shown below:
A typical fuzzy system can be split into four main parts, namely a fuzzifier, a knowledge base, an inference engine and a defuzzifier;
The fuzzifier maps a real crisp input to a fuzzy function, therefore determining the ‘degree of membership’ of the input to a vague concept. In a number of controllers, the values of the input variables are mapped to the range of values of the corresponding universe of discourse. The range and resolution of input-fuzzy sets and their effect on the fuzzification process are considered as factors affecting the overall performance of the controller.
The knowledge base comprises the knowledge of the application domain and the attendant control goals. It can be split into a database of definitions used to express linguistic control rules in the controller, and a rule base that describes the knowledge held by the experts of the domain. Intuitively, the knowledge base is the core element of a fuzzy controller as it will contain all the information necessary to accomplish its execution tasks. Various researchers have applied techniques to fine-tune a fuzzy controller’s knowledge base, many using other AI disciplines such as Genetic Algorithms or neural networks.
The Inference Engine provides the decision making logic of the controller. It deduces the fuzzy control actions by employing fuzzy implications and fuzzy rules of inference. In many aspects, it can be viewed as an emulation of human decision making.
The Defuzzification process converts fuzzy control values into crisp quantities, that is, it links a single point to a fuzzy set, given that the point belongs to the support of the fuzzy set. There are many defuzzification techniques, the most famous being the centre-of-area or centre-of-gravity.
Other defuzzification methods include first of maxima and mean of maxima.
Several inferencing models use fuzzy sets to reason the outputs of a system given inputs. One of the most popular methods was devised by Professor Abe Mamdani that used fuzzy sets to control a steam engine. Another popular model was developed by Professor Tomohiro Takagi and Professor Michio Sugeno.
In Mamdani inferencing, the antecedents and consequents of a fuzzy rule are fuzzy sets. The inference is based on Generalised Modus Ponens, which states that the degree of truth of the consequent of a fuzzy rule is the degree of truth of the antecedent. In the case where more than one antecedent clause is present, the individual degrees of membership are joined using a min t-norm operator. If the fuzzy system contains several rules, their output is combined using a max s-norm operator. Defuzzification is necessary so that the consequent action can be expressed in terms of a crisp value. A graphical representation of this process is shown below.
In the Takagi-Sugeno inferencing model, the consequents are functions that map crisp input values to the rule’s crisp output. Hence fuzzy rules are of the form:
IF x IS X and y IS Y THEN z=f(x,y)
where f is generally a linear function in X and Y. In contrast to Mamdani fuzzy systems, the rules are not combined using a max -operator but are combined by finding a weighted average, where the weight of a given rule is the degree of membership of its antecedent. Therefore Takagi-Sugeno systems do not require any defuzzification.
In this section, a simple example system will be constructed and executed to visualise the design and execution of a fuzzy inference system. The hypothetical system considered here controls the speed of a fan has according to the environment’s temperature and humidity. Therefore, our system consists of two inputs, temperature and humidity and a single output, that is the fan speed.
The first step in the design of our system is to define fuzzy sets to describe the input and output variables. For simplicity’s sake each variable will be characterised by three fuzzy-sets, namely:
Temperature: Cold, Medium, HotHumidity: Dry, Normal, WetFan Speed: Slow, Moderate, Fast
The diagram below shows a graphical representation of the input and output variables of our system and their respective sets.
It can be noted that triangular sets were used to describe most of the sets of this system; however, ‘normal’ humidity is specified using a trapezoidal set. Fuzzy sets reflect the knowledge is the user designing the system, so they can take a wide variety of shapes.
Note that the output was described using fuzzy sets as well; therefore the system that is being considered is a Mamdani-type, that links fuzzy sets related to the inputs of the system to fuzzy sets associated with the output of the system using fuzzy rules.
A total of nine rules are used to describe the knowledge necessary to operate our fan:
If Temperature is Cold and Humidity is Dry Then Fan Speed is SlowIf Temperature is Medium and Humidity is Dry Then Fan Speed is SlowIf Temperature is Cold and Humidity is Normal Then Fan Speed is SlowIf Temperature is Hot and Humidity is Dry Then Fan Speed is ModerateIf Temperature is Medium and Humidity is Normal Then Fan Speed is ModerateIf Temperature is Cold and Humidity is Wet Then Fan Speed is ModerateIf Temperature is Hot and Humidity is Normal Then Fan Speed is FastIf Temperature is Hot and Humidity is Wet Then Fan Speed is FastIf Temperature is Medium and Humidity is Wet Then Fan Speed is Fast
These rules can be visualised if we use a combined fuzzy rule base, that is a grid where the input-fuzzy sets occupy the edges so that each cell in the grid defines a rule. The following diagram shows the rule base for this system.
The following steps take place when an input combination is fed to the system, let us as an example say that we have a temperature of 18 degrees and humidity of 60%:
The degree of membership for each set of the input variables is determined. Hence we can say that a temperature of 18 degrees is
0.48 Cold0.29 Medium0.00 Hot
and humidity of 60% is
0.0 Wet1.0 Normal0.0 Dry
With this input combination, two rules are fired with a degree higher than zero, as can be seen in the updated fuzzy rule base below:
And therefore our fuzzy output will consist of the speed Slow, that has activation of 0.48 and Moderate that has 0.29 activation. The combined effect of the two rules or the fuzzy output of the system is displayed below:
The output set is finally defuzzified using centre-of-gravity defuzzification and a crisp value of 36.814 is obtained to drive the fan.
In this article, a brief introduction to fuzzy sets and fuzzy inferencing was presented. It is shown how control of systems can be achieved using linguistic terms to represent human knowledge. In the next article, a fuzzy inference system will be constructed using python from scratch. | [
{
"code": null,
"e": 580,
"s": 47,
"text": "Many tasks are simple for humans, but they create a continuous challenge for machines. Examples of such systems include walking through a cluttered environment, lifting fragile objects or parking a car. The ability of humans to deal with vague and imprecise data makes such tasks easy for us. Therefore if we aim to replicate the control actions of a human operator, we must be able to model the activities of the operator and not of the plant itself. Our model must be built so that it is capable of dealing with vague information."
},
{
"code": null,
"e": 806,
"s": 580,
"text": "Fuzzy logic-based systems do precisely that; they excel where systems are particularly complex and have been used successfully in many applications ranging from voice and handwriting recognition to subway train speed control."
},
{
"code": null,
"e": 873,
"s": 806,
"text": "This article focuses on the basic ideas of fuzzy sets and systems."
},
{
"code": null,
"e": 1244,
"s": 873,
"text": "Classical logic is based on the crisp set, where a group of distinct objects are considered as a collection. For example, the colours white and red are both separate objects in their own right, but they can be regarded as a collection using the notation {red, white}. Crisp sets are, by convention designated a capital letter hence the above example can be described by,"
},
{
"code": null,
"e": 1261,
"s": 1244,
"text": "F = {red, white}"
},
{
"code": null,
"e": 1574,
"s": 1261,
"text": "A crisp subset can be defined from a more extensive set where the elements of the set belong to the subset according to some condition. For example, set A can be defined as the set of numbers that are greater or equal to 4 and smaller or equal to 12. This statement can be described using the following notation:"
},
{
"code": null,
"e": 1615,
"s": 1574,
"text": "A ={i | i is an integer and 4<= i <= 12}"
},
{
"code": null,
"e": 2092,
"s": 1615,
"text": "A graphical representation of the subset above is possible if we introduce the notion of the characteristic or indicator function of a set, that is, in this case, the function defined over the set of integers, that we shall call X, that indicates the membership of elements in subset A in X. This is achieved by assigning a value of 1 to the elements of X in A, and a value of 0 to the elements of X not in A. In our example, therefore, the indicator function for this set is:"
},
{
"code": null,
"e": 2138,
"s": 2092,
"text": "Graphically this can be displayed as follows:"
},
{
"code": null,
"e": 2401,
"s": 2138,
"text": "The intersection of two sets is the set containing all elements of that are common to both sets. The union of two sets is the set containing all elements that are in either of the sets.The negation of a set A is the set containing all elements that are not in A."
},
{
"code": null,
"e": 2464,
"s": 2401,
"text": "Fuzzy sets were introduced by Lotfi Zadeh (1921–2017) in 1965."
},
{
"code": null,
"e": 2703,
"s": 2464,
"text": "Unlike crisp sets, a fuzzy set allows partial belonging to a set, that is defined by a degree of membership, denoted by μ, that can take any value from 0 (element does not belong at all in the set) to 1 (element belongs fully to the set)."
},
{
"code": null,
"e": 2871,
"s": 2703,
"text": "It is evident that if we remove all the values of belonging except from 0 and 1, the fuzzy set will collapse to a crisp set that was described in the previous section."
},
{
"code": null,
"e": 3079,
"s": 2871,
"text": "The membership function of the set is the relationship between the elements of the set and their degree-of-belonging. An illustration of how membership functions can be applied to temperature is shown below."
},
{
"code": null,
"e": 3401,
"s": 3079,
"text": "In the example above, the fuzzy sets describe temperatures of an engine ranging from very cold to very hot. The value, μ, is the amount of membership in the set. One can notice, for example, that at a temperature of 80 degrees, the engine can be described as being hot to a factor of 0.8, and very hot to a factor of 0.2."
},
{
"code": null,
"e": 3603,
"s": 3401,
"text": "In the previous section, the union, intersection and negation operators of crisp sets were discussed as they provide a way to express conjunction and disjunction (and/or) that are pivotal to reasoning."
},
{
"code": null,
"e": 4025,
"s": 3603,
"text": "The most common method of computing the union of two fuzzy sets is by applying the maximum operator on the sets. Other methods do exist, including the use of the product operator on the two sets. Similarly, the most common method of computing the intersection of two fuzzy sets is by applying the minimum operator on the sets. The complement of a fuzzy set is calculated by subtracting the set membership function from 1."
},
{
"code": null,
"e": 4217,
"s": 4025,
"text": "One crucial observation is that an element can have a degree of belonging both in a set and in the complement of the set. Hence, as an example, element x can be both in A and also in ‘not-A’."
},
{
"code": null,
"e": 4478,
"s": 4217,
"text": "A fuzzy system is a repository of fuzzy expert knowledge that can reason data in vague terms instead of precise Boolean logic. The expert knowledge is a collection of fuzzy membership functions and a set of fuzzy rules, known as the rule-base, having the form:"
},
{
"code": null,
"e": 4541,
"s": 4478,
"text": "IF (conditions are fulfilled) THEN (consequences are inferred)"
},
{
"code": null,
"e": 4599,
"s": 4541,
"text": "The basic configuration of a fuzzy system is shown below:"
},
{
"code": null,
"e": 4734,
"s": 4599,
"text": "A typical fuzzy system can be split into four main parts, namely a fuzzifier, a knowledge base, an inference engine and a defuzzifier;"
},
{
"code": null,
"e": 5185,
"s": 4734,
"text": "The fuzzifier maps a real crisp input to a fuzzy function, therefore determining the ‘degree of membership’ of the input to a vague concept. In a number of controllers, the values of the input variables are mapped to the range of values of the corresponding universe of discourse. The range and resolution of input-fuzzy sets and their effect on the fuzzification process are considered as factors affecting the overall performance of the controller."
},
{
"code": null,
"e": 5805,
"s": 5185,
"text": "The knowledge base comprises the knowledge of the application domain and the attendant control goals. It can be split into a database of definitions used to express linguistic control rules in the controller, and a rule base that describes the knowledge held by the experts of the domain. Intuitively, the knowledge base is the core element of a fuzzy controller as it will contain all the information necessary to accomplish its execution tasks. Various researchers have applied techniques to fine-tune a fuzzy controller’s knowledge base, many using other AI disciplines such as Genetic Algorithms or neural networks."
},
{
"code": null,
"e": 6055,
"s": 5805,
"text": "The Inference Engine provides the decision making logic of the controller. It deduces the fuzzy control actions by employing fuzzy implications and fuzzy rules of inference. In many aspects, it can be viewed as an emulation of human decision making."
},
{
"code": null,
"e": 6353,
"s": 6055,
"text": "The Defuzzification process converts fuzzy control values into crisp quantities, that is, it links a single point to a fuzzy set, given that the point belongs to the support of the fuzzy set. There are many defuzzification techniques, the most famous being the centre-of-area or centre-of-gravity."
},
{
"code": null,
"e": 6427,
"s": 6353,
"text": "Other defuzzification methods include first of maxima and mean of maxima."
},
{
"code": null,
"e": 6728,
"s": 6427,
"text": "Several inferencing models use fuzzy sets to reason the outputs of a system given inputs. One of the most popular methods was devised by Professor Abe Mamdani that used fuzzy sets to control a steam engine. Another popular model was developed by Professor Tomohiro Takagi and Professor Michio Sugeno."
},
{
"code": null,
"e": 7381,
"s": 6728,
"text": "In Mamdani inferencing, the antecedents and consequents of a fuzzy rule are fuzzy sets. The inference is based on Generalised Modus Ponens, which states that the degree of truth of the consequent of a fuzzy rule is the degree of truth of the antecedent. In the case where more than one antecedent clause is present, the individual degrees of membership are joined using a min t-norm operator. If the fuzzy system contains several rules, their output is combined using a max s-norm operator. Defuzzification is necessary so that the consequent action can be expressed in terms of a crisp value. A graphical representation of this process is shown below."
},
{
"code": null,
"e": 7542,
"s": 7381,
"text": "In the Takagi-Sugeno inferencing model, the consequents are functions that map crisp input values to the rule’s crisp output. Hence fuzzy rules are of the form:"
},
{
"code": null,
"e": 7577,
"s": 7542,
"text": "IF x IS X and y IS Y THEN z=f(x,y)"
},
{
"code": null,
"e": 7911,
"s": 7577,
"text": "where f is generally a linear function in X and Y. In contrast to Mamdani fuzzy systems, the rules are not combined using a max -operator but are combined by finding a weighted average, where the weight of a given rule is the degree of membership of its antecedent. Therefore Takagi-Sugeno systems do not require any defuzzification."
},
{
"code": null,
"e": 8296,
"s": 7911,
"text": "In this section, a simple example system will be constructed and executed to visualise the design and execution of a fuzzy inference system. The hypothetical system considered here controls the speed of a fan has according to the environment’s temperature and humidity. Therefore, our system consists of two inputs, temperature and humidity and a single output, that is the fan speed."
},
{
"code": null,
"e": 8494,
"s": 8296,
"text": "The first step in the design of our system is to define fuzzy sets to describe the input and output variables. For simplicity’s sake each variable will be characterised by three fuzzy-sets, namely:"
},
{
"code": null,
"e": 8582,
"s": 8494,
"text": "Temperature: Cold, Medium, HotHumidity: Dry, Normal, WetFan Speed: Slow, Moderate, Fast"
},
{
"code": null,
"e": 8708,
"s": 8582,
"text": "The diagram below shows a graphical representation of the input and output variables of our system and their respective sets."
},
{
"code": null,
"e": 8975,
"s": 8708,
"text": "It can be noted that triangular sets were used to describe most of the sets of this system; however, ‘normal’ humidity is specified using a trapezoidal set. Fuzzy sets reflect the knowledge is the user designing the system, so they can take a wide variety of shapes."
},
{
"code": null,
"e": 9233,
"s": 8975,
"text": "Note that the output was described using fuzzy sets as well; therefore the system that is being considered is a Mamdani-type, that links fuzzy sets related to the inputs of the system to fuzzy sets associated with the output of the system using fuzzy rules."
},
{
"code": null,
"e": 9320,
"s": 9233,
"text": "A total of nine rules are used to describe the knowledge necessary to operate our fan:"
},
{
"code": null,
"e": 9930,
"s": 9320,
"text": "If Temperature is Cold and Humidity is Dry Then Fan Speed is SlowIf Temperature is Medium and Humidity is Dry Then Fan Speed is SlowIf Temperature is Cold and Humidity is Normal Then Fan Speed is SlowIf Temperature is Hot and Humidity is Dry Then Fan Speed is ModerateIf Temperature is Medium and Humidity is Normal Then Fan Speed is ModerateIf Temperature is Cold and Humidity is Wet Then Fan Speed is ModerateIf Temperature is Hot and Humidity is Normal Then Fan Speed is FastIf Temperature is Hot and Humidity is Wet Then Fan Speed is FastIf Temperature is Medium and Humidity is Wet Then Fan Speed is Fast"
},
{
"code": null,
"e": 10162,
"s": 9930,
"text": "These rules can be visualised if we use a combined fuzzy rule base, that is a grid where the input-fuzzy sets occupy the edges so that each cell in the grid defines a rule. The following diagram shows the rule base for this system."
},
{
"code": null,
"e": 10328,
"s": 10162,
"text": "The following steps take place when an input combination is fed to the system, let us as an example say that we have a temperature of 18 degrees and humidity of 60%:"
},
{
"code": null,
"e": 10457,
"s": 10328,
"text": "The degree of membership for each set of the input variables is determined. Hence we can say that a temperature of 18 degrees is"
},
{
"code": null,
"e": 10486,
"s": 10457,
"text": "0.48 Cold0.29 Medium0.00 Hot"
},
{
"code": null,
"e": 10509,
"s": 10486,
"text": "and humidity of 60% is"
},
{
"code": null,
"e": 10534,
"s": 10509,
"text": "0.0 Wet1.0 Normal0.0 Dry"
},
{
"code": null,
"e": 10668,
"s": 10534,
"text": "With this input combination, two rules are fired with a degree higher than zero, as can be seen in the updated fuzzy rule base below:"
},
{
"code": null,
"e": 10889,
"s": 10668,
"text": "And therefore our fuzzy output will consist of the speed Slow, that has activation of 0.48 and Moderate that has 0.29 activation. The combined effect of the two rules or the fuzzy output of the system is displayed below:"
},
{
"code": null,
"e": 11025,
"s": 10889,
"text": "The output set is finally defuzzified using centre-of-gravity defuzzification and a crisp value of 36.814 is obtained to drive the fan."
}
] |
Why You Should Always Use Feature Embeddings With Structured Datasets | by Michael Malin | Towards Data Science | Feature embeddings are one of the most important steps when training neural networks on tabular data tables. Unfortunately, this technique is seldom taught outside of natural language processing (NLP) settings and is consequently almost completely ignored for structured datasets. But skipping this step can lead to significant drops in model accuracy! This has led to a false understanding that gradient boosted methods like XGBoost are always superior for structured dataset problems. Not only will embedding enhanced neural networks often beat gradient boosted methods, but both modeling methods can see major improvements when these embeddings are extracted. This article will answer the following questions:
What are feature embeddings?
How are they used with structured data?
If they are so powerful, why are they not more common?
How are embeddings implemented?
How do I use these embeddings to enhance other models?
Neural networks have difficulty with sparse categorical features. Embeddings are a way to reduce those features to increase model performance. Before discussing structured datasets, its helpful to understand how embeddings are typically used. In natural language processing settings, you are typically dealing with dictionaries of thousands of words. These dictionaries are one-hot encoded into the model, which mathematically is the same as having a separate column for every possible word. When a word is fed into the model, the corresponding column will show a one while all other columns will show zeros. This leads into an incredibly sparse dataset. The solution is to create an embedding.
An embedding will essentially group words with similar meanings based on the training text and return their location. So, for example, ‘fun’ might have a similar embedding value as words like ‘humor’, ‘dancing’, or ‘machine learning’. In practice, neural networks perform far better on these representative features.
Structured datasets also often contain sparce categorical features. In the example customer sales table above, we have zip code and store ID. Because there may be hundreds or thousands of different unique values for these columns, utilizing them would create the same performance issues noted in the NLP problem above. So why not use embeddings the same way?
The problem is, we are now dealing with more than one feature. In this case, two separate sparse categorical columns (zip code AND store ID) as well as other powerful features like sales totals. We simply cannot feed our features into an embedding. We can, however, train our embeddings in the first layer of the model and add in the normal features along side those embeddings. Not only does this transform zip code and store ID into useful features, but now the other useful features are not diluted away by thousands of columns.
In the largest ML focused companies, this technique is absolutely used. The problem is that the vast majority of data scientists outside of those major companies have never heard of using embeddings this way. Why is that? While I would not say these methods are overly difficult to implement, they are above the complexity level of your typical online course or specialization. Most aspiring machine learning practitioners simply never learn how to merge an embedding with other noncategorical features. As a result, features like zip code and store ID are often simply dropped from the model. But these are important features!
Some of the feature value can be captured through techniques like mean encoding but these improvements are often marginal. This has led to a trend of skipping neural networks altogether because gradient boosted methods can handle these categorical features better. But as mentioned above, embeddings can improve both models as will be seen in the next section.
The most difficult part of this process is getting familiar with TensorFlow datasets. While they are nowhere near as intuitive as pandas data frames, they are a great skill to learn if you ever plan on scaling your models to massive datasets or want to build a more complex network.
For this example, we will use the hypothetical customer sales table above. Our goal is to predict the target month’s sales. For simplicity and brevity, we will skip the engineering steps and start with pre-split pandas data frames. For larger datasets, you likely would not start with a data frame but that is a topic for another article.
The first step is the convert these data frames into TensorFlow datasets:
trainset = tf.data.Dataset.from_tensor_slices(( dict(X_train),dict(y_train))).batch(32)validationset = tf.data.Dataset.from_tensor_slices(( dict(X_val),dict(y_val))).batch(32)
One thing to note is that these TensorFlow datasets and the transformations hereafter are not stored into memory the same way a pandas data frame is. They are essentially a pipeline that the data will pass though batch by batch, allowing the model to efficiently train on datasets too large to fit into memory. That is why we are feeding in dictionaries of the data frames rather than the actual data. Notice that we are also defining the batch size now rather than at training like you normally would using Keras API.
Next, we will want to create a list of all unique values for zip code and store id. This will be used for creating and extracting the embeddings later.
zip_codes = X_train['zip_code'].unique()store_ids = X_train['store_id'].unique()
Now we can define the data pipelines using TensorFlow feature columns. Depending on the types of features in your table, there are many options to choose from. Please check out TensorFlow’s feature_column documentation for more information.
# numeric features being fed into the model:feature_columns = []feature_columns.append( tf.feature_column.numeric_column('gender')feature_columns.append( tf.feature_column.numeric_column('age)feature_columns.append( tf.feature_column.numeric_column('previous_sales') # categorical columns using the lists created above:zip_col = tf.feature_column.categorical_column_with_vocabulary_list( 'zip_code', zip_codes)store_col = tf.feature_column.categorical_column_with_vocabulary_list( 'store_id', store_ids) # create an embedding from the categorical column:zip_emb = tf.feature_column.embedding_column(zip_col,dimension=6)store_emb = tf.feature_column.embedding_column(store_col,dimension=4) # add the embeddings to the list of feature columnstf.feature_columns.append(zip_emb)tf.feature_columns.append(store_emb) # create the input layer for the modelfeature_layer = tf.keras.layers.DenseFeatures(feature_columns)
Notice in the embedding step we had to specify the number of dimensions. This refers to how many features we want to reduce the categorical columns down to. The rule of thumb is that you typically reduce the features by the 4th root of the total number of categories (e.g. 1000 unique zip codes down to ~6 embedding columns) but this is another parameter that can be tuned in your model.
Now let us build a simple model:
model = tf.keras.models.Sequential()model.add(feature_layer)model.add(tf.keras.layers.Dense(units=512,activation=’relu’))model.add(tf.keras.layers.Dropout(0.25))# add any layers that you want hereModel.add(tf.keras.layers.Dense(units=1))# compile and train the modelmodel.compile(loss='mse', optimizer='adam', metrics=['accuracy'])model.fit(trainset, validation_data=valset, epochs=20, verbose=2)
Congratulations, you have now trained a model with embeddings! Now how do we extract those embeddings from this model to feed to other models? Simply grab the weights from the model:
zip_emb_weights = model.get_weights()[1]store_emb_weights = model.get_weights()[0]
Notice that the order of the embedding layers can shift around so check that the length of the weight layer matches the length of the unique values defined above to ensure that you are grabbing the correct layer. Now save the weights to a data frame.
# create column names for the embeddingszip_emb_cols = ['zip_emb1', 'zip_emb2', 'zip_emb3', ...]store_emb_cols = ['store_emb1', 'store_emb2', 'store_emb3', ...]# create a pandas data frame:zip_emb_df = pd.DataFrame(columns=zip_emb_cols, index=zip_codes,data=zip_emb_weights)store_emb_df = pd.DataFrame(columns=store_emb_cols, index=store_ids,data=store_emb_weights)# finally, save the data frames to csv or other formatzip_emb_df.to_csv('zip_code_embeddings.csv')store_emb_df.to_csv('store_id_embeddings.csv')
Now that the embeddings are stored, we can merge them back into the original dataset. We can even merge them into other datasets using the same categorical features. I am yet to find a case where these new enhanced datasets have not boosted the accuracy of ALL models utilizing them. Give it a try and I promise you that this process will become a part of your standard machine learning workflow. | [
{
"code": null,
"e": 760,
"s": 47,
"text": "Feature embeddings are one of the most important steps when training neural networks on tabular data tables. Unfortunately, this technique is seldom taught outside of natural language processing (NLP) settings and is consequently almost completely ignored for structured datasets. But skipping this step can lead to significant drops in model accuracy! This has led to a false understanding that gradient boosted methods like XGBoost are always superior for structured dataset problems. Not only will embedding enhanced neural networks often beat gradient boosted methods, but both modeling methods can see major improvements when these embeddings are extracted. This article will answer the following questions:"
},
{
"code": null,
"e": 789,
"s": 760,
"text": "What are feature embeddings?"
},
{
"code": null,
"e": 829,
"s": 789,
"text": "How are they used with structured data?"
},
{
"code": null,
"e": 884,
"s": 829,
"text": "If they are so powerful, why are they not more common?"
},
{
"code": null,
"e": 916,
"s": 884,
"text": "How are embeddings implemented?"
},
{
"code": null,
"e": 971,
"s": 916,
"text": "How do I use these embeddings to enhance other models?"
},
{
"code": null,
"e": 1666,
"s": 971,
"text": "Neural networks have difficulty with sparse categorical features. Embeddings are a way to reduce those features to increase model performance. Before discussing structured datasets, its helpful to understand how embeddings are typically used. In natural language processing settings, you are typically dealing with dictionaries of thousands of words. These dictionaries are one-hot encoded into the model, which mathematically is the same as having a separate column for every possible word. When a word is fed into the model, the corresponding column will show a one while all other columns will show zeros. This leads into an incredibly sparse dataset. The solution is to create an embedding."
},
{
"code": null,
"e": 1983,
"s": 1666,
"text": "An embedding will essentially group words with similar meanings based on the training text and return their location. So, for example, ‘fun’ might have a similar embedding value as words like ‘humor’, ‘dancing’, or ‘machine learning’. In practice, neural networks perform far better on these representative features."
},
{
"code": null,
"e": 2342,
"s": 1983,
"text": "Structured datasets also often contain sparce categorical features. In the example customer sales table above, we have zip code and store ID. Because there may be hundreds or thousands of different unique values for these columns, utilizing them would create the same performance issues noted in the NLP problem above. So why not use embeddings the same way?"
},
{
"code": null,
"e": 2874,
"s": 2342,
"text": "The problem is, we are now dealing with more than one feature. In this case, two separate sparse categorical columns (zip code AND store ID) as well as other powerful features like sales totals. We simply cannot feed our features into an embedding. We can, however, train our embeddings in the first layer of the model and add in the normal features along side those embeddings. Not only does this transform zip code and store ID into useful features, but now the other useful features are not diluted away by thousands of columns."
},
{
"code": null,
"e": 3502,
"s": 2874,
"text": "In the largest ML focused companies, this technique is absolutely used. The problem is that the vast majority of data scientists outside of those major companies have never heard of using embeddings this way. Why is that? While I would not say these methods are overly difficult to implement, they are above the complexity level of your typical online course or specialization. Most aspiring machine learning practitioners simply never learn how to merge an embedding with other noncategorical features. As a result, features like zip code and store ID are often simply dropped from the model. But these are important features!"
},
{
"code": null,
"e": 3863,
"s": 3502,
"text": "Some of the feature value can be captured through techniques like mean encoding but these improvements are often marginal. This has led to a trend of skipping neural networks altogether because gradient boosted methods can handle these categorical features better. But as mentioned above, embeddings can improve both models as will be seen in the next section."
},
{
"code": null,
"e": 4146,
"s": 3863,
"text": "The most difficult part of this process is getting familiar with TensorFlow datasets. While they are nowhere near as intuitive as pandas data frames, they are a great skill to learn if you ever plan on scaling your models to massive datasets or want to build a more complex network."
},
{
"code": null,
"e": 4485,
"s": 4146,
"text": "For this example, we will use the hypothetical customer sales table above. Our goal is to predict the target month’s sales. For simplicity and brevity, we will skip the engineering steps and start with pre-split pandas data frames. For larger datasets, you likely would not start with a data frame but that is a topic for another article."
},
{
"code": null,
"e": 4559,
"s": 4485,
"text": "The first step is the convert these data frames into TensorFlow datasets:"
},
{
"code": null,
"e": 4741,
"s": 4559,
"text": "trainset = tf.data.Dataset.from_tensor_slices(( dict(X_train),dict(y_train))).batch(32)validationset = tf.data.Dataset.from_tensor_slices(( dict(X_val),dict(y_val))).batch(32)"
},
{
"code": null,
"e": 5260,
"s": 4741,
"text": "One thing to note is that these TensorFlow datasets and the transformations hereafter are not stored into memory the same way a pandas data frame is. They are essentially a pipeline that the data will pass though batch by batch, allowing the model to efficiently train on datasets too large to fit into memory. That is why we are feeding in dictionaries of the data frames rather than the actual data. Notice that we are also defining the batch size now rather than at training like you normally would using Keras API."
},
{
"code": null,
"e": 5412,
"s": 5260,
"text": "Next, we will want to create a list of all unique values for zip code and store id. This will be used for creating and extracting the embeddings later."
},
{
"code": null,
"e": 5493,
"s": 5412,
"text": "zip_codes = X_train['zip_code'].unique()store_ids = X_train['store_id'].unique()"
},
{
"code": null,
"e": 5734,
"s": 5493,
"text": "Now we can define the data pipelines using TensorFlow feature columns. Depending on the types of features in your table, there are many options to choose from. Please check out TensorFlow’s feature_column documentation for more information."
},
{
"code": null,
"e": 6749,
"s": 5734,
"text": "# numeric features being fed into the model:feature_columns = []feature_columns.append( tf.feature_column.numeric_column('gender')feature_columns.append( tf.feature_column.numeric_column('age)feature_columns.append( tf.feature_column.numeric_column('previous_sales') # categorical columns using the lists created above:zip_col = tf.feature_column.categorical_column_with_vocabulary_list( 'zip_code', zip_codes)store_col = tf.feature_column.categorical_column_with_vocabulary_list( 'store_id', store_ids) # create an embedding from the categorical column:zip_emb = tf.feature_column.embedding_column(zip_col,dimension=6)store_emb = tf.feature_column.embedding_column(store_col,dimension=4) # add the embeddings to the list of feature columnstf.feature_columns.append(zip_emb)tf.feature_columns.append(store_emb) # create the input layer for the modelfeature_layer = tf.keras.layers.DenseFeatures(feature_columns)"
},
{
"code": null,
"e": 7137,
"s": 6749,
"text": "Notice in the embedding step we had to specify the number of dimensions. This refers to how many features we want to reduce the categorical columns down to. The rule of thumb is that you typically reduce the features by the 4th root of the total number of categories (e.g. 1000 unique zip codes down to ~6 embedding columns) but this is another parameter that can be tuned in your model."
},
{
"code": null,
"e": 7170,
"s": 7137,
"text": "Now let us build a simple model:"
},
{
"code": null,
"e": 7567,
"s": 7170,
"text": "model = tf.keras.models.Sequential()model.add(feature_layer)model.add(tf.keras.layers.Dense(units=512,activation=’relu’))model.add(tf.keras.layers.Dropout(0.25))# add any layers that you want hereModel.add(tf.keras.layers.Dense(units=1))# compile and train the modelmodel.compile(loss='mse', optimizer='adam', metrics=['accuracy'])model.fit(trainset, validation_data=valset, epochs=20, verbose=2)"
},
{
"code": null,
"e": 7750,
"s": 7567,
"text": "Congratulations, you have now trained a model with embeddings! Now how do we extract those embeddings from this model to feed to other models? Simply grab the weights from the model:"
},
{
"code": null,
"e": 7833,
"s": 7750,
"text": "zip_emb_weights = model.get_weights()[1]store_emb_weights = model.get_weights()[0]"
},
{
"code": null,
"e": 8084,
"s": 7833,
"text": "Notice that the order of the embedding layers can shift around so check that the length of the weight layer matches the length of the unique values defined above to ensure that you are grabbing the correct layer. Now save the weights to a data frame."
},
{
"code": null,
"e": 8646,
"s": 8084,
"text": "# create column names for the embeddingszip_emb_cols = ['zip_emb1', 'zip_emb2', 'zip_emb3', ...]store_emb_cols = ['store_emb1', 'store_emb2', 'store_emb3', ...]# create a pandas data frame:zip_emb_df = pd.DataFrame(columns=zip_emb_cols, index=zip_codes,data=zip_emb_weights)store_emb_df = pd.DataFrame(columns=store_emb_cols, index=store_ids,data=store_emb_weights)# finally, save the data frames to csv or other formatzip_emb_df.to_csv('zip_code_embeddings.csv')store_emb_df.to_csv('store_id_embeddings.csv')"
}
] |
AsQueryable() in C# | AsQueryable() method is used to get an IQueryable reference.
Let us see an example to find sum of integer values.
Firstly, set an integer array.
var arr = new int[] { 100, 200, 300, 400 };
Now to find the sum, use the Queryable Sum() and AsQueryable() method.
Queryable.Sum(arr.AsQueryable());
The following is the complete code.
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
var arr = new int[] { 100, 200, 300, 400 };
int res = Queryable.Sum(arr.AsQueryable());
Console.WriteLine("Sum: "+res);
}
}
Sum: 1000 | [
{
"code": null,
"e": 1123,
"s": 1062,
"text": "AsQueryable() method is used to get an IQueryable reference."
},
{
"code": null,
"e": 1176,
"s": 1123,
"text": "Let us see an example to find sum of integer values."
},
{
"code": null,
"e": 1207,
"s": 1176,
"text": "Firstly, set an integer array."
},
{
"code": null,
"e": 1251,
"s": 1207,
"text": "var arr = new int[] { 100, 200, 300, 400 };"
},
{
"code": null,
"e": 1322,
"s": 1251,
"text": "Now to find the sum, use the Queryable Sum() and AsQueryable() method."
},
{
"code": null,
"e": 1356,
"s": 1322,
"text": "Queryable.Sum(arr.AsQueryable());"
},
{
"code": null,
"e": 1392,
"s": 1356,
"text": "The following is the complete code."
},
{
"code": null,
"e": 1403,
"s": 1392,
"text": " Live Demo"
},
{
"code": null,
"e": 1618,
"s": 1403,
"text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n var arr = new int[] { 100, 200, 300, 400 };\n int res = Queryable.Sum(arr.AsQueryable());\n Console.WriteLine(\"Sum: \"+res);\n }\n}"
},
{
"code": null,
"e": 1628,
"s": 1618,
"text": "Sum: 1000"
}
] |
How to get the IIS Application Pool Recycle settings using PowerShell? | To get the IIS application Pool to recycle settings using GUI, you need to check the Application pool advanced settings.
To retrieve the above settings using PowerShell, we can use the Get-IISAppPool command with the specific application pool name. We have the application pool, DefaultAppPool and we need to retrieve its Recycling settings.
PS C:\> (Get-IISAppPool -Name DefaultAppPool).Recycling
Below settings will be for the Periodic restart.
PS C:\> (Get-IISAppPool -Name DefaultAppPool).Recycling.PeriodicRestart
Memory : 0
PrivateMemory : 102400
Requests : 0
Schedule : {add}
Time : 1.05:00:00
Attributes : {memory, privateMemory, requests, time}
ChildElements : {schedule}
ElementTagName : periodicRestart
IsLocallyStored : True
Methods :
RawAttributes : {[memory, 0], [privateMemory, 102400], [requests, 0], [time, 1.05:00:00]}
Schema : Microsoft.Web.Administration.ConfigurationElementSchema
From the further expansion, you can add the Privatememory, Time, etc properties. | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "To get the IIS application Pool to recycle settings using GUI, you need to check the Application pool advanced settings."
},
{
"code": null,
"e": 1404,
"s": 1183,
"text": "To retrieve the above settings using PowerShell, we can use the Get-IISAppPool command with the specific application pool name. We have the application pool, DefaultAppPool and we need to retrieve its Recycling settings."
},
{
"code": null,
"e": 1460,
"s": 1404,
"text": "PS C:\\> (Get-IISAppPool -Name DefaultAppPool).Recycling"
},
{
"code": null,
"e": 1509,
"s": 1460,
"text": "Below settings will be for the Periodic restart."
},
{
"code": null,
"e": 1581,
"s": 1509,
"text": "PS C:\\> (Get-IISAppPool -Name DefaultAppPool).Recycling.PeriodicRestart"
},
{
"code": null,
"e": 2027,
"s": 1581,
"text": "Memory : 0\nPrivateMemory : 102400\nRequests : 0\nSchedule : {add}\nTime : 1.05:00:00\nAttributes : {memory, privateMemory, requests, time}\nChildElements : {schedule}\nElementTagName : periodicRestart\nIsLocallyStored : True\nMethods :\nRawAttributes : {[memory, 0], [privateMemory, 102400], [requests, 0], [time, 1.05:00:00]}\nSchema : Microsoft.Web.Administration.ConfigurationElementSchema"
},
{
"code": null,
"e": 2108,
"s": 2027,
"text": "From the further expansion, you can add the Privatememory, Time, etc properties."
}
] |
Tcl - Variables | In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable.
The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred.
The set command is used for assigning value to a variable. The syntax for set command is,
set variableName value
A few examples of variables are shown below −
#!/usr/bin/tclsh
set variableA 10
set {variable B} test
puts $variableA
puts ${variable B}
When the above code is executed, it produces the following result −
10
test
As you can see in the above program, the $variableName is used to get the value of the variable.
Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below −
#!/usr/bin/tclsh
set variableA "10"
puts $variableA
set sum [expr $variableA +20];
puts $sum
When the above code is executed, it produces the following result −
10
30
As you can see in the above example, expr is used for representing mathematical expression. The default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a single decimal digit. A simple example explains the above.
#!/usr/bin/tclsh
set variableA "10"
set result [expr $variableA / 9];
puts $result
set result [expr $variableA / 9.0];
puts $result
set variableA "10.0"
set result [expr $variableA / 9];
puts $result
When the above code is executed, it produces the following result −
1
1.1111111111111112
1.1111111111111112
In the above example, you can see three cases. In the first case, the dividend and the divisor are whole numbers and we get a whole number as result. In the second case, the divisor alone is a decimal number and in the third case, the dividend is a decimal number. In both second and third cases, we get a decimal number as result.
In the above code, you can change the precision by using tcl_precision special variable. It is shown below −
#!/usr/bin/tclsh
set variableA "10"
set tcl_precision 5
set result [expr $variableA / 9.0];
puts $result
When the above code is executed, it produces the following result −
1.1111
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2328,
"s": 2201,
"text": "In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable."
},
{
"code": null,
"e": 2488,
"s": 2328,
"text": "The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred."
},
{
"code": null,
"e": 2578,
"s": 2488,
"text": "The set command is used for assigning value to a variable. The syntax for set command is,"
},
{
"code": null,
"e": 2602,
"s": 2578,
"text": "set variableName value\n"
},
{
"code": null,
"e": 2648,
"s": 2602,
"text": "A few examples of variables are shown below −"
},
{
"code": null,
"e": 2740,
"s": 2648,
"text": "#!/usr/bin/tclsh\n\nset variableA 10\nset {variable B} test\nputs $variableA\nputs ${variable B}"
},
{
"code": null,
"e": 2808,
"s": 2740,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2817,
"s": 2808,
"text": "10\ntest\n"
},
{
"code": null,
"e": 2914,
"s": 2817,
"text": "As you can see in the above program, the $variableName is used to get the value of the variable."
},
{
"code": null,
"e": 3175,
"s": 2914,
"text": "Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below −"
},
{
"code": null,
"e": 3269,
"s": 3175,
"text": "#!/usr/bin/tclsh\n\nset variableA \"10\"\nputs $variableA\nset sum [expr $variableA +20];\nputs $sum"
},
{
"code": null,
"e": 3337,
"s": 3269,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3344,
"s": 3337,
"text": "10\n30\n"
},
{
"code": null,
"e": 3603,
"s": 3344,
"text": "As you can see in the above example, expr is used for representing mathematical expression. The default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a single decimal digit. A simple example explains the above."
},
{
"code": null,
"e": 3804,
"s": 3603,
"text": "#!/usr/bin/tclsh\n\nset variableA \"10\"\nset result [expr $variableA / 9];\nputs $result\nset result [expr $variableA / 9.0];\nputs $result\nset variableA \"10.0\"\nset result [expr $variableA / 9];\nputs $result"
},
{
"code": null,
"e": 3872,
"s": 3804,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3913,
"s": 3872,
"text": "1\n1.1111111111111112\n1.1111111111111112\n"
},
{
"code": null,
"e": 4245,
"s": 3913,
"text": "In the above example, you can see three cases. In the first case, the dividend and the divisor are whole numbers and we get a whole number as result. In the second case, the divisor alone is a decimal number and in the third case, the dividend is a decimal number. In both second and third cases, we get a decimal number as result."
},
{
"code": null,
"e": 4354,
"s": 4245,
"text": "In the above code, you can change the precision by using tcl_precision special variable. It is shown below −"
},
{
"code": null,
"e": 4460,
"s": 4354,
"text": "#!/usr/bin/tclsh\n\nset variableA \"10\"\nset tcl_precision 5\nset result [expr $variableA / 9.0];\nputs $result"
},
{
"code": null,
"e": 4528,
"s": 4460,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4536,
"s": 4528,
"text": "1.1111\n"
},
{
"code": null,
"e": 4543,
"s": 4536,
"text": " Print"
},
{
"code": null,
"e": 4554,
"s": 4543,
"text": " Add Notes"
}
] |
match_results prefix() and suffix() in C++ | In this article we will be discussing the working, syntax and examples of match_results::prefix() and match_results::suffix() functions in C++ STL.
std::match_results is a specialized container-like class which is used to hold the collection of character sequences which are matched. In this container class a regex match operation finds the matches of the target sequence.
match_results::prefix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. prefix() is used to get the preceding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object.
match_results.prefix();
This function accepts no parameter.
This function returns constant reference of the string or sequence preceding the match sequence.
Input: string str = "Tutorials Points";
regex R("Points");
smatch Mat;
regex_search(str, Mat, R);
Mat.prefix();
Output: Tutorials
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
string str = "Tutorials Points";
regex R("Points");
smatch Mat;
regex_search(str, Mat, R);
cout<<"String prefix is : ";
if (!Mat.empty()) {
cout << Mat.prefix();
}
return 0;
}
If we run the above code it will generate the following output −
String prefix is : Tutorials
match_results::suffix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. suffix() is used to get the succeeding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object.
match_results.suffix();
This function accepts no parameter.
This function returns constant reference of the string or sequence succeeding the match sequence.
Input: std::string str("Tutorials Points is the best");
std::smatch Mat;
std::regex re("Points");
std::regex_match ( str, Mat, re );
Mat.suffix();
Output: is the best
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
string str = "Tutorials Points is the best";
regex R("Points");
smatch Mat;
regex_search(str, Mat, R);
cout<<"String prefix is : ";
if (!Mat.empty()) {
cout << Mat.suffix();
}
return 0;
}
If we run the above code it will generate the following output −
String prefix is : is the best | [
{
"code": null,
"e": 1210,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of match_results::prefix() and match_results::suffix() functions in C++ STL."
},
{
"code": null,
"e": 1436,
"s": 1210,
"text": "std::match_results is a specialized container-like class which is used to hold the collection of character sequences which are matched. In this container class a regex match operation finds the matches of the target sequence."
},
{
"code": null,
"e": 1733,
"s": 1436,
"text": "match_results::prefix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. prefix() is used to get the preceding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object."
},
{
"code": null,
"e": 1757,
"s": 1733,
"text": "match_results.prefix();"
},
{
"code": null,
"e": 1793,
"s": 1757,
"text": "This function accepts no parameter."
},
{
"code": null,
"e": 1890,
"s": 1793,
"text": "This function returns constant reference of the string or sequence preceding the match sequence."
},
{
"code": null,
"e": 2032,
"s": 1890,
"text": "Input: string str = \"Tutorials Points\";\n regex R(\"Points\");\n smatch Mat;\n regex_search(str, Mat, R);\n Mat.prefix();\nOutput: Tutorials"
},
{
"code": null,
"e": 2043,
"s": 2032,
"text": " Live Demo"
},
{
"code": null,
"e": 2308,
"s": 2043,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n string str = \"Tutorials Points\";\n regex R(\"Points\");\n smatch Mat;\n regex_search(str, Mat, R);\n cout<<\"String prefix is : \";\n if (!Mat.empty()) {\n cout << Mat.prefix();\n }\n return 0;\n}"
},
{
"code": null,
"e": 2373,
"s": 2308,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2402,
"s": 2373,
"text": "String prefix is : Tutorials"
},
{
"code": null,
"e": 2700,
"s": 2402,
"text": "match_results::suffix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. suffix() is used to get the succeeding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object."
},
{
"code": null,
"e": 2724,
"s": 2700,
"text": "match_results.suffix();"
},
{
"code": null,
"e": 2760,
"s": 2724,
"text": "This function accepts no parameter."
},
{
"code": null,
"e": 2858,
"s": 2760,
"text": "This function returns constant reference of the string or sequence succeeding the match sequence."
},
{
"code": null,
"e": 3037,
"s": 2858,
"text": "Input: std::string str(\"Tutorials Points is the best\");\n std::smatch Mat;\n std::regex re(\"Points\");\n std::regex_match ( str, Mat, re );\n Mat.suffix();\nOutput: is the best"
},
{
"code": null,
"e": 3048,
"s": 3037,
"text": " Live Demo"
},
{
"code": null,
"e": 3325,
"s": 3048,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n string str = \"Tutorials Points is the best\";\n regex R(\"Points\");\n smatch Mat;\n regex_search(str, Mat, R);\n cout<<\"String prefix is : \";\n if (!Mat.empty()) {\n cout << Mat.suffix();\n }\n return 0;\n}"
},
{
"code": null,
"e": 3390,
"s": 3325,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3421,
"s": 3390,
"text": "String prefix is : is the best"
}
] |
Significance of Q-Q Plots. Understanding the distribution of... | by Sundaresh Chandran | Towards Data Science | Understanding the distribution of a variable(s) is one of the first and foremost tasks done while exploring a dataset. One way to test the distribution of continuous variables graphically is via a Q-Q plot. Personally, these plots come in handy in the case of parametric tests as they insist on the assumption of normality even though they can be used for any underlying distribution.
Quantile-Quantile plot or Q-Q plot is a scatter plot created by plotting 2 different quantiles against each other. The first quantile is that of the variable you are testing the hypothesis for and the second one is the actual distribution you are testing it against. For example, if you are testing if the distribution of age of employees in your team is normally distributed, you are comparing the quantiles of your team members’ age vs quantile from a normally distributed curve. If two quantiles are sampled from the same distribution, they should roughly fall in a straight line.Since this is a visual tool for comparison, results can also be quite subjective nonetheless useful in the understanding underlying distribution of a variable(s)
Below are the steps to generate a Q-Q plot for team members age to test for normality
Take your variable of interest (team member age in this scenario) and sort it from smallest to largest value. Let’s say you have 19 team members in this scenario.Take a normal curve and divide it into 20 equal segments (n+1; where n=#data points)Compute z score for each of these pointsPlot the z-score obtained against the sorted variables. Usually, the z-scores are in the x-axis (also called theoretical quantiles since we are using this as a base for comparison) and the variable quantiles are in the y-axis (also called ordered values)Observe if data points align closely in a straight 45-degree lineIf it does, the age is normally distributed. If it is not, you might want to check it against other possible distributions
Take your variable of interest (team member age in this scenario) and sort it from smallest to largest value. Let’s say you have 19 team members in this scenario.
Take a normal curve and divide it into 20 equal segments (n+1; where n=#data points)
Compute z score for each of these points
Plot the z-score obtained against the sorted variables. Usually, the z-scores are in the x-axis (also called theoretical quantiles since we are using this as a base for comparison) and the variable quantiles are in the y-axis (also called ordered values)
Observe if data points align closely in a straight 45-degree line
If it does, the age is normally distributed. If it is not, you might want to check it against other possible distributions
Below is a sample code to check for normality on a random normal distribution
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom scipy import stats%matplotlib inlinenp.random.seed(100) #for reproducibility# Generate 200 random normal data points with mean=0, standard_deviation=0.1#Documentation:https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.htmlrandom_normal_datapoints = pd.Series(np.random.normal(0, 0.1, 200))# Lets plot the data points along with its KDE to see how it looksfig, ax = plt.subplots()random_normal_datapoints.plot.kde(ax=ax, legend=False, title='A random normal distrubution with mean 0 and SD 1')random_normal_datapoints.plot.hist(density=True, ax=ax)ax.set_ylabel('Frequency')# Plot the Q-Q plot to graphically check for the hypothesis#https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.htmlres = stats.probplot(random_normal_datapoints, plot=plt)plt.show()
# Plot the Q-Q plot to graphically check for the hypothesis# Documentation : https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.htmlres = stats.probplot(random_normal_datapoints, plot=plt)plt.show()
As you can observe, the data points lie approximately in a straight line. Thus, we can say the data point is normally distributed (even though we know well it was sampled from a random normal distribution)
If you were to plot a random uniform distribution against normal distribution, you would get the below plot
As you can see, most of the points, do not lie in a straight line. Showing that the underlying distribution is not normal
More examples on how to check for other distributions and few other examples can be found in the Github link below:
https://github.com/SundareshPrasanna/QQPlot-Medium
Q-Q plot can also be used to test distribution amongst 2 different datasets. For example, if dataset 1, the age variable has 200 records and dataset 2, the age variable has 20 records, it is possible to compare the distributions of these datasets to see if they are indeed the same. This can be particularly helpful in machine learning, where we split data into train-validation-test to see if the distribution is indeed the same. It is also used in the post-deployment scenarios to identify covariate shift/dataset shift/concept shift visually.
In summary, A Q-Q plot helps you compare the sample distribution of the variable at hand against any other possible distributions graphically. | [
{
"code": null,
"e": 557,
"s": 172,
"text": "Understanding the distribution of a variable(s) is one of the first and foremost tasks done while exploring a dataset. One way to test the distribution of continuous variables graphically is via a Q-Q plot. Personally, these plots come in handy in the case of parametric tests as they insist on the assumption of normality even though they can be used for any underlying distribution."
},
{
"code": null,
"e": 1302,
"s": 557,
"text": "Quantile-Quantile plot or Q-Q plot is a scatter plot created by plotting 2 different quantiles against each other. The first quantile is that of the variable you are testing the hypothesis for and the second one is the actual distribution you are testing it against. For example, if you are testing if the distribution of age of employees in your team is normally distributed, you are comparing the quantiles of your team members’ age vs quantile from a normally distributed curve. If two quantiles are sampled from the same distribution, they should roughly fall in a straight line.Since this is a visual tool for comparison, results can also be quite subjective nonetheless useful in the understanding underlying distribution of a variable(s)"
},
{
"code": null,
"e": 1388,
"s": 1302,
"text": "Below are the steps to generate a Q-Q plot for team members age to test for normality"
},
{
"code": null,
"e": 2116,
"s": 1388,
"text": "Take your variable of interest (team member age in this scenario) and sort it from smallest to largest value. Let’s say you have 19 team members in this scenario.Take a normal curve and divide it into 20 equal segments (n+1; where n=#data points)Compute z score for each of these pointsPlot the z-score obtained against the sorted variables. Usually, the z-scores are in the x-axis (also called theoretical quantiles since we are using this as a base for comparison) and the variable quantiles are in the y-axis (also called ordered values)Observe if data points align closely in a straight 45-degree lineIf it does, the age is normally distributed. If it is not, you might want to check it against other possible distributions"
},
{
"code": null,
"e": 2279,
"s": 2116,
"text": "Take your variable of interest (team member age in this scenario) and sort it from smallest to largest value. Let’s say you have 19 team members in this scenario."
},
{
"code": null,
"e": 2364,
"s": 2279,
"text": "Take a normal curve and divide it into 20 equal segments (n+1; where n=#data points)"
},
{
"code": null,
"e": 2405,
"s": 2364,
"text": "Compute z score for each of these points"
},
{
"code": null,
"e": 2660,
"s": 2405,
"text": "Plot the z-score obtained against the sorted variables. Usually, the z-scores are in the x-axis (also called theoretical quantiles since we are using this as a base for comparison) and the variable quantiles are in the y-axis (also called ordered values)"
},
{
"code": null,
"e": 2726,
"s": 2660,
"text": "Observe if data points align closely in a straight 45-degree line"
},
{
"code": null,
"e": 2849,
"s": 2726,
"text": "If it does, the age is normally distributed. If it is not, you might want to check it against other possible distributions"
},
{
"code": null,
"e": 2927,
"s": 2849,
"text": "Below is a sample code to check for normality on a random normal distribution"
},
{
"code": null,
"e": 3803,
"s": 2927,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom scipy import stats%matplotlib inlinenp.random.seed(100) #for reproducibility# Generate 200 random normal data points with mean=0, standard_deviation=0.1#Documentation:https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.htmlrandom_normal_datapoints = pd.Series(np.random.normal(0, 0.1, 200))# Lets plot the data points along with its KDE to see how it looksfig, ax = plt.subplots()random_normal_datapoints.plot.kde(ax=ax, legend=False, title='A random normal distrubution with mean 0 and SD 1')random_normal_datapoints.plot.hist(density=True, ax=ax)ax.set_ylabel('Frequency')# Plot the Q-Q plot to graphically check for the hypothesis#https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.htmlres = stats.probplot(random_normal_datapoints, plot=plt)plt.show()"
},
{
"code": null,
"e": 4025,
"s": 3803,
"text": "# Plot the Q-Q plot to graphically check for the hypothesis# Documentation : https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.htmlres = stats.probplot(random_normal_datapoints, plot=plt)plt.show()"
},
{
"code": null,
"e": 4231,
"s": 4025,
"text": "As you can observe, the data points lie approximately in a straight line. Thus, we can say the data point is normally distributed (even though we know well it was sampled from a random normal distribution)"
},
{
"code": null,
"e": 4339,
"s": 4231,
"text": "If you were to plot a random uniform distribution against normal distribution, you would get the below plot"
},
{
"code": null,
"e": 4461,
"s": 4339,
"text": "As you can see, most of the points, do not lie in a straight line. Showing that the underlying distribution is not normal"
},
{
"code": null,
"e": 4577,
"s": 4461,
"text": "More examples on how to check for other distributions and few other examples can be found in the Github link below:"
},
{
"code": null,
"e": 4628,
"s": 4577,
"text": "https://github.com/SundareshPrasanna/QQPlot-Medium"
},
{
"code": null,
"e": 5174,
"s": 4628,
"text": "Q-Q plot can also be used to test distribution amongst 2 different datasets. For example, if dataset 1, the age variable has 200 records and dataset 2, the age variable has 20 records, it is possible to compare the distributions of these datasets to see if they are indeed the same. This can be particularly helpful in machine learning, where we split data into train-validation-test to see if the distribution is indeed the same. It is also used in the post-deployment scenarios to identify covariate shift/dataset shift/concept shift visually."
}
] |
How to separate string and a numeric value in R? | To separate string and a numeric value, we can use strplit function and split the values by passing all type of characters and all the numeric values. For example, if we have a data frame called df that contains a character column Var having concatenated string and numerical values then we can split them using the below command −
strsplit(df$Var,split="(?<=[a-zA-Z])\\s*(?=[0-9])",perl=TRUE)
Consider the below data frame −
Live Demo
x<-sample(c("india 123","china 232","sudan143","russia326 2"),20,replace=TRUE)
df1<-data.frame(x)
df1
x
1 sudan143
2 china 232
3 russia326 2
4 sudan143
5 sudan143
6 china 232
7 china 232
8 india 123
9 sudan143
10 china 232
11 india 123
12 russia326 2
13 sudan143
14 russia326 2
15 china 232
16 india 123
17 sudan143
18 india 123
19 china 232
20 china 232
Splitting string and numerical values in column x of df1 −
strsplit(df1$x,split="(?<=[a-zA-Z])\\s*(?=[0-9])",perl=TRUE)
[[1]]
[1] "sudan" "143"
[[2]]
[1] "china" "232"
[[3]]
[1] "russia" "326 2"
[[4]]
[1] "sudan" "143"
[[5]]
[1] "sudan" "143"
[[6]]
[1] "china" "232"
[[7]]
[1] "china" "232"
[[8]]
[1] "india" "123"
[[9]]
[1] "sudan" "143"
[[10]]
[1] "china" "232"
[[11]]
[1] "india" "123"
[[12]]
[1] "russia" "326 2"
[[13]]
[1] "sudan" "143"
[[14]]
[1] "russia" "326 2"
[[15]]
[1] "china" "232"
[[16]]
[1] "india" "123"
[[17]]
[1] "sudan" "143"
[[18]]
[1] "india" "123"
[[19]]
[1] "china" "232"
[[20]]
[1] "china" "232"
Live Demo
y<-sample(c("orange 12","banana247","guava 235","kiwi 138"),20,replace=TRUE)
df2<-data.frame(y)
df2
y
1 banana247
2 kiwi 138
3 banana247
4 orange 12
5 kiwi 138
6 kiwi 138
7 banana247
8 banana247
9 orange 12
10 guava 235
11 guava 235
12 banana247
13 guava 235
14 orange 12
15 banana247
16 kiwi 138
17 kiwi 138
18 banana247
19 banana247
20 orange 12
Splitting string and numerical values in column y of df2 −
strsplit(df2$y,split="(?<=[a-zA-Z])\\s*(?=[0-9])",perl=TRUE)
[[1]]
[1] "banana" "247"
[[2]]
[1] "kiwi" "138"
[[3]]
[1] "banana" "247"
[[4]]
[1] "orange" "12"
[[5]]
[1] "kiwi" "138"
[[6]]
[1] "kiwi" "138"
[[7]]
[1] "banana" "247"
[[8]]
[1] "banana" "247"
[[9]]
[1] "orange" "12"
[[10]]
[1] "guava" "235"
[[11]]
[1] "guava" "235"
[[12]]
[1] "banana" "247"
[[13]]
[1] "guava" "235"
[[14]]
[1] "orange" "12"
[[15]]
[1] "banana" "247"
[[16]]
[1] "kiwi" "138"
[[17]]
[1] "kiwi" "138"
[[18]]
[1] "banana" "247"
[[19]]
[1] "banana" "247"
[[20]]
[1] "orange" "12" | [
{
"code": null,
"e": 1394,
"s": 1062,
"text": "To separate string and a numeric value, we can use strplit function and split the values by passing all type of characters and all the numeric values. For example, if we have a data frame called df that contains a character column Var having concatenated string and numerical values then we can split them using the below command −"
},
{
"code": null,
"e": 1456,
"s": 1394,
"text": "strsplit(df$Var,split=\"(?<=[a-zA-Z])\\\\s*(?=[0-9])\",perl=TRUE)"
},
{
"code": null,
"e": 1488,
"s": 1456,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": " Live Demo"
},
{
"code": null,
"e": 1601,
"s": 1499,
"text": "x<-sample(c(\"india 123\",\"china 232\",\"sudan143\",\"russia326 2\"),20,replace=TRUE)\ndf1<-data.frame(x)\ndf1"
},
{
"code": null,
"e": 1867,
"s": 1601,
"text": " x\n1 sudan143\n2 china 232\n3 russia326 2\n4 sudan143\n5 sudan143\n6 china 232\n7 china 232\n8 india 123\n9 sudan143\n10 china 232\n11 india 123\n12 russia326 2\n13 sudan143\n14 russia326 2\n15 china 232\n16 india 123\n17 sudan143\n18 india 123\n19 china 232\n20 china 232"
},
{
"code": null,
"e": 1926,
"s": 1867,
"text": "Splitting string and numerical values in column x of df1 −"
},
{
"code": null,
"e": 1987,
"s": 1926,
"text": "strsplit(df1$x,split=\"(?<=[a-zA-Z])\\\\s*(?=[0-9])\",perl=TRUE)"
},
{
"code": null,
"e": 2487,
"s": 1987,
"text": "[[1]]\n[1] \"sudan\" \"143\"\n[[2]]\n[1] \"china\" \"232\"\n[[3]]\n[1] \"russia\" \"326 2\"\n[[4]]\n[1] \"sudan\" \"143\"\n[[5]]\n[1] \"sudan\" \"143\"\n[[6]]\n[1] \"china\" \"232\"\n[[7]]\n[1] \"china\" \"232\"\n[[8]]\n[1] \"india\" \"123\"\n[[9]]\n[1] \"sudan\" \"143\"\n[[10]]\n[1] \"china\" \"232\"\n[[11]]\n[1] \"india\" \"123\"\n[[12]]\n[1] \"russia\" \"326 2\"\n[[13]]\n[1] \"sudan\" \"143\"\n[[14]]\n[1] \"russia\" \"326 2\"\n[[15]]\n[1] \"china\" \"232\"\n[[16]]\n[1] \"india\" \"123\"\n[[17]]\n[1] \"sudan\" \"143\"\n[[18]]\n[1] \"india\" \"123\"\n[[19]]\n[1] \"china\" \"232\"\n[[20]]\n[1] \"china\" \"232\""
},
{
"code": null,
"e": 2498,
"s": 2487,
"text": " Live Demo"
},
{
"code": null,
"e": 2598,
"s": 2498,
"text": "y<-sample(c(\"orange 12\",\"banana247\",\"guava 235\",\"kiwi 138\"),20,replace=TRUE)\ndf2<-data.frame(y)\ndf2"
},
{
"code": null,
"e": 2860,
"s": 2598,
"text": " y\n1 banana247\n2 kiwi 138\n3 banana247\n4 orange 12\n5 kiwi 138\n6 kiwi 138\n7 banana247\n8 banana247\n9 orange 12\n10 guava 235\n11 guava 235\n12 banana247\n13 guava 235\n14 orange 12\n15 banana247\n16 kiwi 138\n17 kiwi 138\n18 banana247\n19 banana247\n20 orange 12"
},
{
"code": null,
"e": 2919,
"s": 2860,
"text": "Splitting string and numerical values in column y of df2 −"
},
{
"code": null,
"e": 2980,
"s": 2919,
"text": "strsplit(df2$y,split=\"(?<=[a-zA-Z])\\\\s*(?=[0-9])\",perl=TRUE)"
},
{
"code": null,
"e": 3474,
"s": 2980,
"text": "[[1]]\n[1] \"banana\" \"247\"\n[[2]]\n[1] \"kiwi\" \"138\"\n[[3]]\n[1] \"banana\" \"247\"\n[[4]]\n[1] \"orange\" \"12\"\n[[5]]\n[1] \"kiwi\" \"138\"\n[[6]]\n[1] \"kiwi\" \"138\"\n[[7]]\n[1] \"banana\" \"247\"\n[[8]]\n[1] \"banana\" \"247\"\n[[9]]\n[1] \"orange\" \"12\"\n[[10]]\n[1] \"guava\" \"235\"\n[[11]]\n[1] \"guava\" \"235\"\n[[12]]\n[1] \"banana\" \"247\"\n[[13]]\n[1] \"guava\" \"235\"\n[[14]]\n[1] \"orange\" \"12\"\n[[15]]\n[1] \"banana\" \"247\"\n[[16]]\n[1] \"kiwi\" \"138\"\n[[17]]\n[1] \"kiwi\" \"138\"\n[[18]]\n[1] \"banana\" \"247\"\n[[19]]\n[1] \"banana\" \"247\"\n[[20]]\n[1] \"orange\" \"12\""
}
] |
Calculate Volume of Dodecahedron - GeeksforGeeks | 17 Mar, 2021
Given the edge of the dodecahedron calculate its Volume. Volume is the amount of the space which the shapes takes up. A dodecahedron is a 3-dimensional figure made up of 12 faces, or flat sides. All of the faces are pentagons of the same size.The word ‘dodecahedron’ comes from the Greek words dodeca (‘twelve’) and hedron (‘faces’).Formula: Volume = (15 + 7√5)*e3/4Where e is length of an edge.Examples :
Input : side = 4
Output : 490.44
Input : side = 9
Output : 5586.41
C++
Java
Python3
C#
PHP
Javascript
// CPP program to calculate// Volume of dodecahedron#include <bits/stdc++.h>using namespace std; // utility Functiondouble vol_of_dodecahedron(int side){ return (((15 + (7 * (sqrt(5)))) / 4) * (pow(side, 3))) ;}// Driver Functionint main(){ int side = 4; cout << "Volume of dodecahedron = " << vol_of_dodecahedron(side);}
// Java program to calculate// Volume of dodecahedron import java.io.*; class GFG{ // driver function public static void main (String[] args) { int side = 4; System.out.print("Volume of dodecahedron = "); System.out.println(vol_of_dodecahedron(side)); } static double vol_of_dodecahedron(int side) { return (((15 + (7 * (Math.sqrt(5)))) / 4) * (Math.pow(side, 3))); }} // This code is contributed// by Azkia Anam.
# Python3 program to calculate# Volume of dodecahedronimport math # utility Functiondef vol_of_dodecahedron(side) : return (((15 + (7 * (math.sqrt(5)))) / 4) * (math.pow(side, 3))) # Driver Functionside = 4print("Volume of dodecahedron =", round(vol_of_dodecahedron(side), 2)) # This code is contributed by Smitha Dinesh Semwal
// C# program to calculate// Volume of dodecahedronusing System; public class GFG{ // utility Function static float vol_of_dodecahedron(int side) { return (float)(((15 + (7 * (Math.Sqrt(5)))) / 4) * (Math.Pow(side, 3))) ; } // Driver Function static public void Main () { int side = 4; Console.WriteLine("Volume of dodecahedron = " + vol_of_dodecahedron(side)); }} /* This code is contributed by vt_m.*/
<?php// PHP program to calculate// Volume of dodecahedron // utility Functionfunction vol_of_dodecahedron($side){ return (((15 + (7 * (sqrt(5)))) / 4) * (pow($side, 3))) ;} // Driver Function $side = 4; echo ("Volume of dodecahedron = "); echo(vol_of_dodecahedron($side)); // This code is contributed by vt_m.?>
<script>// javascript program to calculate// Volume of dodecahedron // utility Functionfunction vol_of_dodecahedron( side){ return (((15 + (7 * (Math.sqrt(5)))) / 4) * (Math.pow(side, 3))) ;} // Driver Function let side = 4; document.write("Volume of dodecahedron = " + vol_of_dodecahedron(side).toFixed(2)); // This code contributed by gauravrajput1</script>
Output :
Volume of dodecahedron = 490.44
vt_m
GauravRajput1
area-volume-programs
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Closest Pair of Points | O(nlogn) Implementation
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 25428,
"s": 25400,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 25836,
"s": 25428,
"text": "Given the edge of the dodecahedron calculate its Volume. Volume is the amount of the space which the shapes takes up. A dodecahedron is a 3-dimensional figure made up of 12 faces, or flat sides. All of the faces are pentagons of the same size.The word ‘dodecahedron’ comes from the Greek words dodeca (‘twelve’) and hedron (‘faces’).Formula: Volume = (15 + 7√5)*e3/4Where e is length of an edge.Examples : "
},
{
"code": null,
"e": 25904,
"s": 25836,
"text": "Input : side = 4\nOutput : 490.44\n\nInput : side = 9\nOutput : 5586.41"
},
{
"code": null,
"e": 25912,
"s": 25908,
"text": "C++"
},
{
"code": null,
"e": 25917,
"s": 25912,
"text": "Java"
},
{
"code": null,
"e": 25925,
"s": 25917,
"text": "Python3"
},
{
"code": null,
"e": 25928,
"s": 25925,
"text": "C#"
},
{
"code": null,
"e": 25932,
"s": 25928,
"text": "PHP"
},
{
"code": null,
"e": 25943,
"s": 25932,
"text": "Javascript"
},
{
"code": "// CPP program to calculate// Volume of dodecahedron#include <bits/stdc++.h>using namespace std; // utility Functiondouble vol_of_dodecahedron(int side){ return (((15 + (7 * (sqrt(5)))) / 4) * (pow(side, 3))) ;}// Driver Functionint main(){ int side = 4; cout << \"Volume of dodecahedron = \" << vol_of_dodecahedron(side);}",
"e": 26309,
"s": 25943,
"text": null
},
{
"code": "// Java program to calculate// Volume of dodecahedron import java.io.*; class GFG{ // driver function public static void main (String[] args) { int side = 4; System.out.print(\"Volume of dodecahedron = \"); System.out.println(vol_of_dodecahedron(side)); } static double vol_of_dodecahedron(int side) { return (((15 + (7 * (Math.sqrt(5)))) / 4) * (Math.pow(side, 3))); }} // This code is contributed// by Azkia Anam.",
"e": 26832,
"s": 26309,
"text": null
},
{
"code": "# Python3 program to calculate# Volume of dodecahedronimport math # utility Functiondef vol_of_dodecahedron(side) : return (((15 + (7 * (math.sqrt(5)))) / 4) * (math.pow(side, 3))) # Driver Functionside = 4print(\"Volume of dodecahedron =\", round(vol_of_dodecahedron(side), 2)) # This code is contributed by Smitha Dinesh Semwal",
"e": 27196,
"s": 26832,
"text": null
},
{
"code": "// C# program to calculate// Volume of dodecahedronusing System; public class GFG{ // utility Function static float vol_of_dodecahedron(int side) { return (float)(((15 + (7 * (Math.Sqrt(5)))) / 4) * (Math.Pow(side, 3))) ; } // Driver Function static public void Main () { int side = 4; Console.WriteLine(\"Volume of dodecahedron = \" + vol_of_dodecahedron(side)); }} /* This code is contributed by vt_m.*/",
"e": 27699,
"s": 27196,
"text": null
},
{
"code": "<?php// PHP program to calculate// Volume of dodecahedron // utility Functionfunction vol_of_dodecahedron($side){ return (((15 + (7 * (sqrt(5)))) / 4) * (pow($side, 3))) ;} // Driver Function $side = 4; echo (\"Volume of dodecahedron = \"); echo(vol_of_dodecahedron($side)); // This code is contributed by vt_m.?>",
"e": 28052,
"s": 27699,
"text": null
},
{
"code": "<script>// javascript program to calculate// Volume of dodecahedron // utility Functionfunction vol_of_dodecahedron( side){ return (((15 + (7 * (Math.sqrt(5)))) / 4) * (Math.pow(side, 3))) ;} // Driver Function let side = 4; document.write(\"Volume of dodecahedron = \" + vol_of_dodecahedron(side).toFixed(2)); // This code contributed by gauravrajput1</script>",
"e": 28455,
"s": 28052,
"text": null
},
{
"code": null,
"e": 28466,
"s": 28455,
"text": "Output : "
},
{
"code": null,
"e": 28500,
"s": 28466,
"text": " \nVolume of dodecahedron = 490.44"
},
{
"code": null,
"e": 28507,
"s": 28502,
"text": "vt_m"
},
{
"code": null,
"e": 28521,
"s": 28507,
"text": "GauravRajput1"
},
{
"code": null,
"e": 28542,
"s": 28521,
"text": "area-volume-programs"
},
{
"code": null,
"e": 28552,
"s": 28542,
"text": "Geometric"
},
{
"code": null,
"e": 28571,
"s": 28552,
"text": "School Programming"
},
{
"code": null,
"e": 28581,
"s": 28571,
"text": "Geometric"
},
{
"code": null,
"e": 28679,
"s": 28581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28728,
"s": 28679,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 28781,
"s": 28728,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 28815,
"s": 28781,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 28873,
"s": 28815,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 28922,
"s": 28873,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 28940,
"s": 28922,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28956,
"s": 28940,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28975,
"s": 28956,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29000,
"s": 28975,
"text": "Reverse a string in Java"
}
] |
How to create a common error page using JSP? | JSP gives you an option to specify Error Page for each JSP using page attribute. Whenever the page throws an exception, the JSP container automatically invokes the error page.
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage = "xxx" %> directive.
<%@ page errorPage = "ShowError.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1) {
throw new RuntimeException("Error condition!!!");
}
%>
</body>
</html>
We will now write one Error Handling JSP ShowError.jsp, which is given below. Notice that the error-handling page includes the directive <%@ page isErrorPage = "true" %>. This directive causes the JSP compiler to generate the exception instance variable.
<%@ page isErrorPage = "true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre><% exception.printStackTrace(response.getWriter()); %></pre>
</body>
</html>
Access the main.jsp, you will receive an output somewhat like the following −
java.lang.RuntimeException: Error condition!!!
......
Opps...
Sorry, an error occurred.
Here is the exception stack trace: | [
{
"code": null,
"e": 1238,
"s": 1062,
"text": "JSP gives you an option to specify Error Page for each JSP using page attribute. Whenever the page throws an exception, the JSP container automatically invokes the error page."
},
{
"code": null,
"e": 1378,
"s": 1238,
"text": "Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage = \"xxx\" %> directive."
},
{
"code": null,
"e": 1710,
"s": 1378,
"text": "<%@ page errorPage = \"ShowError.jsp\" %>\n\n<html>\n <head>\n <title>Error Handling Example</title>\n </head>\n <body>\n <%\n // Throw an exception to invoke the error page\n int x = 1;\n if (x == 1) {\n throw new RuntimeException(\"Error condition!!!\");\n }\n %>\n </body>\n</html>"
},
{
"code": null,
"e": 1965,
"s": 1710,
"text": "We will now write one Error Handling JSP ShowError.jsp, which is given below. Notice that the error-handling page includes the directive <%@ page isErrorPage = \"true\" %>. This directive causes the JSP compiler to generate the exception instance variable."
},
{
"code": null,
"e": 2276,
"s": 1965,
"text": "<%@ page isErrorPage = \"true\" %>\n\n<html>\n <head>\n <title>Show Error Page</title>\n </head>\n <body>\n <h1>Opps...</h1>\n <p>Sorry, an error occurred.</p>\n <p>Here is the exception stack trace: </p>\n <pre><% exception.printStackTrace(response.getWriter()); %></pre>\n </body>\n</html>"
},
{
"code": null,
"e": 2354,
"s": 2276,
"text": "Access the main.jsp, you will receive an output somewhat like the following −"
},
{
"code": null,
"e": 2479,
"s": 2354,
"text": "java.lang.RuntimeException: Error condition!!!\n......\n\nOpps...\nSorry, an error occurred.\n\nHere is the exception stack trace:"
}
] |
Python - Convert Nested dictionary to Mapped Tuple - GeeksforGeeks | 03 Jul, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert nested dictionaries to mapped tuple. This kind of problem can occur in web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}, ‘best’ : {‘x’ : 8, ‘y’ : 3, ‘z’: 5}}Output : [(‘x’, (5, 8)), (‘y’, (6, 3)), (‘z’, (3, 5))]
Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}}Output : [(‘x’, (5, )), (‘y’, (6, )), (‘z’, (3, ))]
Method #1 : Using list comprehension + generator expressionThe combination of above functions can be used to solve this problem. In this, we perform the tasks of creating the tuple using list comprehension and generator expression helps in grouping, by extracting values using values().
# Python3 code to demonstrate working of # Convert Nested dictionary to Mapped Tuple# Using list comprehension + generator expression # initializing dictionarytest_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4}, 'best' : {'x' : 8, 'y' : 3}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Nested dictionary to Mapped Tuple# Using list comprehension + generator expressionres = [(key, tuple(sub[key] for sub in test_dict.values())) for key in test_dict['gfg']] # printing result print("The grouped dictionary : " + str(res))
The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}}The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]
Method #2 : Using defaultdict() + loopThis is yet another way in which this task can be performed. In this, we perform the task of mapping using defaultdict(), of keys of nested dictionaries and recreate value list using loop. This method is useful for older version of Python.
# Python3 code to demonstrate working of # Convert Nested dictionary to Mapped Tuple# Using defaultdict() + loopfrom collections import defaultdict # initializing dictionarytest_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4}, 'best' : {'x' : 8, 'y' : 3}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Nested dictionary to Mapped Tuple# Using defaultdict() + loopres = defaultdict(tuple)for key, val in test_dict.items(): for ele in val: res[ele] += (val[ele], ) # printing result print("The grouped dictionary : " + str(list(res.items()))
The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}}The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary | [
{
"code": null,
"e": 24333,
"s": 24305,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 24610,
"s": 24333,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert nested dictionaries to mapped tuple. This kind of problem can occur in web development and day-day programming. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24758,
"s": 24610,
"text": "Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}, ‘best’ : {‘x’ : 8, ‘y’ : 3, ‘z’: 5}}Output : [(‘x’, (5, 8)), (‘y’, (6, 3)), (‘z’, (3, 5))]"
},
{
"code": null,
"e": 24866,
"s": 24758,
"text": "Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}}Output : [(‘x’, (5, )), (‘y’, (6, )), (‘z’, (3, ))]"
},
{
"code": null,
"e": 25153,
"s": 24866,
"text": "Method #1 : Using list comprehension + generator expressionThe combination of above functions can be used to solve this problem. In this, we perform the tasks of creating the tuple using list comprehension and generator expression helps in grouping, by extracting values using values()."
},
{
"code": "# Python3 code to demonstrate working of # Convert Nested dictionary to Mapped Tuple# Using list comprehension + generator expression # initializing dictionarytest_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4}, 'best' : {'x' : 8, 'y' : 3}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Nested dictionary to Mapped Tuple# Using list comprehension + generator expressionres = [(key, tuple(sub[key] for sub in test_dict.values())) for key in test_dict['gfg']] # printing result print(\"The grouped dictionary : \" + str(res)) ",
"e": 25813,
"s": 25153,
"text": null
},
{
"code": null,
"e": 25979,
"s": 25813,
"text": "The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}}The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]"
},
{
"code": null,
"e": 26259,
"s": 25981,
"text": "Method #2 : Using defaultdict() + loopThis is yet another way in which this task can be performed. In this, we perform the task of mapping using defaultdict(), of keys of nested dictionaries and recreate value list using loop. This method is useful for older version of Python."
},
{
"code": "# Python3 code to demonstrate working of # Convert Nested dictionary to Mapped Tuple# Using defaultdict() + loopfrom collections import defaultdict # initializing dictionarytest_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4}, 'best' : {'x' : 8, 'y' : 3}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Nested dictionary to Mapped Tuple# Using defaultdict() + loopres = defaultdict(tuple)for key, val in test_dict.items(): for ele in val: res[ele] += (val[ele], ) # printing result print(\"The grouped dictionary : \" + str(list(res.items())) ",
"e": 26920,
"s": 26259,
"text": null
},
{
"code": null,
"e": 27086,
"s": 26920,
"text": "The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}}The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]"
},
{
"code": null,
"e": 27113,
"s": 27086,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27120,
"s": 27113,
"text": "Python"
},
{
"code": null,
"e": 27136,
"s": 27120,
"text": "Python Programs"
},
{
"code": null,
"e": 27234,
"s": 27136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27243,
"s": 27234,
"text": "Comments"
},
{
"code": null,
"e": 27256,
"s": 27243,
"text": "Old Comments"
},
{
"code": null,
"e": 27274,
"s": 27256,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27309,
"s": 27274,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27331,
"s": 27309,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27363,
"s": 27331,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27393,
"s": 27363,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27436,
"s": 27393,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27458,
"s": 27436,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27497,
"s": 27458,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27554,
"s": 27497,
"text": "Python program to check whether a number is Prime or not"
}
] |
Data Structures | Binary Trees | Question 13 - GeeksQuiz | Theory of Computation
Computer Organization and Architecture
Software Engineering
HTML and XML
Engineering Mathematics
GATE
Aptitude
CS Interview Questions
Programming Languages
C
C++
Java
Python
C
C++
Java
Python
Computer Science
Data Structures
Algorithms
Operating Systems
DBMS
Compiler Design
Computer Networks
Theory of Computation
Computer Organization and Architecture
Software Engineering
HTML and XML
Engineering Mathematics
Data Structures
Algorithms
Operating Systems
DBMS
Compiler Design
Computer Networks
Theory of Computation
Computer Organization and Architecture
Software Engineering
HTML and XML
Engineering Mathematics
GATE
Aptitude
CS Interview Questions
Articles
Programming Languages
C
C++
Java
Python
Computer Science
Algorithms
Compiler Design
Comuter Network
Computer Organization and Architecture
Data Structures
Hash
Linked List
Queue
Stack
Tree
DBMS
Difference
Digital Electronics
Mathematics
Operating Systems
Theory of Computation
Placements
Puzzles
Interview Experiences
Programming Languages
C
C++
Java
Python
C
C++
Java
Python
Computer Science
Algorithms
Compiler Design
Comuter Network
Computer Organization and Architecture
Data Structures
Hash
Linked List
Queue
Stack
Tree
DBMS
Difference
Digital Electronics
Mathematics
Operating Systems
Theory of Computation
Algorithms
Compiler Design
Comuter Network
Computer Organization and Architecture
Data Structures
Hash
Linked List
Queue
Stack
Tree
Hash
Linked List
Queue
Stack
Tree
DBMS
Difference
Digital Electronics
Mathematics
Operating Systems
Theory of Computation
Placements
Puzzles
Interview Experiences
GATE
GATE CS Corner
GATE Notes
Last Minute Notes
Official Papers
GATE CS 2017 Important Dates and Links
GATE CS Corner
GATE Notes
Last Minute Notes
Official Papers
GATE CS 2017 Important Dates and Links
Placements
Puzzles
Company Prep
What’s new
Jobs
Apps
Interview Corner
Consider the following C program segment
struct CellNode
{
struct CelINode *leftchild;
int element;
struct CelINode *rightChild;
}
int Dosomething(struct CelINode *ptr)
{
int value = 0;
if (ptr != NULL)
{
if (ptr->leftChild != NULL)
value = 1 + DoSomething(ptr->leftChild);
if (ptr->rightChild != NULL)
value = max(value, 1 + DoSomething(ptr->rightChild));
}
return (value);
}
The value returned by the function DoSomething when a pointer to the root of a non-empty tree is passed as argument is (GATE CS 2004)
(A) The number of leaf nodes in the tree
(B) The number of nodes in the tree
(C) The number of internal nodes in the tree
(D) The height of the tree
Answer: (D) Explanation: DoSomething() returns max(height of left child + 1, height of left child + 1). So given that pointer to root of tree is passed to DoSomething(), it will return height of the tree. Note that this implementation follows the convention where height of a single node is 0. Quiz of this Question | [
{
"code": null,
"e": 314,
"s": 0,
"text": "\nTheory of Computation\nComputer Organization and Architecture\nSoftware Engineering\nHTML and XML\nEngineering Mathematics\n\n\nGATE\nAptitude\nCS Interview Questions\n\n"
},
{
"code": null,
"e": 357,
"s": 314,
"text": "Programming Languages\n\nC\nC++\nJava\nPython\n\n"
},
{
"code": null,
"e": 359,
"s": 357,
"text": "C"
},
{
"code": null,
"e": 363,
"s": 359,
"text": "C++"
},
{
"code": null,
"e": 368,
"s": 363,
"text": "Java"
},
{
"code": null,
"e": 375,
"s": 368,
"text": "Python"
},
{
"code": null,
"e": 598,
"s": 375,
"text": "Computer Science\n\nData Structures\nAlgorithms\nOperating Systems\nDBMS\nCompiler Design\nComputer Networks\nTheory of Computation\nComputer Organization and Architecture\nSoftware Engineering\nHTML and XML\nEngineering Mathematics\n\n"
},
{
"code": null,
"e": 614,
"s": 598,
"text": "Data Structures"
},
{
"code": null,
"e": 625,
"s": 614,
"text": "Algorithms"
},
{
"code": null,
"e": 643,
"s": 625,
"text": "Operating Systems"
},
{
"code": null,
"e": 648,
"s": 643,
"text": "DBMS"
},
{
"code": null,
"e": 664,
"s": 648,
"text": "Compiler Design"
},
{
"code": null,
"e": 682,
"s": 664,
"text": "Computer Networks"
},
{
"code": null,
"e": 704,
"s": 682,
"text": "Theory of Computation"
},
{
"code": null,
"e": 743,
"s": 704,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 764,
"s": 743,
"text": "Software Engineering"
},
{
"code": null,
"e": 777,
"s": 764,
"text": "HTML and XML"
},
{
"code": null,
"e": 801,
"s": 777,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 806,
"s": 801,
"text": "GATE"
},
{
"code": null,
"e": 815,
"s": 806,
"text": "Aptitude"
},
{
"code": null,
"e": 838,
"s": 815,
"text": "CS Interview Questions"
},
{
"code": null,
"e": 1177,
"s": 838,
"text": "Articles\n\nProgramming Languages\n\nC\nC++\nJava\nPython\n\n\nComputer Science\n\nAlgorithms\nCompiler Design\nComuter Network\nComputer Organization and Architecture\nData Structures\n\nHash\nLinked List\nQueue\nStack\nTree\n\n\nDBMS\nDifference\nDigital Electronics\nMathematics\nOperating Systems\nTheory of Computation\n\n\nPlacements\nPuzzles\nInterview Experiences\n\n"
},
{
"code": null,
"e": 1220,
"s": 1177,
"text": "Programming Languages\n\nC\nC++\nJava\nPython\n\n"
},
{
"code": null,
"e": 1222,
"s": 1220,
"text": "C"
},
{
"code": null,
"e": 1226,
"s": 1222,
"text": "C++"
},
{
"code": null,
"e": 1231,
"s": 1226,
"text": "Java"
},
{
"code": null,
"e": 1238,
"s": 1231,
"text": "Python"
},
{
"code": null,
"e": 1481,
"s": 1238,
"text": "Computer Science\n\nAlgorithms\nCompiler Design\nComuter Network\nComputer Organization and Architecture\nData Structures\n\nHash\nLinked List\nQueue\nStack\nTree\n\n\nDBMS\nDifference\nDigital Electronics\nMathematics\nOperating Systems\nTheory of Computation\n\n"
},
{
"code": null,
"e": 1492,
"s": 1481,
"text": "Algorithms"
},
{
"code": null,
"e": 1508,
"s": 1492,
"text": "Compiler Design"
},
{
"code": null,
"e": 1524,
"s": 1508,
"text": "Comuter Network"
},
{
"code": null,
"e": 1563,
"s": 1524,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 1616,
"s": 1563,
"text": "Data Structures\n\nHash\nLinked List\nQueue\nStack\nTree\n\n"
},
{
"code": null,
"e": 1621,
"s": 1616,
"text": "Hash"
},
{
"code": null,
"e": 1633,
"s": 1621,
"text": "Linked List"
},
{
"code": null,
"e": 1639,
"s": 1633,
"text": "Queue"
},
{
"code": null,
"e": 1645,
"s": 1639,
"text": "Stack"
},
{
"code": null,
"e": 1650,
"s": 1645,
"text": "Tree"
},
{
"code": null,
"e": 1655,
"s": 1650,
"text": "DBMS"
},
{
"code": null,
"e": 1666,
"s": 1655,
"text": "Difference"
},
{
"code": null,
"e": 1686,
"s": 1666,
"text": "Digital Electronics"
},
{
"code": null,
"e": 1698,
"s": 1686,
"text": "Mathematics"
},
{
"code": null,
"e": 1716,
"s": 1698,
"text": "Operating Systems"
},
{
"code": null,
"e": 1738,
"s": 1716,
"text": "Theory of Computation"
},
{
"code": null,
"e": 1749,
"s": 1738,
"text": "Placements"
},
{
"code": null,
"e": 1757,
"s": 1749,
"text": "Puzzles"
},
{
"code": null,
"e": 1779,
"s": 1757,
"text": "Interview Experiences"
},
{
"code": null,
"e": 1886,
"s": 1779,
"text": "GATE\n\nGATE CS Corner\nGATE Notes\nLast Minute Notes\nOfficial Papers\nGATE CS 2017 Important Dates and Links\n\n"
},
{
"code": null,
"e": 1901,
"s": 1886,
"text": "GATE CS Corner"
},
{
"code": null,
"e": 1912,
"s": 1901,
"text": "GATE Notes"
},
{
"code": null,
"e": 1930,
"s": 1912,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 1946,
"s": 1930,
"text": "Official Papers"
},
{
"code": null,
"e": 1985,
"s": 1946,
"text": "GATE CS 2017 Important Dates and Links"
},
{
"code": null,
"e": 1996,
"s": 1985,
"text": "Placements"
},
{
"code": null,
"e": 2004,
"s": 1996,
"text": "Puzzles"
},
{
"code": null,
"e": 2017,
"s": 2004,
"text": "Company Prep"
},
{
"code": null,
"e": 2028,
"s": 2017,
"text": "What’s new"
},
{
"code": null,
"e": 2033,
"s": 2028,
"text": "Jobs"
},
{
"code": null,
"e": 2038,
"s": 2033,
"text": "Apps"
},
{
"code": null,
"e": 2055,
"s": 2038,
"text": "Interview Corner"
},
{
"code": null,
"e": 2096,
"s": 2055,
"text": "Consider the following C program segment"
},
{
"code": null,
"e": 2488,
"s": 2096,
"text": "struct CellNode\n{\n struct CelINode *leftchild;\n int element;\n struct CelINode *rightChild;\n}\n\nint Dosomething(struct CelINode *ptr)\n{\n int value = 0;\n if (ptr != NULL)\n {\n if (ptr->leftChild != NULL)\n value = 1 + DoSomething(ptr->leftChild);\n if (ptr->rightChild != NULL)\n value = max(value, 1 + DoSomething(ptr->rightChild));\n }\n return (value);\n}\n"
}
] |
Draw a curve connecting two points instead of a straight line in matplotlib | To draw a curve connecting two points instead of a straight line in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Define a draw_curve() method to make a curve with a mathematical expression.
Plot point1 and point2 data points.
Plot x and y data points returned from the draw_curve() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
def draw_curve(p1, p2):
a = (p2[1] - p1[1]) / (np.cosh(p2[0]) - np.cosh(p1[0]))
b = p1[1] - a * np.cosh(p1[0])
x = np.linspace(p1[0], p2[0], 100)
y = a * np.cosh(x) + b
return x, y
p1 = [0, 1]
p2 = [1, 2]
x, y = draw_curve(p1, p2)
plt.plot(p1[0], p1[1], 'o')
plt.plot(p2[0], p2[1], 'o')
plt.plot(x, y)
plt.show()
It will produce the following output | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "To draw a curve connecting two points instead of a straight line in matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1252,
"s": 1176,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1329,
"s": 1252,
"text": "Define a draw_curve() method to make a curve with a mathematical expression."
},
{
"code": null,
"e": 1365,
"s": 1329,
"text": "Plot point1 and point2 data points."
},
{
"code": null,
"e": 1429,
"s": 1365,
"text": "Plot x and y data points returned from the draw_curve() method."
},
{
"code": null,
"e": 1471,
"s": 1429,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1940,
"s": 1471,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndef draw_curve(p1, p2):\n a = (p2[1] - p1[1]) / (np.cosh(p2[0]) - np.cosh(p1[0]))\n b = p1[1] - a * np.cosh(p1[0])\n x = np.linspace(p1[0], p2[0], 100)\n y = a * np.cosh(x) + b\n return x, y\n\np1 = [0, 1]\np2 = [1, 2]\nx, y = draw_curve(p1, p2)\nplt.plot(p1[0], p1[1], 'o')\nplt.plot(p2[0], p2[1], 'o')\nplt.plot(x, y)\nplt.show()"
},
{
"code": null,
"e": 1977,
"s": 1940,
"text": "It will produce the following output"
}
] |
Count pairs in an array which have at least one digit common - GeeksforGeeks | 24 May, 2021
Given an array of N numbers. Find out the number of pairs i and j such that i < j and Ai and Aj have at least one digit common (For e.g. (11, 19) have 1 digit common but (36, 48) have no digit common)
Examples:
Input: A[] = { 10, 12, 24 } Output: 2 Explanation: Two valid pairs are (10, 12) and (12, 24) which have atleast one digit common
Method 1 (Brute Force) A naive approach to solve this problem is just by running two nested loops and consider all possible pairs. We can check if the two numbers have at least one common digit, by extracting every digit of the first number and try to find it in the extracted digits of second number. The task would become much easier we simply convert them into strings.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to count pairs in an array// with some common digit#include <bits/stdc++.h> using namespace std; // Returns true if the pair is valid,// otherwise falsebool checkValidPair(int num1, int num2){ // converting integers to strings string s1 = to_string(num1); string s2 = to_string(num2); // Iterate over the strings and check // if a character in first string is also // present in second string, return true for (int i = 0; i < s1.size(); i++) for (int j = 0; j < s2.size(); j++) if (s1[i] == s2[j]) return true; // No common digit found return false;} // Returns the number of valid pairsint countPairs(int arr[], int n){ int numberOfPairs = 0; // Iterate over all possible pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs;} // Driver Code to test above functionsint main(){ int arr[] = { 10, 12, 24 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}
// Java Program to count// pairs in an array// with some common digitimport java.io.*; class GFG{ // Returns true if the pair // is valid, otherwise false static boolean checkValidPair(int num1, int num2) { // converting integers // to strings String s1 = Integer.toString(num1); String s2 = Integer.toString(num2); // Iterate over the strings // and check if a character // in first string is also // present in second string, // return true for (int i = 0; i < s1.length(); i++) for (int j = 0; j < s2.length(); j++) if (s1.charAt(i) == s2.charAt(j)) return true; // No common // digit found return false; } // Returns the number // of valid pairs static int countPairs(int []arr, int n) { int numberOfPairs = 0; // Iterate over all // possible pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs; } // Driver Code public static void main(String args[]) { int []arr = new int[]{ 10, 12, 24 }; int n = arr.length; System.out.print(countPairs(arr, n)); }} // This code is contributed// by manish shaw.
# Python3 Program to count pairs in# an array with some common digit # Returns true if the pair is# valid, otherwise falsedef checkValidPair(num1, num2) : # converting integers to strings s1 = str(num1) s2 = str(num2) # Iterate over the strings and check if # a character in first string is also # present in second string, return true for i in range(len(s1)) : for j in range(len(s2)) : if (s1[i] == s2[j]) : return True; # No common digit found return False; # Returns the number of valid pairsdef countPairs(arr, n) : numberOfPairs = 0 # Iterate over all possible pairs for i in range(n) : for j in range(i + 1, n) : if (checkValidPair(arr[i], arr[j])) : numberOfPairs += 1 return numberOfPairs # Driver Codeif __name__ == "__main__" : arr = [ 10, 12, 24 ] n = len(arr) print(countPairs(arr, n)) # This code is contributed by Ryuga
// C# Program to count pairs in an array// with some common digitusing System; class GFG { // Returns true if the pair is valid, // otherwise false static bool checkValidPair(int num1, int num2) { // converting integers to strings string s1 = num1.ToString(); string s2 = num2.ToString(); // Iterate over the strings and check // if a character in first string is also // present in second string, return true for (int i = 0; i < s1.Length; i++) for (int j = 0; j < s2.Length; j++) if (s1[i] == s2[j]) return true; // No common digit found return false; } // Returns the number of valid pairs static int countPairs(int []arr, int n) { int numberOfPairs = 0; // Iterate over all possible pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs; } // Driver Code to test above functions static void Main() { int []arr = new int[]{ 10, 12, 24 }; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); }} // This code is contributed by manish shaw.
<?php// PHP Program to count pairs in an array// with some common digit // Returns true if the pair is valid,// otherwise falsefunction checkValidPair($num1, $num2){ // converting integers to strings $s1 = (string)$num1; $s2 = (string)$num2; // Iterate over the strings and check // if a character in first string is also // present in second string, return true for ($i = 0; $i < strlen($s1); $i++) for ($j = 0; $j < strlen($s2); $j++) if ($s1[$i] == $s2[$j]) return true; // No common digit found return false;} // Returns the number of valid pairsfunction countPairs(&$arr, $n){ $numberOfPairs = 0; // Iterate over all possible pairs for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) if (checkValidPair($arr[$i], $arr[$j])) $numberOfPairs++; return $numberOfPairs;} // Driver Code$arr = array(10, 12, 24 );$n = sizeof($arr);echo (countPairs($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript Program to count pairs in an array// with some common digit // Returns true if the pair is valid,// otherwise falsefunction checkValidPair(num1, num2){ // converting integers to strings var s1 = num1.toString(); var s2 = num2.toString(); var i,j; // Iterate over the strings and check // if a character in first string is also // present in second string, return true for(i = 0; i < s1.length; i++) for(j = 0; j < s2.length; j++) if (s1[i] == s2[j]) return true; // No common digit found return false;} // Returns the number of valid pairsfunction countPairs(arr, n){ var numberOfPairs = 0; // Iterate over all possible pairs for(i = 0; i < n; i++) for(j = i + 1; j < n; j++) if(checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs;} // Driver Code to test above functions var arr = [10, 12, 24]; var n = arr.length;; document.write(countPairs(arr, n)); </script>
2
Time Complexity: O(N2) where N is the size of array.
Method 2 (Bit Masking): An efficient approach of solving this problem is creating a bit mask for every digit present in a particular number. Thus, for every digit to be present in a number if we have a mask of 1111111111.
Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask - 1 1 1 1 1 1 1 1 1 1
Here 1 denotes that the corresponding ith digit is set.
For e.g. 1235 can be represented as
Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask for 1235 - 0 1 1 1 0 1 0 0 0 0
Now we just have to extract every digit of a number and make the corresponding bit set (1 << ith digit) and store the whole number as a mask. Careful analysis suggests that the maximum value of the mask is 1023 in decimal (which contains all the digits from 0 – 9). Since the same set of digits can exist in more than one number, we need to maintain a frequency array to store the count of mask value.
Let the frequencies of two masks i and j be freqi and freqj respectively, If(i AND j) return true, means ith and jth mask contains atleast one common set bit which in turn implies that the numbers from which these masks have been built also contain a common digit then, increment the answer ans += freqi * freqj [ if i != j ] ans += (freqi * (freqi – 1)) / 2 [ if j == i ]
Below is the implementation of this efficient approach:
C++
Java
Python3
C#
Javascript
// CPP Program to count pairs in an array with// some common digit#include <bits/stdc++.h>using namespace std; // This function calculates the mask frequencies// for every present in the arrayvoid calculateMaskFrequencies(int arr[], int n, unordered_map<int, int>& freq){ // Iterate over the array for (int i = 0; i < n; i++) { int num = arr[i]; // Creating an empty mask int mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while (num > 0) { mask = mask | (1 << (num % 10)); num /= 10; } // Update the frequency array freq[mask]++; }} // Function return the number of valid pairsint countPairs(int arr[], int n){ // Store the mask frequencies unordered_map<int, int> freq; calculateMaskFrequencies(arr, n, freq); long long int numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for (int i = 0; i < 1024; i++) { numberOfPairs += (freq[i] * (freq[i] - 1)) / 2; for (int j = i + 1; j < 1024; j++) { // if it contains a common digit if (i & j) numberOfPairs += (freq[i] * freq[j]); } } return numberOfPairs;} // Driver Code to test above functionsint main(){ int arr[] = { 10, 12, 24 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}
// Java Program to count pairs in an array with// some common digitimport java.io.*;import java.util.*;class GFG{ // Store the mask frequencies public static Map<Integer, Integer> freq = new HashMap<Integer, Integer>(); // This function calculates the mask frequencies // for every present in the array public static void calculateMaskFrequencies(int[] arr,int n) { // Iterate over the array for(int i = 0; i < n; i++) { int num = arr[i]; // Creating an empty mask int mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while(num > 0) { mask = mask | (1 << (num % 10)); num /= 10; } // Update the frequency array if(freq.containsKey(mask)) { freq.put(new Integer(mask), freq.get(mask) + 1); } else { freq.put(new Integer(mask), 1); } } } // Function return the number of valid pairs public static int countPairs(int[] arr, int n) { calculateMaskFrequencies(arr, n); int numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for(int i = 0; i < 1024; i++) { int x = 0; if(freq.containsKey(i)) { x = freq.get(i); } numberOfPairs += ((x) * (x - 1)) / 2; for(int j = i + 1; j < 1024; j++) { int y = 0; // if it contains a common digit if((i & j) != 0) { if(freq.containsKey(j)) { y = freq.get(j); } numberOfPairs += x * y; } } } return numberOfPairs; } // Driver Code public static void main (String[] args) { int[] arr = {10, 12, 24}; int n = arr.length; System.out.println(countPairs(arr, n)); }} // This code is contributed by avanitrachhadiya2155
# Python3 Program to count pairs in an array# with some common digit # This function calculates the mask frequencies# for every present in the arraydef calculateMaskFrequencies(arr, n, freq): # Iterate over the array for i in range(n): num = arr[i] # Creating an empty mask mask = 0 # Extracting every digit of the number # and updating corresponding bit in the # mask while (num > 0): mask = mask | (1 << (num % 10)) num //= 10 # Update the frequency array freq[mask] = freq.get(mask, 0) + 1 # Function return the number of valid pairsdef countPairs(arr, n): # Store the mask frequencies freq = dict() calculateMaskFrequencies(arr, n, freq) numberOfPairs = 0 # Considering every possible pair of masks # and calculate pairs according to their # frequencies for i in range(1024): x = 0 if i in freq.keys(): x = freq[i] numberOfPairs += (x * (x - 1)) // 2 for j in range(i + 1, 1024): y = 0 if j in freq.keys(): y = freq[j] # if it contains a common digit if (i & j): numberOfPairs += (x * y) return numberOfPairs # Driver Codearr = [10, 12, 24]n = len(arr)print(countPairs(arr, n)) # This code is contributed by mohit kumar
// C# Program to count pairs in an array with// some common digitusing System;using System.Collections.Generic; public class GFG{ // Store the mask frequencies static Dictionary<int, int> freq = new Dictionary<int, int>(); // This function calculates the mask frequencies // for every present in the array public static void calculateMaskFrequencies(int[] arr,int n) { // Iterate over the array for(int i = 0; i < n; i++) { int num = arr[i]; // Creating an empty mask int mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while(num > 0) { mask = mask | (1 << (num % 10)); num /= 10; } // Update the frequency array if(freq.ContainsKey(mask)) { freq[mask]++; } else { freq.Add(mask, 1); } } } public static int countPairs(int[] arr, int n) { calculateMaskFrequencies(arr, n); int numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for(int i = 0; i < 1024; i++) { int x = 0; if(freq.ContainsKey(i)) { x = freq[i]; } numberOfPairs += ((x) * (x - 1)) / 2; for(int j = i + 1; j < 1024; j++) { int y = 0; // if it contains a common digit if((i & j) != 0) { if(freq.ContainsKey(j)) { y = freq[j]; } numberOfPairs += x * y; } } } return numberOfPairs; } // Driver Code static public void Main () { int[] arr = {10, 12, 24}; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); }} // This code is contributed by rag2127
<script>// Javascript Program to count pairs in an array with// some common digit // Store the mask frequencieslet freq = new Map(); // This function calculates the mask frequencies // for every present in the arrayfunction calculateMaskFrequencies(arr,n){ // Iterate over the array for(let i = 0; i < n; i++) { let num = arr[i]; // Creating an empty mask let mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while(num > 0) { mask = mask | (1 << (num % 10)); num = Math.floor(num/10); } // Update the frequency array if(freq.has(mask)) { freq.set((mask), freq.get(mask) + 1); } else { freq.set((mask), 1); } }} // Function return the number of valid pairsfunction countPairs(arr,n){ calculateMaskFrequencies(arr, n); let numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for(let i = 0; i < 1024; i++) { let x = 0; if(freq.has(i)) { x = freq.get(i); } numberOfPairs += Math.floor((x) * (x - 1)) / 2; for(let j = i + 1; j < 1024; j++) { let y = 0; // if it contains a common digit if((i & j) != 0) { if(freq.has(j)) { y = freq.get(j); } numberOfPairs += x * y; } } } return numberOfPairs;} // Driver Codelet arr=[10, 12, 24];let n = arr.length;document.write(countPairs(arr, n)); // This code is contributed by unknown2108</script>
2
Time Complexity: O(N + 1024 * 1024), where N is the size of the array.
manishshaw1
ankthon
Shivi_Aggarwal
mohit kumar 29
gautamsai4914
avanitrachhadiya2155
rag2127
SURENDRA_GANGWAR
unknown2108
cpp-unordered_map
Arrays
Bit Magic
Technical Scripter
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Trapping Rain Water
Building Heap from Array
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25021,
"s": 24820,
"text": "Given an array of N numbers. Find out the number of pairs i and j such that i < j and Ai and Aj have at least one digit common (For e.g. (11, 19) have 1 digit common but (36, 48) have no digit common)"
},
{
"code": null,
"e": 25032,
"s": 25021,
"text": "Examples: "
},
{
"code": null,
"e": 25162,
"s": 25032,
"text": "Input: A[] = { 10, 12, 24 } Output: 2 Explanation: Two valid pairs are (10, 12) and (12, 24) which have atleast one digit common "
},
{
"code": null,
"e": 25535,
"s": 25162,
"text": "Method 1 (Brute Force) A naive approach to solve this problem is just by running two nested loops and consider all possible pairs. We can check if the two numbers have at least one common digit, by extracting every digit of the first number and try to find it in the extracted digits of second number. The task would become much easier we simply convert them into strings."
},
{
"code": null,
"e": 25586,
"s": 25535,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25590,
"s": 25586,
"text": "C++"
},
{
"code": null,
"e": 25595,
"s": 25590,
"text": "Java"
},
{
"code": null,
"e": 25603,
"s": 25595,
"text": "Python3"
},
{
"code": null,
"e": 25606,
"s": 25603,
"text": "C#"
},
{
"code": null,
"e": 25610,
"s": 25606,
"text": "PHP"
},
{
"code": null,
"e": 25621,
"s": 25610,
"text": "Javascript"
},
{
"code": "// CPP Program to count pairs in an array// with some common digit#include <bits/stdc++.h> using namespace std; // Returns true if the pair is valid,// otherwise falsebool checkValidPair(int num1, int num2){ // converting integers to strings string s1 = to_string(num1); string s2 = to_string(num2); // Iterate over the strings and check // if a character in first string is also // present in second string, return true for (int i = 0; i < s1.size(); i++) for (int j = 0; j < s2.size(); j++) if (s1[i] == s2[j]) return true; // No common digit found return false;} // Returns the number of valid pairsint countPairs(int arr[], int n){ int numberOfPairs = 0; // Iterate over all possible pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs;} // Driver Code to test above functionsint main(){ int arr[] = { 10, 12, 24 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}",
"e": 26735,
"s": 25621,
"text": null
},
{
"code": "// Java Program to count// pairs in an array// with some common digitimport java.io.*; class GFG{ // Returns true if the pair // is valid, otherwise false static boolean checkValidPair(int num1, int num2) { // converting integers // to strings String s1 = Integer.toString(num1); String s2 = Integer.toString(num2); // Iterate over the strings // and check if a character // in first string is also // present in second string, // return true for (int i = 0; i < s1.length(); i++) for (int j = 0; j < s2.length(); j++) if (s1.charAt(i) == s2.charAt(j)) return true; // No common // digit found return false; } // Returns the number // of valid pairs static int countPairs(int []arr, int n) { int numberOfPairs = 0; // Iterate over all // possible pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs; } // Driver Code public static void main(String args[]) { int []arr = new int[]{ 10, 12, 24 }; int n = arr.length; System.out.print(countPairs(arr, n)); }} // This code is contributed// by manish shaw.",
"e": 28172,
"s": 26735,
"text": null
},
{
"code": "# Python3 Program to count pairs in# an array with some common digit # Returns true if the pair is# valid, otherwise falsedef checkValidPair(num1, num2) : # converting integers to strings s1 = str(num1) s2 = str(num2) # Iterate over the strings and check if # a character in first string is also # present in second string, return true for i in range(len(s1)) : for j in range(len(s2)) : if (s1[i] == s2[j]) : return True; # No common digit found return False; # Returns the number of valid pairsdef countPairs(arr, n) : numberOfPairs = 0 # Iterate over all possible pairs for i in range(n) : for j in range(i + 1, n) : if (checkValidPair(arr[i], arr[j])) : numberOfPairs += 1 return numberOfPairs # Driver Codeif __name__ == \"__main__\" : arr = [ 10, 12, 24 ] n = len(arr) print(countPairs(arr, n)) # This code is contributed by Ryuga",
"e": 29135,
"s": 28172,
"text": null
},
{
"code": "// C# Program to count pairs in an array// with some common digitusing System; class GFG { // Returns true if the pair is valid, // otherwise false static bool checkValidPair(int num1, int num2) { // converting integers to strings string s1 = num1.ToString(); string s2 = num2.ToString(); // Iterate over the strings and check // if a character in first string is also // present in second string, return true for (int i = 0; i < s1.Length; i++) for (int j = 0; j < s2.Length; j++) if (s1[i] == s2[j]) return true; // No common digit found return false; } // Returns the number of valid pairs static int countPairs(int []arr, int n) { int numberOfPairs = 0; // Iterate over all possible pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs; } // Driver Code to test above functions static void Main() { int []arr = new int[]{ 10, 12, 24 }; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); }} // This code is contributed by manish shaw.",
"e": 30444,
"s": 29135,
"text": null
},
{
"code": "<?php// PHP Program to count pairs in an array// with some common digit // Returns true if the pair is valid,// otherwise falsefunction checkValidPair($num1, $num2){ // converting integers to strings $s1 = (string)$num1; $s2 = (string)$num2; // Iterate over the strings and check // if a character in first string is also // present in second string, return true for ($i = 0; $i < strlen($s1); $i++) for ($j = 0; $j < strlen($s2); $j++) if ($s1[$i] == $s2[$j]) return true; // No common digit found return false;} // Returns the number of valid pairsfunction countPairs(&$arr, $n){ $numberOfPairs = 0; // Iterate over all possible pairs for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) if (checkValidPair($arr[$i], $arr[$j])) $numberOfPairs++; return $numberOfPairs;} // Driver Code$arr = array(10, 12, 24 );$n = sizeof($arr);echo (countPairs($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 31500,
"s": 30444,
"text": null
},
{
"code": "<script> // Javascript Program to count pairs in an array// with some common digit // Returns true if the pair is valid,// otherwise falsefunction checkValidPair(num1, num2){ // converting integers to strings var s1 = num1.toString(); var s2 = num2.toString(); var i,j; // Iterate over the strings and check // if a character in first string is also // present in second string, return true for(i = 0; i < s1.length; i++) for(j = 0; j < s2.length; j++) if (s1[i] == s2[j]) return true; // No common digit found return false;} // Returns the number of valid pairsfunction countPairs(arr, n){ var numberOfPairs = 0; // Iterate over all possible pairs for(i = 0; i < n; i++) for(j = i + 1; j < n; j++) if(checkValidPair(arr[i], arr[j])) numberOfPairs++; return numberOfPairs;} // Driver Code to test above functions var arr = [10, 12, 24]; var n = arr.length;; document.write(countPairs(arr, n)); </script>",
"e": 32524,
"s": 31500,
"text": null
},
{
"code": null,
"e": 32526,
"s": 32524,
"text": "2"
},
{
"code": null,
"e": 32579,
"s": 32526,
"text": "Time Complexity: O(N2) where N is the size of array."
},
{
"code": null,
"e": 32802,
"s": 32579,
"text": "Method 2 (Bit Masking): An efficient approach of solving this problem is creating a bit mask for every digit present in a particular number. Thus, for every digit to be present in a number if we have a mask of 1111111111. "
},
{
"code": null,
"e": 33152,
"s": 32802,
"text": "Digits - 0 1 2 3 4 5 6 7 8 9\n | | | | | | | | | |\nMask - 1 1 1 1 1 1 1 1 1 1 \n\nHere 1 denotes that the corresponding ith digit is set. \nFor e.g. 1235 can be represented as\nDigits - 0 1 2 3 4 5 6 7 8 9\n | | | | | | | | | |\nMask for 1235 - 0 1 1 1 0 1 0 0 0 0"
},
{
"code": null,
"e": 33555,
"s": 33152,
"text": "Now we just have to extract every digit of a number and make the corresponding bit set (1 << ith digit) and store the whole number as a mask. Careful analysis suggests that the maximum value of the mask is 1023 in decimal (which contains all the digits from 0 – 9). Since the same set of digits can exist in more than one number, we need to maintain a frequency array to store the count of mask value. "
},
{
"code": null,
"e": 33930,
"s": 33555,
"text": "Let the frequencies of two masks i and j be freqi and freqj respectively, If(i AND j) return true, means ith and jth mask contains atleast one common set bit which in turn implies that the numbers from which these masks have been built also contain a common digit then, increment the answer ans += freqi * freqj [ if i != j ] ans += (freqi * (freqi – 1)) / 2 [ if j == i ] "
},
{
"code": null,
"e": 33986,
"s": 33930,
"text": "Below is the implementation of this efficient approach:"
},
{
"code": null,
"e": 33990,
"s": 33986,
"text": "C++"
},
{
"code": null,
"e": 33995,
"s": 33990,
"text": "Java"
},
{
"code": null,
"e": 34003,
"s": 33995,
"text": "Python3"
},
{
"code": null,
"e": 34006,
"s": 34003,
"text": "C#"
},
{
"code": null,
"e": 34017,
"s": 34006,
"text": "Javascript"
},
{
"code": "// CPP Program to count pairs in an array with// some common digit#include <bits/stdc++.h>using namespace std; // This function calculates the mask frequencies// for every present in the arrayvoid calculateMaskFrequencies(int arr[], int n, unordered_map<int, int>& freq){ // Iterate over the array for (int i = 0; i < n; i++) { int num = arr[i]; // Creating an empty mask int mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while (num > 0) { mask = mask | (1 << (num % 10)); num /= 10; } // Update the frequency array freq[mask]++; }} // Function return the number of valid pairsint countPairs(int arr[], int n){ // Store the mask frequencies unordered_map<int, int> freq; calculateMaskFrequencies(arr, n, freq); long long int numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for (int i = 0; i < 1024; i++) { numberOfPairs += (freq[i] * (freq[i] - 1)) / 2; for (int j = i + 1; j < 1024; j++) { // if it contains a common digit if (i & j) numberOfPairs += (freq[i] * freq[j]); } } return numberOfPairs;} // Driver Code to test above functionsint main(){ int arr[] = { 10, 12, 24 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0;}",
"e": 35530,
"s": 34017,
"text": null
},
{
"code": "// Java Program to count pairs in an array with// some common digitimport java.io.*;import java.util.*;class GFG{ // Store the mask frequencies public static Map<Integer, Integer> freq = new HashMap<Integer, Integer>(); // This function calculates the mask frequencies // for every present in the array public static void calculateMaskFrequencies(int[] arr,int n) { // Iterate over the array for(int i = 0; i < n; i++) { int num = arr[i]; // Creating an empty mask int mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while(num > 0) { mask = mask | (1 << (num % 10)); num /= 10; } // Update the frequency array if(freq.containsKey(mask)) { freq.put(new Integer(mask), freq.get(mask) + 1); } else { freq.put(new Integer(mask), 1); } } } // Function return the number of valid pairs public static int countPairs(int[] arr, int n) { calculateMaskFrequencies(arr, n); int numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for(int i = 0; i < 1024; i++) { int x = 0; if(freq.containsKey(i)) { x = freq.get(i); } numberOfPairs += ((x) * (x - 1)) / 2; for(int j = i + 1; j < 1024; j++) { int y = 0; // if it contains a common digit if((i & j) != 0) { if(freq.containsKey(j)) { y = freq.get(j); } numberOfPairs += x * y; } } } return numberOfPairs; } // Driver Code public static void main (String[] args) { int[] arr = {10, 12, 24}; int n = arr.length; System.out.println(countPairs(arr, n)); }} // This code is contributed by avanitrachhadiya2155",
"e": 37408,
"s": 35530,
"text": null
},
{
"code": "# Python3 Program to count pairs in an array# with some common digit # This function calculates the mask frequencies# for every present in the arraydef calculateMaskFrequencies(arr, n, freq): # Iterate over the array for i in range(n): num = arr[i] # Creating an empty mask mask = 0 # Extracting every digit of the number # and updating corresponding bit in the # mask while (num > 0): mask = mask | (1 << (num % 10)) num //= 10 # Update the frequency array freq[mask] = freq.get(mask, 0) + 1 # Function return the number of valid pairsdef countPairs(arr, n): # Store the mask frequencies freq = dict() calculateMaskFrequencies(arr, n, freq) numberOfPairs = 0 # Considering every possible pair of masks # and calculate pairs according to their # frequencies for i in range(1024): x = 0 if i in freq.keys(): x = freq[i] numberOfPairs += (x * (x - 1)) // 2 for j in range(i + 1, 1024): y = 0 if j in freq.keys(): y = freq[j] # if it contains a common digit if (i & j): numberOfPairs += (x * y) return numberOfPairs # Driver Codearr = [10, 12, 24]n = len(arr)print(countPairs(arr, n)) # This code is contributed by mohit kumar",
"e": 38824,
"s": 37408,
"text": null
},
{
"code": "// C# Program to count pairs in an array with// some common digitusing System;using System.Collections.Generic; public class GFG{ // Store the mask frequencies static Dictionary<int, int> freq = new Dictionary<int, int>(); // This function calculates the mask frequencies // for every present in the array public static void calculateMaskFrequencies(int[] arr,int n) { // Iterate over the array for(int i = 0; i < n; i++) { int num = arr[i]; // Creating an empty mask int mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while(num > 0) { mask = mask | (1 << (num % 10)); num /= 10; } // Update the frequency array if(freq.ContainsKey(mask)) { freq[mask]++; } else { freq.Add(mask, 1); } } } public static int countPairs(int[] arr, int n) { calculateMaskFrequencies(arr, n); int numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for(int i = 0; i < 1024; i++) { int x = 0; if(freq.ContainsKey(i)) { x = freq[i]; } numberOfPairs += ((x) * (x - 1)) / 2; for(int j = i + 1; j < 1024; j++) { int y = 0; // if it contains a common digit if((i & j) != 0) { if(freq.ContainsKey(j)) { y = freq[j]; } numberOfPairs += x * y; } } } return numberOfPairs; } // Driver Code static public void Main () { int[] arr = {10, 12, 24}; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); }} // This code is contributed by rag2127",
"e": 40984,
"s": 38824,
"text": null
},
{
"code": "<script>// Javascript Program to count pairs in an array with// some common digit // Store the mask frequencieslet freq = new Map(); // This function calculates the mask frequencies // for every present in the arrayfunction calculateMaskFrequencies(arr,n){ // Iterate over the array for(let i = 0; i < n; i++) { let num = arr[i]; // Creating an empty mask let mask = 0; // Extracting every digit of the number // and updating corresponding bit in the // mask while(num > 0) { mask = mask | (1 << (num % 10)); num = Math.floor(num/10); } // Update the frequency array if(freq.has(mask)) { freq.set((mask), freq.get(mask) + 1); } else { freq.set((mask), 1); } }} // Function return the number of valid pairsfunction countPairs(arr,n){ calculateMaskFrequencies(arr, n); let numberOfPairs = 0; // Considering every possible pair of masks // and calculate pairs according to their // frequencies for(let i = 0; i < 1024; i++) { let x = 0; if(freq.has(i)) { x = freq.get(i); } numberOfPairs += Math.floor((x) * (x - 1)) / 2; for(let j = i + 1; j < 1024; j++) { let y = 0; // if it contains a common digit if((i & j) != 0) { if(freq.has(j)) { y = freq.get(j); } numberOfPairs += x * y; } } } return numberOfPairs;} // Driver Codelet arr=[10, 12, 24];let n = arr.length;document.write(countPairs(arr, n)); // This code is contributed by unknown2108</script>",
"e": 42624,
"s": 40984,
"text": null
},
{
"code": null,
"e": 42626,
"s": 42624,
"text": "2"
},
{
"code": null,
"e": 42697,
"s": 42626,
"text": "Time Complexity: O(N + 1024 * 1024), where N is the size of the array."
},
{
"code": null,
"e": 42709,
"s": 42697,
"text": "manishshaw1"
},
{
"code": null,
"e": 42717,
"s": 42709,
"text": "ankthon"
},
{
"code": null,
"e": 42732,
"s": 42717,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 42747,
"s": 42732,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 42761,
"s": 42747,
"text": "gautamsai4914"
},
{
"code": null,
"e": 42782,
"s": 42761,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 42790,
"s": 42782,
"text": "rag2127"
},
{
"code": null,
"e": 42807,
"s": 42790,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 42819,
"s": 42807,
"text": "unknown2108"
},
{
"code": null,
"e": 42837,
"s": 42819,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 42844,
"s": 42837,
"text": "Arrays"
},
{
"code": null,
"e": 42854,
"s": 42844,
"text": "Bit Magic"
},
{
"code": null,
"e": 42873,
"s": 42854,
"text": "Technical Scripter"
},
{
"code": null,
"e": 42880,
"s": 42873,
"text": "Arrays"
},
{
"code": null,
"e": 42890,
"s": 42880,
"text": "Bit Magic"
},
{
"code": null,
"e": 42988,
"s": 42890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42997,
"s": 42988,
"text": "Comments"
},
{
"code": null,
"e": 43010,
"s": 42997,
"text": "Old Comments"
},
{
"code": null,
"e": 43035,
"s": 43010,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 43055,
"s": 43035,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 43080,
"s": 43055,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 43129,
"s": 43080,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 43167,
"s": 43129,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 43194,
"s": 43167,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 43240,
"s": 43194,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 43308,
"s": 43240,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 43354,
"s": 43308,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
}
] |
DropDownView in Android - GeeksforGeeks | 18 Feb, 2021
DropDownView is another exciting feature used in most Android applications. It is a unique way of representing the menu and other options in animated form. We can get to see the list of options under one heading in DropDownView. In this article, we are going to see how to implement DropDownView in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
A unique way of representing data in the Animated form.
Make it easy to navigate and find many options under one heading.
Large options can be displayed easily.
Attributes
Description
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency and JitPack Repository
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.github.AnthonyFermin:DropDownView:1.0.1’
Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.
allprojects {
repositories {
...
maven { url “https://jitpack.io” }
}
}
After adding this dependency sync your project and now we will move towards its implementation.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--DropDown Menu--> <com.anthonyfdev.dropdownview.DropDownView android:id="@+id/drop_down_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:containerBackgroundColor="@color/purple_200" app:overlayColor="#EEEEEE" /> </LinearLayout>
Step 4: Create new layout resource files
Navigate to the app > res > layout > right-click > New > Layout resource file and name the files as header and footer.
Below is the code for the header.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <!--Header for drop down--> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Amazing" /> </LinearLayout>
Below is the code for the footer.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <!--Items in drop down--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Awesome" /> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Line 1" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Line 2" /> <TextView android:id="@+id/textView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Line 3" /> <TextView android:id="@+id/textView4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Line 4" /> <TextView android:id="@+id/textView5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Line 5" /> <TextView android:id="@+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Line 6" /> <TextView android:id="@+id/textView7" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Line 7" /> </LinearLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.anthonyfdev.dropdownview.DropDownView; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Drop down menu given using id DropDownView dropDownView = (DropDownView) findViewById(R.id.drop_down_view); View collapsedView = LayoutInflater.from(this).inflate(R.layout.header, null, false); View expandedView = LayoutInflater.from(this).inflate(R.layout.footer, null, false); dropDownView.setHeaderView(collapsedView); dropDownView.setExpandedView(expandedView); collapsedView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on click the drop down // will open or close if (dropDownView.isExpanded()) { dropDownView.collapseDropDown(); } else { dropDownView.expandDropDown(); } } }); }}
Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.
android
Android-View
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 25589,
"s": 25116,
"text": "DropDownView is another exciting feature used in most Android applications. It is a unique way of representing the menu and other options in animated form. We can get to see the list of options under one heading in DropDownView. In this article, we are going to see how to implement DropDownView in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25645,
"s": 25589,
"text": "A unique way of representing data in the Animated form."
},
{
"code": null,
"e": 25711,
"s": 25645,
"text": "Make it easy to navigate and find many options under one heading."
},
{
"code": null,
"e": 25750,
"s": 25711,
"text": "Large options can be displayed easily."
},
{
"code": null,
"e": 25761,
"s": 25750,
"text": "Attributes"
},
{
"code": null,
"e": 25773,
"s": 25761,
"text": "Description"
},
{
"code": null,
"e": 25802,
"s": 25773,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25964,
"s": 25802,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26010,
"s": 25964,
"text": "Step 2: Add dependency and JitPack Repository"
},
{
"code": null,
"e": 26129,
"s": 26010,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 26190,
"s": 26129,
"text": "implementation ‘com.github.AnthonyFermin:DropDownView:1.0.1’"
},
{
"code": null,
"e": 26332,
"s": 26190,
"text": "Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section."
},
{
"code": null,
"e": 26346,
"s": 26332,
"text": "allprojects {"
},
{
"code": null,
"e": 26362,
"s": 26346,
"text": " repositories {"
},
{
"code": null,
"e": 26369,
"s": 26362,
"text": " ..."
},
{
"code": null,
"e": 26407,
"s": 26369,
"text": " maven { url “https://jitpack.io” }"
},
{
"code": null,
"e": 26414,
"s": 26407,
"text": " }"
},
{
"code": null,
"e": 26416,
"s": 26414,
"text": "}"
},
{
"code": null,
"e": 26514,
"s": 26416,
"text": "After adding this dependency sync your project and now we will move towards its implementation. "
},
{
"code": null,
"e": 26562,
"s": 26514,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26705,
"s": 26562,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 26709,
"s": 26705,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--DropDown Menu--> <com.anthonyfdev.dropdownview.DropDownView android:id=\"@+id/drop_down_view\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:containerBackgroundColor=\"@color/purple_200\" app:overlayColor=\"#EEEEEE\" /> </LinearLayout>",
"e": 27385,
"s": 26709,
"text": null
},
{
"code": null,
"e": 27426,
"s": 27385,
"text": "Step 4: Create new layout resource files"
},
{
"code": null,
"e": 27545,
"s": 27426,
"text": "Navigate to the app > res > layout > right-click > New > Layout resource file and name the files as header and footer."
},
{
"code": null,
"e": 27588,
"s": 27545,
"text": "Below is the code for the header.xml file:"
},
{
"code": null,
"e": 27592,
"s": 27588,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"10dp\"> <!--Header for drop down--> <TextView android:id=\"@+id/textView2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Amazing\" /> </LinearLayout>",
"e": 28065,
"s": 27592,
"text": null
},
{
"code": null,
"e": 28108,
"s": 28065,
"text": "Below is the code for the footer.xml file:"
},
{
"code": null,
"e": 28112,
"s": 28108,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"10dp\"> <!--Items in drop down--> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Awesome\" /> <TextView android:id=\"@+id/textView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"Line 1\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"Line 2\" /> <TextView android:id=\"@+id/textView3\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Line 3\" /> <TextView android:id=\"@+id/textView4\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Line 4\" /> <TextView android:id=\"@+id/textView5\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Line 5\" /> <TextView android:id=\"@+id/textView6\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Line 6\" /> <TextView android:id=\"@+id/textView7\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Line 7\" /> </LinearLayout>",
"e": 29867,
"s": 28112,
"text": null
},
{
"code": null,
"e": 29915,
"s": 29867,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30105,
"s": 29915,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30110,
"s": 30105,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.anthonyfdev.dropdownview.DropDownView; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Drop down menu given using id DropDownView dropDownView = (DropDownView) findViewById(R.id.drop_down_view); View collapsedView = LayoutInflater.from(this).inflate(R.layout.header, null, false); View expandedView = LayoutInflater.from(this).inflate(R.layout.footer, null, false); dropDownView.setHeaderView(collapsedView); dropDownView.setExpandedView(expandedView); collapsedView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on click the drop down // will open or close if (dropDownView.isExpanded()) { dropDownView.collapseDropDown(); } else { dropDownView.expandDropDown(); } } }); }}",
"e": 31409,
"s": 30110,
"text": null
},
{
"code": null,
"e": 31540,
"s": 31409,
"text": "Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below."
},
{
"code": null,
"e": 31548,
"s": 31540,
"text": "android"
},
{
"code": null,
"e": 31561,
"s": 31548,
"text": "Android-View"
},
{
"code": null,
"e": 31585,
"s": 31561,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31593,
"s": 31585,
"text": "Android"
},
{
"code": null,
"e": 31598,
"s": 31593,
"text": "Java"
},
{
"code": null,
"e": 31617,
"s": 31598,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31622,
"s": 31617,
"text": "Java"
},
{
"code": null,
"e": 31630,
"s": 31622,
"text": "Android"
},
{
"code": null,
"e": 31728,
"s": 31630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31767,
"s": 31728,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31817,
"s": 31767,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31859,
"s": 31817,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31897,
"s": 31859,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 31970,
"s": 31897,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 31985,
"s": 31970,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32029,
"s": 31985,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32051,
"s": 32029,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32087,
"s": 32051,
"text": "Arrays.sort() in Java with examples"
}
] |
File and FileReader in JavaScript? | Following is the code showing file and fileReader in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,.sample {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.result {
color: red;
}
</style>
</head>
<body>
<h1>File and FileReader in JavaScript</h1>
<input type="file" accept="text/*" onchange="displayFile(this)" />
<div class="result"></div>
<br />
<div class="sample"></div>
<h3>Click on the above button to display file and its details</h3>
<script>
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
function displayFile(input) {
let file = input.files[0];
resEle.innerHTML += "File name = " + file.name + "<br>";
resEle.innerHTML += "File size = " + file.size + " bytes <br>";
resEle.innerHTML += "File type = " + file.type + "<br>";
var Reader = new FileReader();
Reader.readAsText(file);
Reader.onload = function () {
sampleEle.innerHTML += Reader.result;
};
Reader.onerror = function () {
sampleEle.innerHTML += Reader.error;
};
}
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘Choose file’ button and choosing a file − | [
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Following is the code showing file and fileReader in JavaScript −"
},
{
"code": null,
"e": 1139,
"s": 1128,
"text": " Live Demo"
},
{
"code": null,
"e": 2450,
"s": 1139,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,.sample {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n .result {\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>File and FileReader in JavaScript</h1>\n<input type=\"file\" accept=\"text/*\" onchange=\"displayFile(this)\" />\n<div class=\"result\"></div>\n<br />\n<div class=\"sample\"></div>\n<h3>Click on the above button to display file and its details</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let sampleEle = document.querySelector(\".sample\");\n function displayFile(input) {\n let file = input.files[0];\n resEle.innerHTML += \"File name = \" + file.name + \"<br>\";\n resEle.innerHTML += \"File size = \" + file.size + \" bytes <br>\";\n resEle.innerHTML += \"File type = \" + file.type + \"<br>\";\n var Reader = new FileReader();\n Reader.readAsText(file);\n Reader.onload = function () {\n sampleEle.innerHTML += Reader.result;\n };\n Reader.onerror = function () {\n sampleEle.innerHTML += Reader.error;\n };\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2501,
"s": 2450,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2560,
"s": 2501,
"text": "On clicking the ‘Choose file’ button and choosing a file −"
}
] |
Sync AWS RDS Postgres to Redshift using AWS DMS | by Axel Furlan | Towards Data Science | Disclaimer: this post assumes some understanding of programming.
When we first started to get to know AWS Redshift, we fell in love for the fast aggregated query processing. This strong advantage meant sky-rocketing our productivity and speed when performing statistical studies or simply data-extractions. So, of course, we turned it into our main data warehouse for all the data sources we managed (Adwords, Salesforce, FBAds, Zendesk, etc.) — all of this, using Stitch as our main ETL tool.
Stitch holds a nice subscription plan of $100, offering process capacity for 5M rows and $20 per additional million rows. Stitch logs and billing invoices tell us we barely reached $180 on a very busy month using all the data sources mentioned above. Most of those months were just plain $100 (no additional million rows used).
Our company develops, maintains and sells its core SaaS product, IncreaseCard. Hosted in the AWS Cloud, our production database resides in AWS RDS, storing between 10 and 20 million new rows every month, and considerably growing.So typically, using Stitch to sync our production database to a Redshift warehouse, would turn out to be painfully expensive for a third-world startup company. Also considering our country’s currency lost a lot of its value against US dollars recently.
We also had another restriction. The company’s developing its second major product, IncreaseConciliación. This one uses the NoSQL Apache Cassandra database to store and process its huge data. The problem is, both products must be synced in order for Conciliación to use transactions extracted by Card. In other words, we had to build a data-lake accessible for consumption by any service to perform syncing operations on-demand.
Many things to take into account, right?
Being a small team of 2 people, the mighty “Data Team”, we get it easy to try and test new things, especially architectures.
We started by using AWS Data Pipeline, a UI based service to build ETLs between a bunch of data sources. Although the process of building an ETL was rather easy, there were a bunch of workarounds that we had to take in order for it to be effective — remember that we have to update every change whether it be an insertion, a deletion or an update. Since you can’t use code here, it became unmaintainable quickly. Furthermore, there isn’t much detailed documentation or clear examples for this service IMO.
We tried to set a Lambda to consume every 15 minutes the Wal log of a replication slot of our Postgres database, and send it to a Kinesis Firehose data stream. It seemed to be all safe and sound until a production process updated more rows than usually expected. We found out that, in these cases, the way the records came from the logical decoding were huge rows full of chunks of changes of the tables involved, causing the function to die of lack of memory every time it tried to load it. We solved this by setting true to the property write_in_chunks of the logical decoding plugin, we used (wal2json), enabling us to partition the incoming JSON log. Long story short, the function could still be terminated unsuccessfully due to not enough time to process the huge transaction. No bueno.
Ok so, let’s head to it.
Our current architecture consists of the following:
A DMS (Database Migration Service) instance replicating on-going changes to Redshift and S3.
The Redshift source endpoint.
An S3 bucket used by DMS as a target endpoint.
A Lambda that triggers every time an object is created in the S3 bucket mentioned above.
(Optional) An SNS topic subscribed to the same event of object creation. This enables you to subscribe anything to that topic, for example, multiple lambdas. For more info, click this link.
For this post to be more “democratic”, I’ll divide it into 2 sections. The first one will be the steps to replicate changes directly to Redshift. The second one, building the S3 data-lake for other services to use. Feel free to read one or the other, or even better, both 😄.
Since I don’t consider myself smarter than people that write AWS documentation, I’ll copy-paste some of their instructions below 🤷♂.
Find your RDS instance, look up the parameter group that this instance applies. Either duplicate or modify the parameter group directly with the following.
1.- Set the rds.logical_replication static parameter to 1. As part of applying this parameter, we also set the parameters wal_level, max_wal_senders, max_replication_slots, andmax_connections. These parameter changes can increase WAL generation, so you should only set therds.logical_replication parameter when you are using logical slots.
2.- Reboot the DB instance for the static rds.logical_replication parameter to take effect.
After rebooting, we should be good to go. A good way to test if everything’s gucci is by running the following line on your database console.
increasecard=> show wal_level; wal_level----------- logical(1 row)
First, we must create the resources that the task is going to use. Create the endpoints (source and target) and the replication instance (basically an EC2 instance that’s in charge of all the dirty work).
The process of creating a replication instance is super straightforward, so I won’t go over it, just make sure to use a VPC that has access to the source and target you intend to use.
For the source endpoint, tick the option that says something like “Select a RDS instance” and effectively, select your source database and fill the fields for the credentials.
For the target endpoint, select Redshift and fill in all the textboxes with Host, Port and credentials.
Great, now we have everything we need, let’s create the task that’s going to migrate and replicate the stuff.
In DMS, press the Create Task button, put it a fancy name and start selecting all the resources we created earlier. For Migration type choose Migrate existing data and replicate ongoing changes, this performs a full migration first and then starts replicating on-going CRUD operations on the target database.
On the selection section, select whatever schema/table you want to use, in my case I’ll just replicate every change within a schema — also, check if the tables have primary keys, DMS may mess up if they don’t have a PK. Use % character as a wildcard (i.e “all tables containing the word ‘foo’ ” would be table = %foo%.
The task can also have transformation rules, it enables you to, for example, change a schema or table name on the target destination.
Ready to unleash it? Hit that create task button and wait for it to start — or start it if you chose not to start when created. The task now is going to fully load the tables into your destination and then start replicating changes. You should see Load complete, replication ongoing as its status when finished migrating.
Aaaaaand...
Voila, done!. Your Redshift warehouse is now enriched by your production RDS data, good job!. At this point, if anything went wrong you can always enable the logging feature of the DMS task to see what happened 😄, just take into account Cloudwatch billing.
You can also check some useful charts that the DMS task presents to us.
Next section is going to be about the creation of the S3 data-lake for other services to consume database changes. If you’re leaving now, thanks for reading and I hope this post was useful to you.
Same as before, create a task that instead of Redshift as a target destination, it’s an S3 bucket.
For the target endpoint, previously create an S3 bucket, and simply put the name of the bucket and the corresponding role to access it. Take into account the service role should have the following policy.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:DeleteObject" ], "Resource": [ "arn:aws:s3:::<name-of-bucket>" ] }, { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::<name-of-bucket>" ] } ]}
On the additional parameters section, put the following addColumnName=true;, including the previous parameters or others that you may want to use.
In this case, choose to Replicate data changes only as migration type, we don’t want to infest our S3 bucket of previous data.
For more info about using S3 as a target for DMS, click here.
Ok, the moment of truth, run your little Frankenstein baby.
The state of the task should be Ongoing replication. If otherwise, check the logs related to the replication instance for errors in the Cloudwatch service.
From now on, if you’re using a staging database instance (which I hope you are), create, update and delete some rows in order for changes to be replicated by the task. This will hopefully conclude in a csv file in the S3 bucket you specified in your destination endpoint.
This file should have something like:
Op, id, field..fieldsI, 1, ...D, 2U, 3, ...
If you’re not, what here we call as salame, you’d realize I stands for Insert, D for delete and U for Update.
The moment you’ve been waiting for (or not). This is where we get to code the function that’s going to parse the CSV document that’s being created on our bucket.
For this part, I suggest you use Serverless, a nice tool to easily deploy Lambda functions using your AWS CLI credentials. It’s as simple as writing a .yml file, hitting serverless deploy and voila.
Now, let’s create our Lambda function and later add the S3 bucket event to trigger the function on every object creation. Also, you may want to add a prefix if you’ve specified that the files are going to be created within a specific folder, just put folder/ on the prefix textbox, and you’re good to go.
Let’s code part of the function that’s going to receive and extract the data from the file uploaded in the bucket.
So, what we first want to do is build our handler function, you know, the usual main() but Lambdably speaking.
This main function is going to receive as a parameter the JSON event that Cloudwatch handles to it, basically saying “Yo, there’s a new file created in the bucket, here’s its key to access it.”
Here’s the sample event that AWS gives us.
And below I paste the Python code that I use to get the final content of the file created in S3.
Now you have the data of the CSV in the file_content variable. If you have experience with parsers, this should be a piece of cake, if that’s not the case for you, I recommend you check this link.
From now on, it’s on your hands. Use a python driver to handle the CRUD operations, processing every row of the CSV impacting the changes on Redshift. For this case, I recommend using functions like execute_values() (psycopg2) to minimize execution time as explained here. Use Lambda environment variables to handle credential secrets for the function to use, remember it’s not a good idea to hardcode them.
What I present to you is just one of the thousand possibilities to achieve the goal of synchronizing databases. If you don’t mind spending some hundreds 💸 on services that handle the ETL process for you, go for it. No really, just go for it.
This architecture serves us with 2 main positive side effects IMO. First one, having tracking information about the changes in your production database, this can never be needless. Nowadays with services like AWS Athena and Glue you can query that data directly via the console. The second one is the ability to connect/trigger any procedure via S3 bucket object creation event — in our case, the IncreaseConciliación team replicating changes in their own Cassandra database.
We’ve come to an end, hopefully, you’ve enjoyed my first article 😄 | [
{
"code": null,
"e": 112,
"s": 47,
"text": "Disclaimer: this post assumes some understanding of programming."
},
{
"code": null,
"e": 541,
"s": 112,
"text": "When we first started to get to know AWS Redshift, we fell in love for the fast aggregated query processing. This strong advantage meant sky-rocketing our productivity and speed when performing statistical studies or simply data-extractions. So, of course, we turned it into our main data warehouse for all the data sources we managed (Adwords, Salesforce, FBAds, Zendesk, etc.) — all of this, using Stitch as our main ETL tool."
},
{
"code": null,
"e": 869,
"s": 541,
"text": "Stitch holds a nice subscription plan of $100, offering process capacity for 5M rows and $20 per additional million rows. Stitch logs and billing invoices tell us we barely reached $180 on a very busy month using all the data sources mentioned above. Most of those months were just plain $100 (no additional million rows used)."
},
{
"code": null,
"e": 1351,
"s": 869,
"text": "Our company develops, maintains and sells its core SaaS product, IncreaseCard. Hosted in the AWS Cloud, our production database resides in AWS RDS, storing between 10 and 20 million new rows every month, and considerably growing.So typically, using Stitch to sync our production database to a Redshift warehouse, would turn out to be painfully expensive for a third-world startup company. Also considering our country’s currency lost a lot of its value against US dollars recently."
},
{
"code": null,
"e": 1782,
"s": 1351,
"text": "We also had another restriction. The company’s developing its second major product, IncreaseConciliación. This one uses the NoSQL Apache Cassandra database to store and process its huge data. The problem is, both products must be synced in order for Conciliación to use transactions extracted by Card. In other words, we had to build a data-lake accessible for consumption by any service to perform syncing operations on-demand."
},
{
"code": null,
"e": 1823,
"s": 1782,
"text": "Many things to take into account, right?"
},
{
"code": null,
"e": 1948,
"s": 1823,
"text": "Being a small team of 2 people, the mighty “Data Team”, we get it easy to try and test new things, especially architectures."
},
{
"code": null,
"e": 2454,
"s": 1948,
"text": "We started by using AWS Data Pipeline, a UI based service to build ETLs between a bunch of data sources. Although the process of building an ETL was rather easy, there were a bunch of workarounds that we had to take in order for it to be effective — remember that we have to update every change whether it be an insertion, a deletion or an update. Since you can’t use code here, it became unmaintainable quickly. Furthermore, there isn’t much detailed documentation or clear examples for this service IMO."
},
{
"code": null,
"e": 3247,
"s": 2454,
"text": "We tried to set a Lambda to consume every 15 minutes the Wal log of a replication slot of our Postgres database, and send it to a Kinesis Firehose data stream. It seemed to be all safe and sound until a production process updated more rows than usually expected. We found out that, in these cases, the way the records came from the logical decoding were huge rows full of chunks of changes of the tables involved, causing the function to die of lack of memory every time it tried to load it. We solved this by setting true to the property write_in_chunks of the logical decoding plugin, we used (wal2json), enabling us to partition the incoming JSON log. Long story short, the function could still be terminated unsuccessfully due to not enough time to process the huge transaction. No bueno."
},
{
"code": null,
"e": 3272,
"s": 3247,
"text": "Ok so, let’s head to it."
},
{
"code": null,
"e": 3324,
"s": 3272,
"text": "Our current architecture consists of the following:"
},
{
"code": null,
"e": 3417,
"s": 3324,
"text": "A DMS (Database Migration Service) instance replicating on-going changes to Redshift and S3."
},
{
"code": null,
"e": 3447,
"s": 3417,
"text": "The Redshift source endpoint."
},
{
"code": null,
"e": 3494,
"s": 3447,
"text": "An S3 bucket used by DMS as a target endpoint."
},
{
"code": null,
"e": 3583,
"s": 3494,
"text": "A Lambda that triggers every time an object is created in the S3 bucket mentioned above."
},
{
"code": null,
"e": 3773,
"s": 3583,
"text": "(Optional) An SNS topic subscribed to the same event of object creation. This enables you to subscribe anything to that topic, for example, multiple lambdas. For more info, click this link."
},
{
"code": null,
"e": 4048,
"s": 3773,
"text": "For this post to be more “democratic”, I’ll divide it into 2 sections. The first one will be the steps to replicate changes directly to Redshift. The second one, building the S3 data-lake for other services to use. Feel free to read one or the other, or even better, both 😄."
},
{
"code": null,
"e": 4182,
"s": 4048,
"text": "Since I don’t consider myself smarter than people that write AWS documentation, I’ll copy-paste some of their instructions below 🤷♂."
},
{
"code": null,
"e": 4338,
"s": 4182,
"text": "Find your RDS instance, look up the parameter group that this instance applies. Either duplicate or modify the parameter group directly with the following."
},
{
"code": null,
"e": 4678,
"s": 4338,
"text": "1.- Set the rds.logical_replication static parameter to 1. As part of applying this parameter, we also set the parameters wal_level, max_wal_senders, max_replication_slots, andmax_connections. These parameter changes can increase WAL generation, so you should only set therds.logical_replication parameter when you are using logical slots."
},
{
"code": null,
"e": 4770,
"s": 4678,
"text": "2.- Reboot the DB instance for the static rds.logical_replication parameter to take effect."
},
{
"code": null,
"e": 4912,
"s": 4770,
"text": "After rebooting, we should be good to go. A good way to test if everything’s gucci is by running the following line on your database console."
},
{
"code": null,
"e": 4979,
"s": 4912,
"text": "increasecard=> show wal_level; wal_level----------- logical(1 row)"
},
{
"code": null,
"e": 5184,
"s": 4979,
"text": "First, we must create the resources that the task is going to use. Create the endpoints (source and target) and the replication instance (basically an EC2 instance that’s in charge of all the dirty work)."
},
{
"code": null,
"e": 5368,
"s": 5184,
"text": "The process of creating a replication instance is super straightforward, so I won’t go over it, just make sure to use a VPC that has access to the source and target you intend to use."
},
{
"code": null,
"e": 5544,
"s": 5368,
"text": "For the source endpoint, tick the option that says something like “Select a RDS instance” and effectively, select your source database and fill the fields for the credentials."
},
{
"code": null,
"e": 5648,
"s": 5544,
"text": "For the target endpoint, select Redshift and fill in all the textboxes with Host, Port and credentials."
},
{
"code": null,
"e": 5758,
"s": 5648,
"text": "Great, now we have everything we need, let’s create the task that’s going to migrate and replicate the stuff."
},
{
"code": null,
"e": 6067,
"s": 5758,
"text": "In DMS, press the Create Task button, put it a fancy name and start selecting all the resources we created earlier. For Migration type choose Migrate existing data and replicate ongoing changes, this performs a full migration first and then starts replicating on-going CRUD operations on the target database."
},
{
"code": null,
"e": 6386,
"s": 6067,
"text": "On the selection section, select whatever schema/table you want to use, in my case I’ll just replicate every change within a schema — also, check if the tables have primary keys, DMS may mess up if they don’t have a PK. Use % character as a wildcard (i.e “all tables containing the word ‘foo’ ” would be table = %foo%."
},
{
"code": null,
"e": 6520,
"s": 6386,
"text": "The task can also have transformation rules, it enables you to, for example, change a schema or table name on the target destination."
},
{
"code": null,
"e": 6842,
"s": 6520,
"text": "Ready to unleash it? Hit that create task button and wait for it to start — or start it if you chose not to start when created. The task now is going to fully load the tables into your destination and then start replicating changes. You should see Load complete, replication ongoing as its status when finished migrating."
},
{
"code": null,
"e": 6854,
"s": 6842,
"text": "Aaaaaand..."
},
{
"code": null,
"e": 7111,
"s": 6854,
"text": "Voila, done!. Your Redshift warehouse is now enriched by your production RDS data, good job!. At this point, if anything went wrong you can always enable the logging feature of the DMS task to see what happened 😄, just take into account Cloudwatch billing."
},
{
"code": null,
"e": 7183,
"s": 7111,
"text": "You can also check some useful charts that the DMS task presents to us."
},
{
"code": null,
"e": 7380,
"s": 7183,
"text": "Next section is going to be about the creation of the S3 data-lake for other services to consume database changes. If you’re leaving now, thanks for reading and I hope this post was useful to you."
},
{
"code": null,
"e": 7479,
"s": 7380,
"text": "Same as before, create a task that instead of Redshift as a target destination, it’s an S3 bucket."
},
{
"code": null,
"e": 7684,
"s": 7479,
"text": "For the target endpoint, previously create an S3 bucket, and simply put the name of the bucket and the corresponding role to access it. Take into account the service role should have the following policy."
},
{
"code": null,
"e": 8173,
"s": 7684,
"text": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\": [ \"s3:PutObject\", \"s3:DeleteObject\" ], \"Resource\": [ \"arn:aws:s3:::<name-of-bucket>\" ] }, { \"Effect\": \"Allow\", \"Action\": [ \"s3:ListBucket\" ], \"Resource\": [ \"arn:aws:s3:::<name-of-bucket>\" ] } ]}"
},
{
"code": null,
"e": 8320,
"s": 8173,
"text": "On the additional parameters section, put the following addColumnName=true;, including the previous parameters or others that you may want to use."
},
{
"code": null,
"e": 8447,
"s": 8320,
"text": "In this case, choose to Replicate data changes only as migration type, we don’t want to infest our S3 bucket of previous data."
},
{
"code": null,
"e": 8509,
"s": 8447,
"text": "For more info about using S3 as a target for DMS, click here."
},
{
"code": null,
"e": 8569,
"s": 8509,
"text": "Ok, the moment of truth, run your little Frankenstein baby."
},
{
"code": null,
"e": 8725,
"s": 8569,
"text": "The state of the task should be Ongoing replication. If otherwise, check the logs related to the replication instance for errors in the Cloudwatch service."
},
{
"code": null,
"e": 8997,
"s": 8725,
"text": "From now on, if you’re using a staging database instance (which I hope you are), create, update and delete some rows in order for changes to be replicated by the task. This will hopefully conclude in a csv file in the S3 bucket you specified in your destination endpoint."
},
{
"code": null,
"e": 9035,
"s": 8997,
"text": "This file should have something like:"
},
{
"code": null,
"e": 9079,
"s": 9035,
"text": "Op, id, field..fieldsI, 1, ...D, 2U, 3, ..."
},
{
"code": null,
"e": 9189,
"s": 9079,
"text": "If you’re not, what here we call as salame, you’d realize I stands for Insert, D for delete and U for Update."
},
{
"code": null,
"e": 9351,
"s": 9189,
"text": "The moment you’ve been waiting for (or not). This is where we get to code the function that’s going to parse the CSV document that’s being created on our bucket."
},
{
"code": null,
"e": 9550,
"s": 9351,
"text": "For this part, I suggest you use Serverless, a nice tool to easily deploy Lambda functions using your AWS CLI credentials. It’s as simple as writing a .yml file, hitting serverless deploy and voila."
},
{
"code": null,
"e": 9855,
"s": 9550,
"text": "Now, let’s create our Lambda function and later add the S3 bucket event to trigger the function on every object creation. Also, you may want to add a prefix if you’ve specified that the files are going to be created within a specific folder, just put folder/ on the prefix textbox, and you’re good to go."
},
{
"code": null,
"e": 9970,
"s": 9855,
"text": "Let’s code part of the function that’s going to receive and extract the data from the file uploaded in the bucket."
},
{
"code": null,
"e": 10081,
"s": 9970,
"text": "So, what we first want to do is build our handler function, you know, the usual main() but Lambdably speaking."
},
{
"code": null,
"e": 10275,
"s": 10081,
"text": "This main function is going to receive as a parameter the JSON event that Cloudwatch handles to it, basically saying “Yo, there’s a new file created in the bucket, here’s its key to access it.”"
},
{
"code": null,
"e": 10318,
"s": 10275,
"text": "Here’s the sample event that AWS gives us."
},
{
"code": null,
"e": 10415,
"s": 10318,
"text": "And below I paste the Python code that I use to get the final content of the file created in S3."
},
{
"code": null,
"e": 10612,
"s": 10415,
"text": "Now you have the data of the CSV in the file_content variable. If you have experience with parsers, this should be a piece of cake, if that’s not the case for you, I recommend you check this link."
},
{
"code": null,
"e": 11020,
"s": 10612,
"text": "From now on, it’s on your hands. Use a python driver to handle the CRUD operations, processing every row of the CSV impacting the changes on Redshift. For this case, I recommend using functions like execute_values() (psycopg2) to minimize execution time as explained here. Use Lambda environment variables to handle credential secrets for the function to use, remember it’s not a good idea to hardcode them."
},
{
"code": null,
"e": 11262,
"s": 11020,
"text": "What I present to you is just one of the thousand possibilities to achieve the goal of synchronizing databases. If you don’t mind spending some hundreds 💸 on services that handle the ETL process for you, go for it. No really, just go for it."
},
{
"code": null,
"e": 11739,
"s": 11262,
"text": "This architecture serves us with 2 main positive side effects IMO. First one, having tracking information about the changes in your production database, this can never be needless. Nowadays with services like AWS Athena and Glue you can query that data directly via the console. The second one is the ability to connect/trigger any procedure via S3 bucket object creation event — in our case, the IncreaseConciliación team replicating changes in their own Cassandra database."
}
] |
Standard SQL in Google BigQuery. Advantages and Examples of Use in... | by Marie Sharapa | Towards Data Science | In 2016, Google BigQuery introduced a new way to communicate with tables: Standard SQL. Until then, BigQuery had its own structured query language called BigQuery SQL (now called Legacy SQL).
At first glance, there isn’t much difference between Legacy and Standard SQL: the names of tables are written a little differently; Standard has slightly stricter grammar requirements (for example, you can’t put a comma before FROM) and more data types. But if you look closely, there are some minor syntax changes that give marketers many advantages.
At OWOX we decided to clarify the answers to the following questions:
What are the advantages of Standard SQL over Legacy SQL?
What are the capabilities of Standard SQL and how is it used?
How can I move from Legacy to Standard SQL?
What other services, syntax features, operators, and functions is Standard SQL compatible with?
How can I use SQL queries for marketing reports?
Standard SQL supports new data types: ARRAY and STRUCT (arrays and nested fields). This means that in BigQuery, it has become easier to work with tables loaded from JSON/Avro files, which often contain multi-level attachments.
A nested field is a mini table inside a larger one:
In the diagram above, the blue and yellow bars are the lines in which mini tables are embedded. Each line is one session. Sessions have common parameters: date, ID number, user device category, browser, operating system, etc. In addition to the general parameters for each session, the hits table is attached to the line.
The hits table contains information about user actions on the site. For example, if a user clicks on a banner, flips through the catalog, opens a product page, puts a product in the basket, or places an order, these actions will be recorded in the hits table.
If a user places an order on the site, information about the order will also be entered in the hits table:
transactionId (number identifying the transaction)
transactionRevenue (total value of the order)
transactionShipping (shipping costs)
Session data tables collected using OWOX BI have a similar structure.
Suppose you want to know the number of orders from users in New York City over the past month. To find out, you need to refer to the hits table and count the number of unique transaction IDs. To extract data from such tables, Standard SQL has an UNNEST function:
#standardSQL SELECT COUNT (DISTINCT hits.transaction.transactionId) -- count the number of unique order numbers; DISTINCT helps to avoid duplicationFROM `project_name.dataset_name.owoxbi_sessions_*` -- refer to the table group (wildcard tables)WHERE ( _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTHS)) -- if we don’t know which dates we need, it’s better to use the function FORMAT_DATE INTERVAL AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) ) AND geoNetwork.city = ‘New York’ -- choose orders made in New York City
If the order information was recorded in a separate table and not in a nested table, you would have to use JOIN to combine the table with order information and the table with session data in order to find out in which sessions orders were made.
If you need to extract data from multi-level nested fields, you can add subqueries with SELECT and WHERE. For example, in OWOX BI session streaming tables, another subtable, product, is written to the hits subtable. The product subtable collects product data that are transmitted with an Enhanced Ecommerce array. If enhanced e-commerce is set up on the site and a user has looked at a product page, characteristics of this product will be recorded in the product subtable.
To get these product characteristics, you’ll need a subquery inside the main query. For each product characteristic, a separate SELECT subquery is created in parentheses:
SELECT column_name1, -- list the other columns you want to receive column_name2, (SELECT productBrand FROM UNNEST(hits.product)) AS hits_product_productBrand, (SELECT productRevenue FROM UNNEST(hits.product)) AS hits_product_productRevenue, -- list product features (SELECT localProductRevenue FROM UNNEST(hits.product)) AS hits_product_localProductRevenue, (SELECT productPrice FROM UNNEST(hits.product)) AS hits_product_productPrice,FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD`
Thanks to the capabilities of Standard SQL, it’s easier to build query logic and write code. For comparison, in Legacy SQL, you would need to write this type of ladder:
SELECT column_name1, column_name2, column_name3 FROM ( SELECT table_name.some_column AS column1... FROM table_name)
Using Standard SQL, you can access BigQuery tables directly from Google Bigtable, Google Cloud Storage, Google Drive, and Google Sheets.That is, instead of loading the entire table into BigQuery, you can delete the data with one single query, select the parameters you need, and upload them to cloud storage.
If you need to use a formula that isn’t documented, User Defined Functions (UDF) will help you. In our practice, this happens rarely, since the Standard SQL documentation covers almost all tasks of digital analytics.
In Standard SQL, user-defined functions can be written in SQL or JavaScript; Legacy SQL only supports JavaScript. The arguments of these functions are columns, and the values they take are the result of manipulating columns. In Standard SQL, functions can be written in the same window as queries.
In Legacy SQL, JOIN conditions can be based on equality or column names. In addition to these options, the Standard SQL dialect supports JOIN by inequality and by arbitrary expression.
For example, to identify unfair CPA partners, we can select sessions in which the source was replaced within 60 seconds of the transaction. To do this in Standard SQL, we can add an inequality to the JOIN condition:
#standardSQLSELECT *FROM ( SELECT traff.clientId AS clientId, traff.page_path AS pagePath, traff.traffic_source AS startSource, traff.traffic_medium AS startMedium, traff.time AS startTime, aff.evAction AS evAction, aff.evSource AS finishSource, aff.evMedium AS finishMedium, aff.evCampaign AS finishCampaign, aff.time AS finishTime, aff.isTransaction AS isTransaction, aff.pagePath AS link, traff.time-aff.time AS diff FROM ( SELECT fullVisitorID AS clientId, h.page.pagePath AS page_path, trafficSource.source AS traffic_source, trafficSource.medium AS traffic_medium, trafficSource.campaign AS traffic_campaign, date, SAFE_CAST(visitStartTime+h.time/1000 AS INT64) AS time FROM `demoproject.google_analytics_sample.ga_sessions_20190301`, UNNEST (hits) AS h WHERE trafficSource.medium != 'cpa' ) AS traffJOIN ( SELECT total.date date, total.time time, total.clientId AS clientId, total.eventAction AS evAction, total.source AS evSource, total.medium AS evMedium, total.campaign AS evCampaign, tr.eventAction AS isTransaction, total.page_path AS pagePath FROM ( SELECT fullVisitorID AS clientId, h.page.pagePath AS page_path, h.eventInfo.eventAction AS eventAction, trafficSource.source AS source, trafficSource.medium AS medium, trafficSource.campaign AS campaign, date, SAFE_CAST(visitStartTime+h.time/1000 AS INT64) AS time FROM `demoproject.google_analytics_sample.ga_sessions_20190301`, UNNEST(hits) AS h WHERE trafficSource.medium ='cpa' ) AS totalLEFT JOIN ( SELECT fullVisitorID AS clientId, date, h.eventInfo.eventAction AS eventAction, h.page.pagePath pagePath, SAFE_CAST(visitStartTime+h.time/1000 AS INT64) AS time FROM `demoproject.google_analytics_sample.ga_sessions_20190301`, UNNEST(hits) AS h WHERE h.eventInfo.eventAction = 'typ_page' AND h.type = 'EVENT' GROUP BY 1, 2, 3, 4, 5 ) AS trON total.clientId=tr.clientIdAND total.date=tr.dateAND tr.time>total.time -- JOIN tables by inequality. Pass the additional WHERE clause that was needed in Legacy SQLWHERE tr.eventAction = 'typ_page' ) AS affON traff.clientId = aff.clientId)WHERE diff> -60AND diff<0 GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ORDER BY clientId, finishTime
The only limitation of Standard SQL with respect to JOIN is that it doesn’t allow semi-join with subqueries of the form WHERE column IN (SELECT ...):
#legacySQLSELECT mother_age, COUNT(mother_age) totalFROM [bigquery-public-data:samples.natality]WHERE -- such a construction cannot be used in Standard SQL state IN (SELECT state FROM (SELECT state, COUNT(state) total FROM [bigquery-public-data:samples.natality] GROUP BY state ORDER BY total DESC LIMIT 10)) AND mother_age > 50GROUP BY mother_ageORDER BY mother_age DESC
Some functions in Legacy SQL return NULL if the condition is incorrect. For example, if division by zero has crept into your calculations, the query will be executed and NULL entries will appear in the resulting rows of the table. This may mask problems in the query or in the data.
The logic of Standard SQL is more straightforward. If a condition or input data is incorrect, the query will generate an error, for example «division by zero,» so you can quickly correct the query. The following checks are embedded in Standard SQL:
Valid values for +, -, ×, SUM, AVG, STDEV
Division by zero
JOIN queries written in Standard SQL are faster than those written in Legacy SQL thanks to preliminary filtering of incoming data. First, the query selects the rows that match the JOIN conditions, then processes them.In the future, Google BigQuery will work on improving the speed and performance of queries only for Standard SQL.
Data Manipulation Language (DML) functions are available in Standard SQL. This means that you can update tables and add or remove rows from them through the same window in which you write queries. For example, using DML, you can combine data from two tables into one:
#standardSQLMERGE dataset.Inventory AS TUSING dataset.NewArrivals AS SON T.ProductID = S.ProductIDWHEN MATCHED THEN UPDATE SET quantity = T.quantity + S.quantityWHEN NOT MATCHED THEN INSERT (ProductID, quantity) VALUES (ProductID, quantity)
With Standard SQL, complex queries can be started not only with SELECT but also with WITH, making code easier to read, comment, and understand. This also means it’s easier to prevent your own and correct others’ mistakes.
#standardSQLWITH total_1 AS ( -- the first subquery in which the intermediate indicator will be calculated SELECT id, metric1, SUM(metric2) AS total_sum1 FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD` GROUP BY id, metric),total_2 AS ( -- the second subquery SELECT id, metric1, SUM(metric2) AS total_sum2 FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD` GROUP BY id, metric1),total_3 AS ( -- the third subquery SELECT id, metric, SUM(metric2) AS total_sum3 FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD` GROUP BY id, metric)SELECT *,ROUND(100*( total_2.total_sum2 - total_3.total_sum3) / total_3.total_sum3, 3) AS difference -- get the difference index: subtract the value of the second subquery from the value of the third; divide by the value of the third FROM total_1ORDER BY 1, 2
It’s convenient to work with the WITH operator if you have calculations that are done in several stages. First, you can collect intermediate metrics in subqueries, then do the final calculations.
The Google Cloud Platform (GCP), which includes BigQuery, is a full-cycle platform for working with big data, from organizing a data warehouse or data cloud to running scientific experiments and predictive and prescriptive analytics. With the introduction of Standard SQL, BigQuery is expanding its audience. Working with GCP is becoming more interesting for marketing analysts, product analysts, data scientists, and teams of other specialists.
At OWOX BI, we often work with tables compiled using the standard Google Analytics 360 export to Google BigQuery or the OWOX BI Pipeline. In the examples below, we’ll look at the specifics of SQL queries for such data.
In Google BigQuery, user behavior data for your site is stored in wildcard tables (tables with an asterisk); a separate table is formed for each day. These tables have the same name: only the suffix is different. The suffix is the date in the format YYYYMMDD. For example, the table owoxbi_sessions_20190301 contains data on sessions for March 1, 2019.
We can refer directly to a group of such tables in one request in order to obtain data, for example, from February 1 through February 28, 2019. To do this, we need to replace YYYYMMDD with an * in FROM, and in WHERE, we need to specify the table suffixes for the start and end of the time interval:
#standardSQLSELECT sessionId, FROM `project_name.dataset_name.owoxbi_sessions_*`WHERE _TABLE_SUFFIX BETWEEN �' AND �'
The specific dates for which we want to collect data are not always known to us. For example, every week we might need to analyze data for the last three months. To do this, we can use the FORMAT_DATE function:
#standardSQLSELECT <enumerate field names>FROM `project_name.dataset_name.owoxbi_sessions_*`WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 3 MONTHS))ANDFORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
After BETWEEN, we record the suffix of the first table. The phrase CURRENT_DATE (), INTERVAL 3 MONTHS means «select data for the last 3 months from the current date.» The second table suffix is formatted after AND. It’s needed to mark the end of the interval as yesterday: CURRENT_DATE (), INTERVAL 1 DAY.
User parameters and metrics in Google Analytics Export tables are written to the nested hits table and to the customDimensions and customMetrics subtables. All custom dimensions are recorded in two columns: one for the number of parameters collected on the site, the second for their values. Here’s what all the parameters transmitted with one hit look like:
In order to unpack them and write the necessary parameters in separate columns, we use the following SQL query:
-- Custom Dimensions (in the line below index - the number of the user variable, which is set in the Google Analytics interface; dimension1 is the name of the custom parameter, which you can change as you like. For each subsequent parameter, you need to write the same line: (SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customDimensions)) AS dimension1, -- Custom Metrics: the index below is the number of the user metric specified in the Google Analytics interface; metric1 is the name of the metric, which you can change as you like. For each of the following metrics, you need to write the same line: (SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customMetrics)) AS metric1
Here’s what it looks like in the request:
#standardSQLSELECT <column name1>,<column_name2>, -- list column names(SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customDimensions)) AS page_type,(SELECT MAX(IF(index=2, value, NULL)) FROM UNNEST(hits.customDimensions)) AS visitor_type, -- produce the necessary custom dimensions(SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customMetrics)) AS metric1 -- produce the necessary custom metrics<column_name3> -- if you need more columns, continue to listFROM `project_name.dataset_name.owoxbi_sessions_20190201`
In the screenshot below, we’ve selected parameters 1 and 2 from Google Analytics 360 demo data in Google BigQuery and called them page_type and client_id. Each parameter is recorded in a separate column:
Such calculations are useful if you plan to visualize data in Google Data Studio and filter by city and device category. This is easy to do with the COUNT window function:
#standardSQLSELECT<column_name 1>, -- choose any columns COUNT (DISTINCT sessionId) AS total_sessions, -- summarize the session IDs to find the total number of sessionsCOUNT(DISTINCT sessionId) OVER(PARTITION BY date, geoNetwork.city, session.device.deviceCategory, trafficSource.source, trafficSource.medium, trafficSource.campaign) AS part_sessions -- summarize the number of sessions by campaign, channel, traffic source, city, and device categoryFROM `project_name.dataset_name.owoxbi_sessions_20190201`
Suppose you collect data on completed orders in several BigQuery tables: one collects all orders from Store A, the other collects orders from Store B. You want to combine them into one table with these columns:
client_id — a number that identifies a unique buyer
transaction_created — order creation time in TIMESTAMP format
transaction_id — order number
is_approved — whether the order was confirmed
transaction_revenue — order amount
In our example orders from January 1, 2018, to yesterday must be in the table. To do this, select the appropriate columns from each group of tables, assign them the same name, and combine the results with UNION ALL:
#standardSQLSELECT cid AS client_id, order_time AS transaction_created,order_status AS is_approved,order_number AS transaction_idFROM `project_name.dataset_name.table1_*`WHERE ( _TABLE_SUFFIX BETWEEN �' AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) )UNION ALL SELECTuserId AS client_id,created_timestamp AS transaction_created,operator_mark AS is_approved,transactionId AS transaction_idFROM `project_name.dataset_name.table1_*`WHERE ( _TABLE_SUFFIX BETWEEN �' AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) )ORDER BY transaction_created DESC
When data enters Google Analytics, the system automatically determines the group to which a particular transition belongs: Direct, Organic Search, Paid Search, and so on. To identify a group of channels, Google Analytics looks at the UTM tags of transitions, namely utm_source and utm_medium. You can read more about channel groups and definition rules in Google Analytics Help.
If OWOX BI clients want to assign their own names to groups of channels, we create a dictionary, which transition belongs to a specific channel. To do this, we use the conditional CASE operator and the REGEXP_CONTAINS function. This function selects the values in which the specified regular expression occurs.
We recommend taking names from your list of sources in Google Analytics. Here’s an example of how to add such conditions to the request body:
#standardSQLSELECT CASE WHEN (REGEXP_CONTAINS (source, 'yandex') AND medium = 'referral' THEN 'Organic Search' WHEN (REGEXP_CONTAINS (source, 'yandex.market')) AND medium = 'referral' THEN 'Referral'WHEN (REGEXP_CONTAINS (source, '^(go.mail.ru|google.com)$') AND medium = 'referral') THEN 'Organic Search'WHEN medium = 'organic' THEN 'Organic Search'WHEN (medium = 'cpc') THEN 'Paid Search'WHEN REGEXP_CONTAINS (medium, '^(sending|email|mail)$') THEN 'Email' WHEN REGEXP_CONTAINS (source, '(mail|email|Mail)') THEN 'Email' WHEN REGEXP_CONTAINS (medium, '^(cpa)$') THEN 'Affiliate' WHEN medium = 'social' THEN 'Social' WHEN source = '(direct)' THEN 'Direct' WHEN REGEXP_CONTAINS (medium, 'banner|cpm') THEN 'Display' ELSE 'Other' END channel_group -- the name of the column in which the channel groups are writtenFROM `project_name.dataset_name.owoxbi_sessions_20190201`
If you haven’t switched to Standard SQL yet, you can do it at any time. The main thing is to avoid mixing dialects in one request.
Legacy SQL is used by default in the old BigQuery interface. To switch between dialects, click Show Options under the query input field and uncheck the Use Legacy SQL box next to SQL Dialect.
The new interface uses Standard SQL by default. Here, you need to go to the More tab to switch dialects:
If you haven’t ticked the request settings, you can start with the desired prefix (#standardSQL or #legacySQL):
#standardSQLSELECT weight_pounds, state, year, gestation_weeksFROM `bigquery-public-data.samples.natality`ORDER BY weight_pounds DESCLIMIT 10;
In this case, Google BigQuery will ignore the settings in the interface and run the query using the dialect specified in the prefix.
If you have views or saved queries that are launched on a schedule using Apps Script, don’t forget to change the value of useLegacySql to false in the script:
var job = {configuration: { query: { query: 'INSERT INTO MyDataSet.MyFooBarTable (Id, Foo, Date) VALUES (1, \'bar\', current_Date);', useLegacySql: false }
If you work with Google BigQuery not with tables but with views, those views can’t be accessed in the Standard SQL dialect. That is, if your presentation is written in Legacy SQL, you can’t write requests to it in Standard SQL.
To transfer a view to standard SQL, you need to manually rewrite the query by which it was created. The easiest way to do this is through the BigQuery interface.
1. Open the view:
2. Click Details. The query text should open, and the Edit Query button will appear below:
Now you can edit the request according to the rules of Standard SQL.If you plan to continue using the request as a presentation, click Save View after you’ve finished editing.
Thanks to the implementation of Standard SQL, you can directly access data stored in other services directly from BigQuery:
Google Cloud Storage log files
Transactional records in Google Bigtable
Data from other sources
This allows you to use Google Cloud Platform products for any analytical tasks, including predictive and prescriptive analytics based on machine learning algorithms.
The query structure in the Standard dialect is almost the same as in Legacy:
The names of the tables and view are separated with a period (full stop), and the whole query is enclosed in grave accents: `project_name.data_name_name.table_name``bigquery-public-data.samples.natality`
The full syntax of the query, with explanations of what can be included in each operator, is compiled as a schema in the BigQuery documentation.
Features of Standard SQL syntax:
Commas are needed to list fields in the SELECT statement.
If you use the UNNEST operator after FROM , a comma or JOIN is placed before UNNEST.
You can’t put a comma before FROM.
A comma between two queries equals a CROSS JOIN, so be careful with it.
JOIN can be done not only by column or equality but by arbitrary expressions and inequality.
It’s possible to write complex subqueries in any part of the SQL expression (in SELECT, FROM, WHERE, etc.). In practice, it’s not yet possible to use expressions like WHERE column_name IN (SELECT ...) as you can in other databases.
In Standard SQL, operators define the type of data. For example, an array is always written in brackets []. Operators are used for comparison, matching the logical expression (NOT, OR, AND), and in arithmetic calculations.
Standard SQL supports more features than Legacy: traditional aggregation (sum, number, minimum, maximum); mathematical, string, and statistical functions; and rare formats such as HyperLogLog ++.
In the Standard dialect, there are more functions for working with dates and TIMESTAMP. A complete list of features is provided in Google’s documentation. The most commonly used functions are for working with dates, strings, aggregation, and window.
1. Aggregation functions
COUNT (DISTINCT column_name) counts the number of unique values in a column. For example, say we need to count the number of sessions from mobile devices on March 1, 2019. Since a session number can be repeated on different lines, we want to count only the unique session number values:
#standardSQLSELECT COUNT (DISTINCT sessionId) AS sessionsFROM `project_name.dataset_name.owoxbi_sessions_20190301`WHERE device.deviceCategory = 'mobile'
SUM (column_name) — the sum of the values in the column
#standardSQLSELECT SUM (hits.transaction.transactionRevenue) AS revenueFROM `project_name.dataset_name.owoxbi_sessions_20190301`,UNNEST (hits) AS hits -- unpacking the nested field hitsWHERE device.deviceCategory = 'mobile'
MIN (column_name) | MAX (column_name) — the minimum and maximum value in the column. These functions are convenient for checking the spread of data in a table.
2. Window (analytical) functions
Analytical functions consider values not for the entire table but for a certain window — a set of rows that you’re interested in. That is, you can define segments within a table. For example, you can calculate SUM (revenue) not for all lines but for cities, device categories, and so on. You can turn the analytic functions SUM, COUNT, and AVG as well as other aggregation functions by adding the OVER condition (PARTITION BY column_name) to them.
For example, you need to count the number of sessions by traffic source, channel, campaign, city, and device category. In this case, we can use the following expression:
SELECT date, geoNetwork.city, t.device.deviceCategory, trafficSource.source, trafficSource.medium, trafficSource.campaign,COUNT(DISTINCT sessionId) OVER(PARTITION BY date, geoNetwork.city, session.device.deviceCategory, trafficSource.source, trafficSource.medium, trafficSource.campaign) AS segmented_sessionsFROM `project_name.dataset_name.owoxbi_sessions_20190301` t
OVER determines the window for which calculations will be made. PARTITION BY indicates which rows should be grouped for calculation. In some functions, it’s necessary to specify the order of grouping with ORDER BY.
For a complete list of window functions, see the BigQuery documentation.
3. String functions
These are useful when you need to change text, format the text in a line, or glue the values of columns. For example, string functions are great if you want to generate a unique session identifier from the standard Google Analytics 360 export data. Let’s consider the most popular string functions.
SUBSTR cuts part of the string. In the request, this function is written as SUBSTR (string_name, 0.4). The first number indicates how many characters to skip from the beginning of the line, and the second number indicates how many digits to cut. For example, say you have a date column that contains dates in the STRING format. In this case, the dates look like this: 20190103. If you want to extract a year from this line, SUBSTR will help you:
#standardSQLSELECTSUBSTR(date,0,4) AS yearFROM `project_name.dataset_name.owoxbi_sessions_20190301`
CONCAT (column_name, etc.) glues values. Let’s use the date column from the previous example. Suppose you want all dates to be recorded like this: 2019–03–01. To convert dates from their current format to this format, two string functions can be used: first, cut the necessary pieces of the string with SUBSTR, then glue them through the hyphen:
#standardSQLSELECTCONCAT(SUBSTR(date,0,4),"-",SUBSTR(date,5,2),"-",SUBSTR(date,7,2)) AS dateFROM `project_name.dataset_name.owoxbi_sessions_20190301`
REGEXP_CONTAINS returns the values of columns in which the regular expression occurs:
#standardSQLSELECT CASEWHEN REGEXP_CONTAINS (medium, '^(sending|email|mail)$') THEN 'Email' WHEN REGEXP_CONTAINS (source, '(mail|email|Mail)') THEN 'Email' WHEN REGEXP_CONTAINS (medium, '^(cpa)$') THEN 'Affiliate'ELSE 'Other'END Channel_groupsFROM `project_name.dataset_name.owoxbi_sessions_20190301`
This function can be used in both SELECT and WHERE. For example, in WHERE, you can select specific pages with it:
WHERE REGEXP_CONTAINS(hits.page.pagePath, 'land[123]/|/product-order')
4. Date functions
Often, dates in tables are recorded in STRING format. If you plan to visualize results in Google Data Studio, the dates in the table need to be converted to DATE format using the PARSE_DATE function.
PARSE_DATE converts a STRING of the 1900–01–01 format to the DATE format.If the dates in your tables look different (for example, 19000101 or 01_01_1900), you must first convert them to the specified format.
#standardSQLSELECT PARSE_DATE('%Y-%m-%d', date) AS date_newFROM `project_name.dataset_name.owoxbi_sessions_20190301`
DATE_DIFF calculates how much time has passed between two dates in days, weeks, months, or years. It’s useful if you need to determine the interval between when a user saw advertising and placed an order. Here’s how the function looks in a request:
#standardSQL SELECT DATE_DIFF( PARSE_DATE('%Y%m%d', date1), PARSE_DATE('%Y%m%d', date2), DAY ) days -- convert the date1 and date2 lines to the DATE format; choose units to show the difference (DAY, WEEK, MONTH, etc.)FROM `project_name.dataset_name.owoxbi_sessions_20190301`
If you want to learn more about the listed functions, read BigQuery Google Features — A Detailed Review.
The Standard SQL dialect allows businesses to extract maximum information from data with deep segmentation, technical audits, marketing KPI analysis, and identification of unfair contractors in CPA networks. Here are examples of business problems in which SQL queries on data collected in Google BigQuery will help you.
1. ROPO analysis: evaluate the contribution of online campaigns to offline sales. To perform ROPO analysis, you need to combine data on online user behavior with data from your CRM, call tracking system, and mobile application.
If there’s a key in one and the second base — a common parameter that is unique for each user (for example, User ID) — you can track:which users visited the site before buying goods in the storehow users behaved on the sitehow long users took to make a purchase decisionwhat campaigns had the greatest increase on offline purchases.
2. Segment customers by any combination of parameters, from behavior on the site (pages visited, products viewed, number of visits to the site before buying) to loyalty card number and purchased items.
3. Find out which CPA partners are working in bad faith and replacing UTM tags.
4. Analyze the progress of users through the sales funnel.
We’ve prepared a selection of queries in Standard SQL dialect. If you already collect data from your site, from advertising sources, and from your CRM system in Google BigQuery, you can use these templates to solve your business problems. Simply replace the project name, dataset, and table in BigQuery with your own. In the collection, you’ll receive 11 SQL queries.
For data collected using standard export from Google Analytics 360 to Google BigQuery:
User actions in the context of any parameters
Statistics on key user actions
Users who viewed specific product pages
Actions of users who bought a particular product
Set up the funnel with any necessary steps
Effectiveness of the internal search site
For data collected in Google BigQuery using OWOX BI:
Attributed consumption by source and channel
Average cost of attracting a visitor by city
ROAS for gross profit by source and channel
Number of orders in the CRM by payment method and delivery method
Average delivery time by city | [
{
"code": null,
"e": 364,
"s": 172,
"text": "In 2016, Google BigQuery introduced a new way to communicate with tables: Standard SQL. Until then, BigQuery had its own structured query language called BigQuery SQL (now called Legacy SQL)."
},
{
"code": null,
"e": 716,
"s": 364,
"text": "At first glance, there isn’t much difference between Legacy and Standard SQL: the names of tables are written a little differently; Standard has slightly stricter grammar requirements (for example, you can’t put a comma before FROM) and more data types. But if you look closely, there are some minor syntax changes that give marketers many advantages."
},
{
"code": null,
"e": 786,
"s": 716,
"text": "At OWOX we decided to clarify the answers to the following questions:"
},
{
"code": null,
"e": 843,
"s": 786,
"text": "What are the advantages of Standard SQL over Legacy SQL?"
},
{
"code": null,
"e": 905,
"s": 843,
"text": "What are the capabilities of Standard SQL and how is it used?"
},
{
"code": null,
"e": 949,
"s": 905,
"text": "How can I move from Legacy to Standard SQL?"
},
{
"code": null,
"e": 1045,
"s": 949,
"text": "What other services, syntax features, operators, and functions is Standard SQL compatible with?"
},
{
"code": null,
"e": 1094,
"s": 1045,
"text": "How can I use SQL queries for marketing reports?"
},
{
"code": null,
"e": 1321,
"s": 1094,
"text": "Standard SQL supports new data types: ARRAY and STRUCT (arrays and nested fields). This means that in BigQuery, it has become easier to work with tables loaded from JSON/Avro files, which often contain multi-level attachments."
},
{
"code": null,
"e": 1373,
"s": 1321,
"text": "A nested field is a mini table inside a larger one:"
},
{
"code": null,
"e": 1695,
"s": 1373,
"text": "In the diagram above, the blue and yellow bars are the lines in which mini tables are embedded. Each line is one session. Sessions have common parameters: date, ID number, user device category, browser, operating system, etc. In addition to the general parameters for each session, the hits table is attached to the line."
},
{
"code": null,
"e": 1955,
"s": 1695,
"text": "The hits table contains information about user actions on the site. For example, if a user clicks on a banner, flips through the catalog, opens a product page, puts a product in the basket, or places an order, these actions will be recorded in the hits table."
},
{
"code": null,
"e": 2062,
"s": 1955,
"text": "If a user places an order on the site, information about the order will also be entered in the hits table:"
},
{
"code": null,
"e": 2113,
"s": 2062,
"text": "transactionId (number identifying the transaction)"
},
{
"code": null,
"e": 2159,
"s": 2113,
"text": "transactionRevenue (total value of the order)"
},
{
"code": null,
"e": 2196,
"s": 2159,
"text": "transactionShipping (shipping costs)"
},
{
"code": null,
"e": 2266,
"s": 2196,
"text": "Session data tables collected using OWOX BI have a similar structure."
},
{
"code": null,
"e": 2529,
"s": 2266,
"text": "Suppose you want to know the number of orders from users in New York City over the past month. To find out, you need to refer to the hits table and count the number of unique transaction IDs. To extract data from such tables, Standard SQL has an UNNEST function:"
},
{
"code": null,
"e": 3114,
"s": 2529,
"text": "#standardSQL SELECT COUNT (DISTINCT hits.transaction.transactionId) -- count the number of unique order numbers; DISTINCT helps to avoid duplicationFROM `project_name.dataset_name.owoxbi_sessions_*` -- refer to the table group (wildcard tables)WHERE ( _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTHS)) -- if we don’t know which dates we need, it’s better to use the function FORMAT_DATE INTERVAL AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) ) AND geoNetwork.city = ‘New York’ -- choose orders made in New York City"
},
{
"code": null,
"e": 3359,
"s": 3114,
"text": "If the order information was recorded in a separate table and not in a nested table, you would have to use JOIN to combine the table with order information and the table with session data in order to find out in which sessions orders were made."
},
{
"code": null,
"e": 3833,
"s": 3359,
"text": "If you need to extract data from multi-level nested fields, you can add subqueries with SELECT and WHERE. For example, in OWOX BI session streaming tables, another subtable, product, is written to the hits subtable. The product subtable collects product data that are transmitted with an Enhanced Ecommerce array. If enhanced e-commerce is set up on the site and a user has looked at a product page, characteristics of this product will be recorded in the product subtable."
},
{
"code": null,
"e": 4004,
"s": 3833,
"text": "To get these product characteristics, you’ll need a subquery inside the main query. For each product characteristic, a separate SELECT subquery is created in parentheses:"
},
{
"code": null,
"e": 4507,
"s": 4004,
"text": "SELECT column_name1, -- list the other columns you want to receive column_name2, (SELECT productBrand FROM UNNEST(hits.product)) AS hits_product_productBrand, (SELECT productRevenue FROM UNNEST(hits.product)) AS hits_product_productRevenue, -- list product features (SELECT localProductRevenue FROM UNNEST(hits.product)) AS hits_product_localProductRevenue, (SELECT productPrice FROM UNNEST(hits.product)) AS hits_product_productPrice,FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD`"
},
{
"code": null,
"e": 4676,
"s": 4507,
"text": "Thanks to the capabilities of Standard SQL, it’s easier to build query logic and write code. For comparison, in Legacy SQL, you would need to write this type of ladder:"
},
{
"code": null,
"e": 4799,
"s": 4676,
"text": "SELECT column_name1, column_name2, column_name3 FROM ( SELECT table_name.some_column AS column1... FROM table_name)"
},
{
"code": null,
"e": 5108,
"s": 4799,
"text": "Using Standard SQL, you can access BigQuery tables directly from Google Bigtable, Google Cloud Storage, Google Drive, and Google Sheets.That is, instead of loading the entire table into BigQuery, you can delete the data with one single query, select the parameters you need, and upload them to cloud storage."
},
{
"code": null,
"e": 5325,
"s": 5108,
"text": "If you need to use a formula that isn’t documented, User Defined Functions (UDF) will help you. In our practice, this happens rarely, since the Standard SQL documentation covers almost all tasks of digital analytics."
},
{
"code": null,
"e": 5625,
"s": 5325,
"text": "In Standard SQL, user-defined functions can be written in SQL or JavaScript; Legacy SQL only supports JavaScript. The arguments of these functions are columns, and the values they take are the result of manipulating columns. In Standard SQL, functions can be written in the same window as queries."
},
{
"code": null,
"e": 5810,
"s": 5625,
"text": "In Legacy SQL, JOIN conditions can be based on equality or column names. In addition to these options, the Standard SQL dialect supports JOIN by inequality and by arbitrary expression."
},
{
"code": null,
"e": 6026,
"s": 5810,
"text": "For example, to identify unfair CPA partners, we can select sessions in which the source was replaced within 60 seconds of the transaction. To do this in Standard SQL, we can add an inequality to the JOIN condition:"
},
{
"code": null,
"e": 8297,
"s": 6026,
"text": "#standardSQLSELECT *FROM ( SELECT traff.clientId AS clientId, traff.page_path AS pagePath, traff.traffic_source AS startSource, traff.traffic_medium AS startMedium, traff.time AS startTime, aff.evAction AS evAction, aff.evSource AS finishSource, aff.evMedium AS finishMedium, aff.evCampaign AS finishCampaign, aff.time AS finishTime, aff.isTransaction AS isTransaction, aff.pagePath AS link, traff.time-aff.time AS diff FROM ( SELECT fullVisitorID AS clientId, h.page.pagePath AS page_path, trafficSource.source AS traffic_source, trafficSource.medium AS traffic_medium, trafficSource.campaign AS traffic_campaign, date, SAFE_CAST(visitStartTime+h.time/1000 AS INT64) AS time FROM `demoproject.google_analytics_sample.ga_sessions_20190301`, UNNEST (hits) AS h WHERE trafficSource.medium != 'cpa' ) AS traffJOIN ( SELECT total.date date, total.time time, total.clientId AS clientId, total.eventAction AS evAction, total.source AS evSource, total.medium AS evMedium, total.campaign AS evCampaign, tr.eventAction AS isTransaction, total.page_path AS pagePath FROM ( SELECT fullVisitorID AS clientId, h.page.pagePath AS page_path, h.eventInfo.eventAction AS eventAction, trafficSource.source AS source, trafficSource.medium AS medium, trafficSource.campaign AS campaign, date, SAFE_CAST(visitStartTime+h.time/1000 AS INT64) AS time FROM `demoproject.google_analytics_sample.ga_sessions_20190301`, UNNEST(hits) AS h WHERE trafficSource.medium ='cpa' ) AS totalLEFT JOIN ( SELECT fullVisitorID AS clientId, date, h.eventInfo.eventAction AS eventAction, h.page.pagePath pagePath, SAFE_CAST(visitStartTime+h.time/1000 AS INT64) AS time FROM `demoproject.google_analytics_sample.ga_sessions_20190301`, UNNEST(hits) AS h WHERE h.eventInfo.eventAction = 'typ_page' AND h.type = 'EVENT' GROUP BY 1, 2, 3, 4, 5 ) AS trON total.clientId=tr.clientIdAND total.date=tr.dateAND tr.time>total.time -- JOIN tables by inequality. Pass the additional WHERE clause that was needed in Legacy SQLWHERE tr.eventAction = 'typ_page' ) AS affON traff.clientId = aff.clientId)WHERE diff> -60AND diff<0 GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ORDER BY clientId, finishTime"
},
{
"code": null,
"e": 8447,
"s": 8297,
"text": "The only limitation of Standard SQL with respect to JOIN is that it doesn’t allow semi-join with subqueries of the form WHERE column IN (SELECT ...):"
},
{
"code": null,
"e": 8999,
"s": 8447,
"text": "#legacySQLSELECT mother_age, COUNT(mother_age) totalFROM [bigquery-public-data:samples.natality]WHERE -- such a construction cannot be used in Standard SQL state IN (SELECT state FROM (SELECT state, COUNT(state) total FROM [bigquery-public-data:samples.natality] GROUP BY state ORDER BY total DESC LIMIT 10)) AND mother_age > 50GROUP BY mother_ageORDER BY mother_age DESC"
},
{
"code": null,
"e": 9282,
"s": 8999,
"text": "Some functions in Legacy SQL return NULL if the condition is incorrect. For example, if division by zero has crept into your calculations, the query will be executed and NULL entries will appear in the resulting rows of the table. This may mask problems in the query or in the data."
},
{
"code": null,
"e": 9531,
"s": 9282,
"text": "The logic of Standard SQL is more straightforward. If a condition or input data is incorrect, the query will generate an error, for example «division by zero,» so you can quickly correct the query. The following checks are embedded in Standard SQL:"
},
{
"code": null,
"e": 9573,
"s": 9531,
"text": "Valid values for +, -, ×, SUM, AVG, STDEV"
},
{
"code": null,
"e": 9590,
"s": 9573,
"text": "Division by zero"
},
{
"code": null,
"e": 9921,
"s": 9590,
"text": "JOIN queries written in Standard SQL are faster than those written in Legacy SQL thanks to preliminary filtering of incoming data. First, the query selects the rows that match the JOIN conditions, then processes them.In the future, Google BigQuery will work on improving the speed and performance of queries only for Standard SQL."
},
{
"code": null,
"e": 10189,
"s": 9921,
"text": "Data Manipulation Language (DML) functions are available in Standard SQL. This means that you can update tables and add or remove rows from them through the same window in which you write queries. For example, using DML, you can combine data from two tables into one:"
},
{
"code": null,
"e": 10432,
"s": 10189,
"text": "#standardSQLMERGE dataset.Inventory AS TUSING dataset.NewArrivals AS SON T.ProductID = S.ProductIDWHEN MATCHED THEN UPDATE SET quantity = T.quantity + S.quantityWHEN NOT MATCHED THEN INSERT (ProductID, quantity) VALUES (ProductID, quantity)"
},
{
"code": null,
"e": 10654,
"s": 10432,
"text": "With Standard SQL, complex queries can be started not only with SELECT but also with WITH, making code easier to read, comment, and understand. This also means it’s easier to prevent your own and correct others’ mistakes."
},
{
"code": null,
"e": 11589,
"s": 10654,
"text": "#standardSQLWITH total_1 AS ( -- the first subquery in which the intermediate indicator will be calculated SELECT id, metric1, SUM(metric2) AS total_sum1 FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD` GROUP BY id, metric),total_2 AS ( -- the second subquery SELECT id, metric1, SUM(metric2) AS total_sum2 FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD` GROUP BY id, metric1),total_3 AS ( -- the third subquery SELECT id, metric, SUM(metric2) AS total_sum3 FROM `project_name.dataset_name.owoxbi_sessions_YYYYMMDD` GROUP BY id, metric)SELECT *,ROUND(100*( total_2.total_sum2 - total_3.total_sum3) / total_3.total_sum3, 3) AS difference -- get the difference index: subtract the value of the second subquery from the value of the third; divide by the value of the third FROM total_1ORDER BY 1, 2"
},
{
"code": null,
"e": 11785,
"s": 11589,
"text": "It’s convenient to work with the WITH operator if you have calculations that are done in several stages. First, you can collect intermediate metrics in subqueries, then do the final calculations."
},
{
"code": null,
"e": 12231,
"s": 11785,
"text": "The Google Cloud Platform (GCP), which includes BigQuery, is a full-cycle platform for working with big data, from organizing a data warehouse or data cloud to running scientific experiments and predictive and prescriptive analytics. With the introduction of Standard SQL, BigQuery is expanding its audience. Working with GCP is becoming more interesting for marketing analysts, product analysts, data scientists, and teams of other specialists."
},
{
"code": null,
"e": 12450,
"s": 12231,
"text": "At OWOX BI, we often work with tables compiled using the standard Google Analytics 360 export to Google BigQuery or the OWOX BI Pipeline. In the examples below, we’ll look at the specifics of SQL queries for such data."
},
{
"code": null,
"e": 12803,
"s": 12450,
"text": "In Google BigQuery, user behavior data for your site is stored in wildcard tables (tables with an asterisk); a separate table is formed for each day. These tables have the same name: only the suffix is different. The suffix is the date in the format YYYYMMDD. For example, the table owoxbi_sessions_20190301 contains data on sessions for March 1, 2019."
},
{
"code": null,
"e": 13102,
"s": 12803,
"text": "We can refer directly to a group of such tables in one request in order to obtain data, for example, from February 1 through February 28, 2019. To do this, we need to replace YYYYMMDD with an * in FROM, and in WHERE, we need to specify the table suffixes for the start and end of the time interval:"
},
{
"code": null,
"e": 13220,
"s": 13102,
"text": "#standardSQLSELECT sessionId, FROM `project_name.dataset_name.owoxbi_sessions_*`WHERE _TABLE_SUFFIX BETWEEN �' AND �'"
},
{
"code": null,
"e": 13431,
"s": 13220,
"text": "The specific dates for which we want to collect data are not always known to us. For example, every week we might need to analyze data for the last three months. To do this, we can use the FORMAT_DATE function:"
},
{
"code": null,
"e": 13682,
"s": 13431,
"text": "#standardSQLSELECT <enumerate field names>FROM `project_name.dataset_name.owoxbi_sessions_*`WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 3 MONTHS))ANDFORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))"
},
{
"code": null,
"e": 13989,
"s": 13682,
"text": "After BETWEEN, we record the suffix of the first table. The phrase CURRENT_DATE (), INTERVAL 3 MONTHS means «select data for the last 3 months from the current date.» The second table suffix is formatted after AND. It’s needed to mark the end of the interval as yesterday: CURRENT_DATE (), INTERVAL 1 DAY."
},
{
"code": null,
"e": 14348,
"s": 13989,
"text": "User parameters and metrics in Google Analytics Export tables are written to the nested hits table and to the customDimensions and customMetrics subtables. All custom dimensions are recorded in two columns: one for the number of parameters collected on the site, the second for their values. Here’s what all the parameters transmitted with one hit look like:"
},
{
"code": null,
"e": 14460,
"s": 14348,
"text": "In order to unpack them and write the necessary parameters in separate columns, we use the following SQL query:"
},
{
"code": null,
"e": 15159,
"s": 14460,
"text": "-- Custom Dimensions (in the line below index - the number of the user variable, which is set in the Google Analytics interface; dimension1 is the name of the custom parameter, which you can change as you like. For each subsequent parameter, you need to write the same line: (SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customDimensions)) AS dimension1, -- Custom Metrics: the index below is the number of the user metric specified in the Google Analytics interface; metric1 is the name of the metric, which you can change as you like. For each of the following metrics, you need to write the same line: (SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customMetrics)) AS metric1"
},
{
"code": null,
"e": 15201,
"s": 15159,
"text": "Here’s what it looks like in the request:"
},
{
"code": null,
"e": 15730,
"s": 15201,
"text": "#standardSQLSELECT <column name1>,<column_name2>, -- list column names(SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customDimensions)) AS page_type,(SELECT MAX(IF(index=2, value, NULL)) FROM UNNEST(hits.customDimensions)) AS visitor_type, -- produce the necessary custom dimensions(SELECT MAX(IF(index=1, value, NULL)) FROM UNNEST(hits.customMetrics)) AS metric1 -- produce the necessary custom metrics<column_name3> -- if you need more columns, continue to listFROM `project_name.dataset_name.owoxbi_sessions_20190201`"
},
{
"code": null,
"e": 15934,
"s": 15730,
"text": "In the screenshot below, we’ve selected parameters 1 and 2 from Google Analytics 360 demo data in Google BigQuery and called them page_type and client_id. Each parameter is recorded in a separate column:"
},
{
"code": null,
"e": 16106,
"s": 15934,
"text": "Such calculations are useful if you plan to visualize data in Google Data Studio and filter by city and device category. This is easy to do with the COUNT window function:"
},
{
"code": null,
"e": 16614,
"s": 16106,
"text": "#standardSQLSELECT<column_name 1>, -- choose any columns COUNT (DISTINCT sessionId) AS total_sessions, -- summarize the session IDs to find the total number of sessionsCOUNT(DISTINCT sessionId) OVER(PARTITION BY date, geoNetwork.city, session.device.deviceCategory, trafficSource.source, trafficSource.medium, trafficSource.campaign) AS part_sessions -- summarize the number of sessions by campaign, channel, traffic source, city, and device categoryFROM `project_name.dataset_name.owoxbi_sessions_20190201`"
},
{
"code": null,
"e": 16825,
"s": 16614,
"text": "Suppose you collect data on completed orders in several BigQuery tables: one collects all orders from Store A, the other collects orders from Store B. You want to combine them into one table with these columns:"
},
{
"code": null,
"e": 16877,
"s": 16825,
"text": "client_id — a number that identifies a unique buyer"
},
{
"code": null,
"e": 16940,
"s": 16877,
"text": "transaction_created — order creation time in TIMESTAMP format"
},
{
"code": null,
"e": 16970,
"s": 16940,
"text": "transaction_id — order number"
},
{
"code": null,
"e": 17016,
"s": 16970,
"text": "is_approved — whether the order was confirmed"
},
{
"code": null,
"e": 17051,
"s": 17016,
"text": "transaction_revenue — order amount"
},
{
"code": null,
"e": 17267,
"s": 17051,
"text": "In our example orders from January 1, 2018, to yesterday must be in the table. To do this, select the appropriate columns from each group of tables, assign them the same name, and combine the results with UNION ALL:"
},
{
"code": null,
"e": 17860,
"s": 17267,
"text": "#standardSQLSELECT cid AS client_id, order_time AS transaction_created,order_status AS is_approved,order_number AS transaction_idFROM `project_name.dataset_name.table1_*`WHERE ( _TABLE_SUFFIX BETWEEN �' AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) )UNION ALL SELECTuserId AS client_id,created_timestamp AS transaction_created,operator_mark AS is_approved,transactionId AS transaction_idFROM `project_name.dataset_name.table1_*`WHERE ( _TABLE_SUFFIX BETWEEN �' AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) )ORDER BY transaction_created DESC"
},
{
"code": null,
"e": 18239,
"s": 17860,
"text": "When data enters Google Analytics, the system automatically determines the group to which a particular transition belongs: Direct, Organic Search, Paid Search, and so on. To identify a group of channels, Google Analytics looks at the UTM tags of transitions, namely utm_source and utm_medium. You can read more about channel groups and definition rules in Google Analytics Help."
},
{
"code": null,
"e": 18552,
"s": 18239,
"text": "If OWOX BI clients want to assign their own names to groups of channels, we create a dictionary, which transition belongs to a specific channel. To do this, we use the conditional CASE operator and the REGEXP_CONTAINS function. This function selects the values in which the specified regular expression occurs."
},
{
"code": null,
"e": 18694,
"s": 18552,
"text": "We recommend taking names from your list of sources in Google Analytics. Here’s an example of how to add such conditions to the request body:"
},
{
"code": null,
"e": 19580,
"s": 18694,
"text": "#standardSQLSELECT CASE WHEN (REGEXP_CONTAINS (source, 'yandex') AND medium = 'referral' THEN 'Organic Search' WHEN (REGEXP_CONTAINS (source, 'yandex.market')) AND medium = 'referral' THEN 'Referral'WHEN (REGEXP_CONTAINS (source, '^(go.mail.ru|google.com)$') AND medium = 'referral') THEN 'Organic Search'WHEN medium = 'organic' THEN 'Organic Search'WHEN (medium = 'cpc') THEN 'Paid Search'WHEN REGEXP_CONTAINS (medium, '^(sending|email|mail)$') THEN 'Email' WHEN REGEXP_CONTAINS (source, '(mail|email|Mail)') THEN 'Email' WHEN REGEXP_CONTAINS (medium, '^(cpa)$') THEN 'Affiliate' WHEN medium = 'social' THEN 'Social' WHEN source = '(direct)' THEN 'Direct' WHEN REGEXP_CONTAINS (medium, 'banner|cpm') THEN 'Display' ELSE 'Other' END channel_group -- the name of the column in which the channel groups are writtenFROM `project_name.dataset_name.owoxbi_sessions_20190201`"
},
{
"code": null,
"e": 19711,
"s": 19580,
"text": "If you haven’t switched to Standard SQL yet, you can do it at any time. The main thing is to avoid mixing dialects in one request."
},
{
"code": null,
"e": 19903,
"s": 19711,
"text": "Legacy SQL is used by default in the old BigQuery interface. To switch between dialects, click Show Options under the query input field and uncheck the Use Legacy SQL box next to SQL Dialect."
},
{
"code": null,
"e": 20008,
"s": 19903,
"text": "The new interface uses Standard SQL by default. Here, you need to go to the More tab to switch dialects:"
},
{
"code": null,
"e": 20120,
"s": 20008,
"text": "If you haven’t ticked the request settings, you can start with the desired prefix (#standardSQL or #legacySQL):"
},
{
"code": null,
"e": 20265,
"s": 20120,
"text": "#standardSQLSELECT weight_pounds, state, year, gestation_weeksFROM `bigquery-public-data.samples.natality`ORDER BY weight_pounds DESCLIMIT 10;"
},
{
"code": null,
"e": 20398,
"s": 20265,
"text": "In this case, Google BigQuery will ignore the settings in the interface and run the query using the dialect specified in the prefix."
},
{
"code": null,
"e": 20557,
"s": 20398,
"text": "If you have views or saved queries that are launched on a schedule using Apps Script, don’t forget to change the value of useLegacySql to false in the script:"
},
{
"code": null,
"e": 20723,
"s": 20557,
"text": "var job = {configuration: { query: { query: 'INSERT INTO MyDataSet.MyFooBarTable (Id, Foo, Date) VALUES (1, \\'bar\\', current_Date);', useLegacySql: false }"
},
{
"code": null,
"e": 20951,
"s": 20723,
"text": "If you work with Google BigQuery not with tables but with views, those views can’t be accessed in the Standard SQL dialect. That is, if your presentation is written in Legacy SQL, you can’t write requests to it in Standard SQL."
},
{
"code": null,
"e": 21113,
"s": 20951,
"text": "To transfer a view to standard SQL, you need to manually rewrite the query by which it was created. The easiest way to do this is through the BigQuery interface."
},
{
"code": null,
"e": 21131,
"s": 21113,
"text": "1. Open the view:"
},
{
"code": null,
"e": 21222,
"s": 21131,
"text": "2. Click Details. The query text should open, and the Edit Query button will appear below:"
},
{
"code": null,
"e": 21398,
"s": 21222,
"text": "Now you can edit the request according to the rules of Standard SQL.If you plan to continue using the request as a presentation, click Save View after you’ve finished editing."
},
{
"code": null,
"e": 21522,
"s": 21398,
"text": "Thanks to the implementation of Standard SQL, you can directly access data stored in other services directly from BigQuery:"
},
{
"code": null,
"e": 21554,
"s": 21522,
"text": "Google Cloud Storage log files"
},
{
"code": null,
"e": 21595,
"s": 21554,
"text": "Transactional records in Google Bigtable"
},
{
"code": null,
"e": 21619,
"s": 21595,
"text": "Data from other sources"
},
{
"code": null,
"e": 21785,
"s": 21619,
"text": "This allows you to use Google Cloud Platform products for any analytical tasks, including predictive and prescriptive analytics based on machine learning algorithms."
},
{
"code": null,
"e": 21862,
"s": 21785,
"text": "The query structure in the Standard dialect is almost the same as in Legacy:"
},
{
"code": null,
"e": 22066,
"s": 21862,
"text": "The names of the tables and view are separated with a period (full stop), and the whole query is enclosed in grave accents: `project_name.data_name_name.table_name``bigquery-public-data.samples.natality`"
},
{
"code": null,
"e": 22211,
"s": 22066,
"text": "The full syntax of the query, with explanations of what can be included in each operator, is compiled as a schema in the BigQuery documentation."
},
{
"code": null,
"e": 22244,
"s": 22211,
"text": "Features of Standard SQL syntax:"
},
{
"code": null,
"e": 22302,
"s": 22244,
"text": "Commas are needed to list fields in the SELECT statement."
},
{
"code": null,
"e": 22387,
"s": 22302,
"text": "If you use the UNNEST operator after FROM , a comma or JOIN is placed before UNNEST."
},
{
"code": null,
"e": 22422,
"s": 22387,
"text": "You can’t put a comma before FROM."
},
{
"code": null,
"e": 22494,
"s": 22422,
"text": "A comma between two queries equals a CROSS JOIN, so be careful with it."
},
{
"code": null,
"e": 22587,
"s": 22494,
"text": "JOIN can be done not only by column or equality but by arbitrary expressions and inequality."
},
{
"code": null,
"e": 22819,
"s": 22587,
"text": "It’s possible to write complex subqueries in any part of the SQL expression (in SELECT, FROM, WHERE, etc.). In practice, it’s not yet possible to use expressions like WHERE column_name IN (SELECT ...) as you can in other databases."
},
{
"code": null,
"e": 23042,
"s": 22819,
"text": "In Standard SQL, operators define the type of data. For example, an array is always written in brackets []. Operators are used for comparison, matching the logical expression (NOT, OR, AND), and in arithmetic calculations."
},
{
"code": null,
"e": 23238,
"s": 23042,
"text": "Standard SQL supports more features than Legacy: traditional aggregation (sum, number, minimum, maximum); mathematical, string, and statistical functions; and rare formats such as HyperLogLog ++."
},
{
"code": null,
"e": 23488,
"s": 23238,
"text": "In the Standard dialect, there are more functions for working with dates and TIMESTAMP. A complete list of features is provided in Google’s documentation. The most commonly used functions are for working with dates, strings, aggregation, and window."
},
{
"code": null,
"e": 23513,
"s": 23488,
"text": "1. Aggregation functions"
},
{
"code": null,
"e": 23800,
"s": 23513,
"text": "COUNT (DISTINCT column_name) counts the number of unique values in a column. For example, say we need to count the number of sessions from mobile devices on March 1, 2019. Since a session number can be repeated on different lines, we want to count only the unique session number values:"
},
{
"code": null,
"e": 23954,
"s": 23800,
"text": "#standardSQLSELECT COUNT (DISTINCT sessionId) AS sessionsFROM `project_name.dataset_name.owoxbi_sessions_20190301`WHERE device.deviceCategory = 'mobile'"
},
{
"code": null,
"e": 24010,
"s": 23954,
"text": "SUM (column_name) — the sum of the values in the column"
},
{
"code": null,
"e": 24235,
"s": 24010,
"text": "#standardSQLSELECT SUM (hits.transaction.transactionRevenue) AS revenueFROM `project_name.dataset_name.owoxbi_sessions_20190301`,UNNEST (hits) AS hits -- unpacking the nested field hitsWHERE device.deviceCategory = 'mobile'"
},
{
"code": null,
"e": 24395,
"s": 24235,
"text": "MIN (column_name) | MAX (column_name) — the minimum and maximum value in the column. These functions are convenient for checking the spread of data in a table."
},
{
"code": null,
"e": 24428,
"s": 24395,
"text": "2. Window (analytical) functions"
},
{
"code": null,
"e": 24878,
"s": 24428,
"text": "Analytical functions consider values not for the entire table but for a certain window — a set of rows that you’re interested in. That is, you can define segments within a table. For example, you can calculate SUM (revenue) not for all lines but for cities, device categories, and so on. You can turn the analytic functions SUM, COUNT, and AVG as well as other aggregation functions by adding the OVER condition (PARTITION BY column_name) to them."
},
{
"code": null,
"e": 25048,
"s": 24878,
"text": "For example, you need to count the number of sessions by traffic source, channel, campaign, city, and device category. In this case, we can use the following expression:"
},
{
"code": null,
"e": 25460,
"s": 25048,
"text": "SELECT date, geoNetwork.city, t.device.deviceCategory, trafficSource.source, trafficSource.medium, trafficSource.campaign,COUNT(DISTINCT sessionId) OVER(PARTITION BY date, geoNetwork.city, session.device.deviceCategory, trafficSource.source, trafficSource.medium, trafficSource.campaign) AS segmented_sessionsFROM `project_name.dataset_name.owoxbi_sessions_20190301` t"
},
{
"code": null,
"e": 25675,
"s": 25460,
"text": "OVER determines the window for which calculations will be made. PARTITION BY indicates which rows should be grouped for calculation. In some functions, it’s necessary to specify the order of grouping with ORDER BY."
},
{
"code": null,
"e": 25748,
"s": 25675,
"text": "For a complete list of window functions, see the BigQuery documentation."
},
{
"code": null,
"e": 25768,
"s": 25748,
"text": "3. String functions"
},
{
"code": null,
"e": 26069,
"s": 25768,
"text": "These are useful when you need to change text, format the text in a line, or glue the values of columns. For example, string functions are great if you want to generate a unique session identifier from the standard Google Analytics 360 export data. Let’s consider the most popular string functions."
},
{
"code": null,
"e": 26515,
"s": 26069,
"text": "SUBSTR cuts part of the string. In the request, this function is written as SUBSTR (string_name, 0.4). The first number indicates how many characters to skip from the beginning of the line, and the second number indicates how many digits to cut. For example, say you have a date column that contains dates in the STRING format. In this case, the dates look like this: 20190103. If you want to extract a year from this line, SUBSTR will help you:"
},
{
"code": null,
"e": 26615,
"s": 26515,
"text": "#standardSQLSELECTSUBSTR(date,0,4) AS yearFROM `project_name.dataset_name.owoxbi_sessions_20190301`"
},
{
"code": null,
"e": 26961,
"s": 26615,
"text": "CONCAT (column_name, etc.) glues values. Let’s use the date column from the previous example. Suppose you want all dates to be recorded like this: 2019–03–01. To convert dates from their current format to this format, two string functions can be used: first, cut the necessary pieces of the string with SUBSTR, then glue them through the hyphen:"
},
{
"code": null,
"e": 27111,
"s": 26961,
"text": "#standardSQLSELECTCONCAT(SUBSTR(date,0,4),\"-\",SUBSTR(date,5,2),\"-\",SUBSTR(date,7,2)) AS dateFROM `project_name.dataset_name.owoxbi_sessions_20190301`"
},
{
"code": null,
"e": 27197,
"s": 27111,
"text": "REGEXP_CONTAINS returns the values of columns in which the regular expression occurs:"
},
{
"code": null,
"e": 27504,
"s": 27197,
"text": "#standardSQLSELECT CASEWHEN REGEXP_CONTAINS (medium, '^(sending|email|mail)$') THEN 'Email' WHEN REGEXP_CONTAINS (source, '(mail|email|Mail)') THEN 'Email' WHEN REGEXP_CONTAINS (medium, '^(cpa)$') THEN 'Affiliate'ELSE 'Other'END Channel_groupsFROM `project_name.dataset_name.owoxbi_sessions_20190301`"
},
{
"code": null,
"e": 27618,
"s": 27504,
"text": "This function can be used in both SELECT and WHERE. For example, in WHERE, you can select specific pages with it:"
},
{
"code": null,
"e": 27689,
"s": 27618,
"text": "WHERE REGEXP_CONTAINS(hits.page.pagePath, 'land[123]/|/product-order')"
},
{
"code": null,
"e": 27707,
"s": 27689,
"text": "4. Date functions"
},
{
"code": null,
"e": 27907,
"s": 27707,
"text": "Often, dates in tables are recorded in STRING format. If you plan to visualize results in Google Data Studio, the dates in the table need to be converted to DATE format using the PARSE_DATE function."
},
{
"code": null,
"e": 28115,
"s": 27907,
"text": "PARSE_DATE converts a STRING of the 1900–01–01 format to the DATE format.If the dates in your tables look different (for example, 19000101 or 01_01_1900), you must first convert them to the specified format."
},
{
"code": null,
"e": 28233,
"s": 28115,
"text": "#standardSQLSELECT PARSE_DATE('%Y-%m-%d', date) AS date_newFROM `project_name.dataset_name.owoxbi_sessions_20190301`"
},
{
"code": null,
"e": 28482,
"s": 28233,
"text": "DATE_DIFF calculates how much time has passed between two dates in days, weeks, months, or years. It’s useful if you need to determine the interval between when a user saw advertising and placed an order. Here’s how the function looks in a request:"
},
{
"code": null,
"e": 28757,
"s": 28482,
"text": "#standardSQL SELECT DATE_DIFF( PARSE_DATE('%Y%m%d', date1), PARSE_DATE('%Y%m%d', date2), DAY ) days -- convert the date1 and date2 lines to the DATE format; choose units to show the difference (DAY, WEEK, MONTH, etc.)FROM `project_name.dataset_name.owoxbi_sessions_20190301`"
},
{
"code": null,
"e": 28862,
"s": 28757,
"text": "If you want to learn more about the listed functions, read BigQuery Google Features — A Detailed Review."
},
{
"code": null,
"e": 29182,
"s": 28862,
"text": "The Standard SQL dialect allows businesses to extract maximum information from data with deep segmentation, technical audits, marketing KPI analysis, and identification of unfair contractors in CPA networks. Here are examples of business problems in which SQL queries on data collected in Google BigQuery will help you."
},
{
"code": null,
"e": 29410,
"s": 29182,
"text": "1. ROPO analysis: evaluate the contribution of online campaigns to offline sales. To perform ROPO analysis, you need to combine data on online user behavior with data from your CRM, call tracking system, and mobile application."
},
{
"code": null,
"e": 29743,
"s": 29410,
"text": "If there’s a key in one and the second base — a common parameter that is unique for each user (for example, User ID) — you can track:which users visited the site before buying goods in the storehow users behaved on the sitehow long users took to make a purchase decisionwhat campaigns had the greatest increase on offline purchases."
},
{
"code": null,
"e": 29945,
"s": 29743,
"text": "2. Segment customers by any combination of parameters, from behavior on the site (pages visited, products viewed, number of visits to the site before buying) to loyalty card number and purchased items."
},
{
"code": null,
"e": 30025,
"s": 29945,
"text": "3. Find out which CPA partners are working in bad faith and replacing UTM tags."
},
{
"code": null,
"e": 30084,
"s": 30025,
"text": "4. Analyze the progress of users through the sales funnel."
},
{
"code": null,
"e": 30452,
"s": 30084,
"text": "We’ve prepared a selection of queries in Standard SQL dialect. If you already collect data from your site, from advertising sources, and from your CRM system in Google BigQuery, you can use these templates to solve your business problems. Simply replace the project name, dataset, and table in BigQuery with your own. In the collection, you’ll receive 11 SQL queries."
},
{
"code": null,
"e": 30539,
"s": 30452,
"text": "For data collected using standard export from Google Analytics 360 to Google BigQuery:"
},
{
"code": null,
"e": 30585,
"s": 30539,
"text": "User actions in the context of any parameters"
},
{
"code": null,
"e": 30616,
"s": 30585,
"text": "Statistics on key user actions"
},
{
"code": null,
"e": 30656,
"s": 30616,
"text": "Users who viewed specific product pages"
},
{
"code": null,
"e": 30705,
"s": 30656,
"text": "Actions of users who bought a particular product"
},
{
"code": null,
"e": 30748,
"s": 30705,
"text": "Set up the funnel with any necessary steps"
},
{
"code": null,
"e": 30790,
"s": 30748,
"text": "Effectiveness of the internal search site"
},
{
"code": null,
"e": 30843,
"s": 30790,
"text": "For data collected in Google BigQuery using OWOX BI:"
},
{
"code": null,
"e": 30888,
"s": 30843,
"text": "Attributed consumption by source and channel"
},
{
"code": null,
"e": 30933,
"s": 30888,
"text": "Average cost of attracting a visitor by city"
},
{
"code": null,
"e": 30977,
"s": 30933,
"text": "ROAS for gross profit by source and channel"
},
{
"code": null,
"e": 31043,
"s": 30977,
"text": "Number of orders in the CRM by payment method and delivery method"
}
] |
Convert given array to Arithmetic Progression by adding an element - GeeksforGeeks | 20 May, 2021
Given an array arr[], the task is to find an element that can be added to the array in order to convert it to Arithmetic Progression. If it’s impossible to convert the given array into an AP, then print -1.
Examples:
Input: arr[] = {3, 7} Output: 11 3, 7 and 11 is a finite AP sequence.
Input: a[] = {4, 6, 8, 15} Output: -1
Approach:
Sort the array and start traversing the array element by element and note the difference between the two consecutive elements.
If the difference for all the elements is the same then print last element + common difference.
If the difference is different for at most one pair (arr[i – 1], arr[i]) and diff = 2 * common difference for all other elements, then print arr[i] – common difference.
Else print -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach #include<bits/stdc++.h>using namespace std; // Function to return the number to be// addedint getNumToAdd(int arr[], int n){ sort(arr,arr+n); int d = arr[1] - arr[0]; int numToAdd = -1; bool numAdded = false; for (int i = 2; i < n; i++) { int diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd;} // Driver codeint main(){ int arr[] = { 1, 3, 5, 7, 11, 13, 15 }; int n = sizeof(arr)/sizeof(arr[0]); cout << getNumToAdd(arr, n);} // This code is contributed// by ihritik
// Java implementation of the approachimport java.util.*;public class GFG { // Function to return the number to be // added static int getNumToAdd(int arr[], int n) { Arrays.sort(arr); int d = arr[1] - arr[0]; int numToAdd = -1; boolean numAdded = false; for (int i = 2; i < n; i++) { int diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd; } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 5, 7, 11, 13, 15 }; int n = arr.length; System.out.println(getNumToAdd(arr, n)); }}
# Python 3 implementation of the approach # Function to return the number# to be addeddef getNumToAdd(arr, n): arr.sort(reverse = False) d = arr[1] - arr[0] numToAdd = -1 numAdded = False for i in range(2, n, 1): diff = arr[i] - arr[i - 1] # If difference of the current consecutive # elements is different from the common # difference if (diff != d): # If number has already been chosen # then it's not possible to add # another number if (numAdded): return -1 # If the current different is twice # the common difference then a # number can be added midway from # current and previous element if (diff == 2 * d): numToAdd = arr[i] - d # Number has been chosen numAdded = True # It's not possible to maintain # the common difference else: return -1 # Return last element + common difference # if no element is chosen and the array # is already in AP if (numToAdd == -1): return (arr[n - 1] + d) # Else return the chosen number return numToAdd # Driver codeif __name__ == '__main__': arr = [1, 3, 5, 7, 11, 13, 15] n = len(arr) print(getNumToAdd(arr, n)) # This code is contributed# mohit kumar 29
// C# implementation of the approach using System;public class GFG { // Function to return the number to be // added static int getNumToAdd(int []arr, int n) { Array.Sort(arr); int d = arr[1] - arr[0]; int numToAdd = -1; bool numAdded = false; for (int i = 2; i < n; i++) { int diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd; } // Driver code public static void Main() { int []arr = { 1, 3, 5, 7, 11, 13, 15 }; int n = arr.Length; Console.WriteLine(getNumToAdd(arr, n)); }} // This code is contributed// by ihritik
<?php// PHP implementation of the approach // Function to return the number// to be addedfunction getNumToAdd($arr, $n){ sort($arr); $d = $arr[1] - $arr[0]; $numToAdd = -1; $numAdded = false; for ($i = 2; $i < $n; $i++) { $diff = $arr[$i] - $arr[$i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if ($diff != $d) { // If number has already been // chosen then it's not possible // to add another number if ($numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if ($diff == 2 * $d) { $numToAdd = $arr[$i] - $d; // Number has been chosen $numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if ($numToAdd == -1) return ($arr[$n - 1] + $d); // Else return the chosen number return $numToAdd;} // Driver code$arr = array( 1, 3, 5, 7, 11, 13, 15 );$n = sizeof($arr);echo getNumToAdd($arr, $n); // This code is contributed by Sachin..?>
<script> // Javascript implementation of the approach // Function to return the number to be// addedfunction getNumToAdd(arr, n){ arr.sort(function(a, b){return a - b}); var d = arr[1] - arr[0]; var numToAdd = -1; var numAdded = false; for(var i = 2; i < n; i++) { var diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd;} // Driver codevar arr = [ 1, 3, 5, 7, 11, 13, 15 ];var n = arr.length;document.write(getNumToAdd(arr, n)); // This code is contributed by Ankita saini </script>
9
Time Complexity : O(n Log n)
ihritik
mohit kumar 29
Sach_Code
ankita_saini
arithmetic progression
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays | [
{
"code": null,
"e": 25256,
"s": 25228,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 25463,
"s": 25256,
"text": "Given an array arr[], the task is to find an element that can be added to the array in order to convert it to Arithmetic Progression. If it’s impossible to convert the given array into an AP, then print -1."
},
{
"code": null,
"e": 25475,
"s": 25463,
"text": "Examples: "
},
{
"code": null,
"e": 25545,
"s": 25475,
"text": "Input: arr[] = {3, 7} Output: 11 3, 7 and 11 is a finite AP sequence."
},
{
"code": null,
"e": 25584,
"s": 25545,
"text": "Input: a[] = {4, 6, 8, 15} Output: -1 "
},
{
"code": null,
"e": 25595,
"s": 25584,
"text": "Approach: "
},
{
"code": null,
"e": 25722,
"s": 25595,
"text": "Sort the array and start traversing the array element by element and note the difference between the two consecutive elements."
},
{
"code": null,
"e": 25818,
"s": 25722,
"text": "If the difference for all the elements is the same then print last element + common difference."
},
{
"code": null,
"e": 25987,
"s": 25818,
"text": "If the difference is different for at most one pair (arr[i – 1], arr[i]) and diff = 2 * common difference for all other elements, then print arr[i] – common difference."
},
{
"code": null,
"e": 26002,
"s": 25987,
"text": "Else print -1."
},
{
"code": null,
"e": 26054,
"s": 26002,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26058,
"s": 26054,
"text": "C++"
},
{
"code": null,
"e": 26063,
"s": 26058,
"text": "Java"
},
{
"code": null,
"e": 26071,
"s": 26063,
"text": "Python3"
},
{
"code": null,
"e": 26074,
"s": 26071,
"text": "C#"
},
{
"code": null,
"e": 26078,
"s": 26074,
"text": "PHP"
},
{
"code": null,
"e": 26089,
"s": 26078,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach #include<bits/stdc++.h>using namespace std; // Function to return the number to be// addedint getNumToAdd(int arr[], int n){ sort(arr,arr+n); int d = arr[1] - arr[0]; int numToAdd = -1; bool numAdded = false; for (int i = 2; i < n; i++) { int diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd;} // Driver codeint main(){ int arr[] = { 1, 3, 5, 7, 11, 13, 15 }; int n = sizeof(arr)/sizeof(arr[0]); cout << getNumToAdd(arr, n);} // This code is contributed// by ihritik",
"e": 27634,
"s": 26089,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;public class GFG { // Function to return the number to be // added static int getNumToAdd(int arr[], int n) { Arrays.sort(arr); int d = arr[1] - arr[0]; int numToAdd = -1; boolean numAdded = false; for (int i = 2; i < n; i++) { int diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd; } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 5, 7, 11, 13, 15 }; int n = arr.length; System.out.println(getNumToAdd(arr, n)); }}",
"e": 29367,
"s": 27634,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to return the number# to be addeddef getNumToAdd(arr, n): arr.sort(reverse = False) d = arr[1] - arr[0] numToAdd = -1 numAdded = False for i in range(2, n, 1): diff = arr[i] - arr[i - 1] # If difference of the current consecutive # elements is different from the common # difference if (diff != d): # If number has already been chosen # then it's not possible to add # another number if (numAdded): return -1 # If the current different is twice # the common difference then a # number can be added midway from # current and previous element if (diff == 2 * d): numToAdd = arr[i] - d # Number has been chosen numAdded = True # It's not possible to maintain # the common difference else: return -1 # Return last element + common difference # if no element is chosen and the array # is already in AP if (numToAdd == -1): return (arr[n - 1] + d) # Else return the chosen number return numToAdd # Driver codeif __name__ == '__main__': arr = [1, 3, 5, 7, 11, 13, 15] n = len(arr) print(getNumToAdd(arr, n)) # This code is contributed# mohit kumar 29",
"e": 30787,
"s": 29367,
"text": null
},
{
"code": "// C# implementation of the approach using System;public class GFG { // Function to return the number to be // added static int getNumToAdd(int []arr, int n) { Array.Sort(arr); int d = arr[1] - arr[0]; int numToAdd = -1; bool numAdded = false; for (int i = 2; i < n; i++) { int diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd; } // Driver code public static void Main() { int []arr = { 1, 3, 5, 7, 11, 13, 15 }; int n = arr.Length; Console.WriteLine(getNumToAdd(arr, n)); }} // This code is contributed// by ihritik",
"e": 32536,
"s": 30787,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the number// to be addedfunction getNumToAdd($arr, $n){ sort($arr); $d = $arr[1] - $arr[0]; $numToAdd = -1; $numAdded = false; for ($i = 2; $i < $n; $i++) { $diff = $arr[$i] - $arr[$i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if ($diff != $d) { // If number has already been // chosen then it's not possible // to add another number if ($numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if ($diff == 2 * $d) { $numToAdd = $arr[$i] - $d; // Number has been chosen $numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if ($numToAdd == -1) return ($arr[$n - 1] + $d); // Else return the chosen number return $numToAdd;} // Driver code$arr = array( 1, 3, 5, 7, 11, 13, 15 );$n = sizeof($arr);echo getNumToAdd($arr, $n); // This code is contributed by Sachin..?>",
"e": 34021,
"s": 32536,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the number to be// addedfunction getNumToAdd(arr, n){ arr.sort(function(a, b){return a - b}); var d = arr[1] - arr[0]; var numToAdd = -1; var numAdded = false; for(var i = 2; i < n; i++) { var diff = arr[i] - arr[i - 1]; // If difference of the current // consecutive elements is // different from the common // difference if (diff != d) { // If number has already been // chosen then it's not possible // to add another number if (numAdded) return -1; // If the current different is // twice the common difference // then a number can be added midway // from current and previous element if (diff == 2 * d) { numToAdd = arr[i] - d; // Number has been chosen numAdded = true; } // It's not possible to maintain // the common difference else return -1; } } // Return last element + common difference // if no element is chosen and the array // is already in AP if (numToAdd == -1) return (arr[n - 1] + d); // Else return the chosen number return numToAdd;} // Driver codevar arr = [ 1, 3, 5, 7, 11, 13, 15 ];var n = arr.length;document.write(getNumToAdd(arr, n)); // This code is contributed by Ankita saini </script>",
"e": 35565,
"s": 34021,
"text": null
},
{
"code": null,
"e": 35567,
"s": 35565,
"text": "9"
},
{
"code": null,
"e": 35599,
"s": 35569,
"text": "Time Complexity : O(n Log n) "
},
{
"code": null,
"e": 35607,
"s": 35599,
"text": "ihritik"
},
{
"code": null,
"e": 35622,
"s": 35607,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35632,
"s": 35622,
"text": "Sach_Code"
},
{
"code": null,
"e": 35645,
"s": 35632,
"text": "ankita_saini"
},
{
"code": null,
"e": 35668,
"s": 35645,
"text": "arithmetic progression"
},
{
"code": null,
"e": 35675,
"s": 35668,
"text": "Arrays"
},
{
"code": null,
"e": 35683,
"s": 35675,
"text": "Sorting"
},
{
"code": null,
"e": 35690,
"s": 35683,
"text": "Arrays"
},
{
"code": null,
"e": 35698,
"s": 35690,
"text": "Sorting"
},
{
"code": null,
"e": 35796,
"s": 35698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35844,
"s": 35796,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 35888,
"s": 35844,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 35920,
"s": 35888,
"text": "Multidimensional Arrays in Java"
}
] |
How can a query multiply 2 cells for each row in MySQL? | You can use multiplication operator (*) between two cells. The syntax is as follows
SELECT yourColumnName1,yourColumnName2,
yourColumnName1*yourColumnName2 as ‘anyVariableName’
from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table MultiplicationDemo
-> (
-> FirstPrice int,
-> SecondPrice int
-> );
Query OK, 0 rows affected (0.63 sec)
Now you can display all records from the table using insert command. The query is as follows
mysql> insert into MultiplicationDemo values(10,2);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MultiplicationDemo values(4,2);
Query OK, 1 row affected (0.30 sec)
mysql> insert into MultiplicationDemo values(5,6);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MultiplicationDemo values(6,3);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows
mysql> select *from MultiplicationDemo;
The following is the output
+------------+-------------+
| FirstPrice | SecondPrice |
+------------+-------------+
| 10 | 2 |
| 4 | 2 |
| 5 | 6 |
| 6 | 3 |
+------------+-------------+
4 rows in set (0.00 sec)
Here is the query to multiply 2 cells
mysql> select FirstPrice,SecondPrice,
-> FirstPrice*SecondPrice as 'MultiplicationResult'
-> from MultiplicationDemo;
The following is the output
+------------+-------------+----------------------+
| FirstPrice | SecondPrice | MultiplicationResult |
+------------+-------------+----------------------+
| 10 | 2 | 20 |
| 4 | 2 | 8 |
| 5 | 6 | 30 |
| 6 | 3 | 18 |
+------------+-------------+----------------------+
4 rows in set (0.03 sec) | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "You can use multiplication operator (*) between two cells. The syntax is as follows"
},
{
"code": null,
"e": 1259,
"s": 1146,
"text": "SELECT yourColumnName1,yourColumnName2,\nyourColumnName1*yourColumnName2 as ‘anyVariableName’\nfrom yourTableName;"
},
{
"code": null,
"e": 1356,
"s": 1259,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1493,
"s": 1356,
"text": "mysql> create table MultiplicationDemo\n -> (\n -> FirstPrice int,\n -> SecondPrice int\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1586,
"s": 1493,
"text": "Now you can display all records from the table using insert command. The query is as follows"
},
{
"code": null,
"e": 1938,
"s": 1586,
"text": "mysql> insert into MultiplicationDemo values(10,2);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into MultiplicationDemo values(4,2);\nQuery OK, 1 row affected (0.30 sec)\n\nmysql> insert into MultiplicationDemo values(5,6);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into MultiplicationDemo values(6,3);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2021,
"s": 1938,
"text": "Display all records from the table using select statement. The query is as follows"
},
{
"code": null,
"e": 2061,
"s": 2021,
"text": "mysql> select *from MultiplicationDemo;"
},
{
"code": null,
"e": 2089,
"s": 2061,
"text": "The following is the output"
},
{
"code": null,
"e": 2346,
"s": 2089,
"text": "+------------+-------------+\n| FirstPrice | SecondPrice |\n+------------+-------------+\n| 10 | 2 |\n| 4 | 2 |\n| 5 | 6 |\n| 6 | 3 |\n+------------+-------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2384,
"s": 2346,
"text": "Here is the query to multiply 2 cells"
},
{
"code": null,
"e": 2508,
"s": 2384,
"text": "mysql> select FirstPrice,SecondPrice,\n -> FirstPrice*SecondPrice as 'MultiplicationResult'\n -> from MultiplicationDemo;"
},
{
"code": null,
"e": 2536,
"s": 2508,
"text": "The following is the output"
},
{
"code": null,
"e": 2977,
"s": 2536,
"text": "+------------+-------------+----------------------+\n| FirstPrice | SecondPrice | MultiplicationResult |\n+------------+-------------+----------------------+\n| 10 | 2 | 20 |\n| 4 | 2 | 8 |\n| 5 | 6 | 30 |\n| 6 | 3 | 18 |\n+------------+-------------+----------------------+\n4 rows in set (0.03 sec)"
}
] |
ANN Binary Classification | Towards Data Science | This article aims to explain how to create an artificial neural network (ANN) to predict if a banker customer is leaving or not using raw banking customers' data. The article is split into 6 parts as below.
Problem statementData processingModel buildingModel compilingModel fittingModel prediction
Problem statement
Data processing
Model building
Model compiling
Model fitting
Model prediction
Now let’s begin the journey 🏃♂️🏃♀️!
1. Problem statement
We are tasked by a bank to predict if a customer is likely to leave the bank. 6-month customer banking data is given. The bank plans to use your findings to re-engage with customers who are leaving.
2. Data processing
First, import the data with Pandas using read_csv() as below.
dataset = pd.read_csv(‘Churn_Modelling.csv’)
Figure 1 shows a snippet of the data. The first 13 columns are independent variables about customer ID, name, Credit Score, Geography, Gender, Age, etc. The last column is a dependent variable if the customer left or stayed.
Now, let’s start data processing.
1) Feature selection
The first question: do we need all independent variables to fit the model 🤔? The answer is No. For instance, Row Number, Customer ID, or Surname has no impact on the customer leaving or staying. But customer’s age may have, as young customers possibly tend to leave the bank. So with this logic, we tell which independent variables would impact the outcome. But remember only the neural network can tell which features have a high impact on the outcome.
So independent variable X is:
X = dataset.iloc[:, 3: 13].values
Dependent variable y is:
y = dataset.iloc[:, 13].values
2) Categorical encoding
Neural networks only take numerical values for learning.
Therefore, categorical variables, such as Geography and Gender need to be encoded into numerical ones. Here we use fit_transform() method of LabelEncoder from sklearn. We create two label encoders for each column.
from sklearn.preprocessing import LabelEncoderlabelencoder_X_1 = LabelEncoder()X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
Notice above, we input index 1, as the index of Geography column in X is 1. After encoding, country German becomes 1, France is 0, Spain is 2. With the same method, encode Gender column as below.
labelencoder_X_2 = LabelEncoder()X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
Now, the male is 1 and female become 0 (hopefully Dear Lady won’t feel offended as this is purely random 😊).
3) One-hot encoding
Notice above after encoding, German becomes 1, France is 0, Spain is 2. However, there is no relational order between countries. Namely, Spain is not higher than German, and France is not lower than Spain. So we need to create dummy variables for the categorical variables to remove the numerical relationship introduced by categorical encoding. Here only need to do it for Geography column, since there is only 2 categories for the Gender column.
from sklearn.preprocessing import OneHotEncoderonehotencoder = OneHotEncoder(categorical_features = [1])X = onehotencoder.fit_transform(X).toarray()
Figure 2 is the encoded data. Notice the first 3 columns are one-hot encoded dummy variables for Country German, France, and Spain.
To avoid the dummy data trap, we remove the 1st column because two columns with 0 and 1 are enough to encode 3 countries.
X = X[:, 1:]
4) Data split
Next, split the data into training and test set with the test set taking 20%. We use random_state to make sure splitting remains the same each time.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y,test_size = 0.2, random_state = 0)
5) Feature scaling
Scaling the features is to avoid intensive computation and also avoid one variable dominating the others. For a binary classification problem, no need to scale the dependent variable. But for regression, we need to scale the dependent variables.
Normal methods include Standardization and Normalization as shown in Figure 3. Here we take Standardization.
from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)
Note, we use the scale set from the training set to transform the test set. With this step, data processing is done. Figure 4 is the test data you should get.
3. Model building
Here we build a Sequential model using Keras. The first step is to initialize the sequential model.
classifier = Sequential()
For this problem, the model is built with 2 dense layers.
#add input layer and first hidden layerclassifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’, input_dim = 11))#add 2nd hidden layerclassifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’))
Note that Output_dim for the hidden layer is a choice of art, depending on your experience. As a tip, based on experimentation, choosing it as the average between the number of nodes in the input layer and the number of nodes in the output layer. A more sensible method is to use parameter tuning which tests different models with different parameters using a technique like k-fold cross-validation. Here, the input dimension is 11 features and the output dimension is 1, thus the output dimension is 6. Here we use uniform distributions to randomize weights between 0 and 1. Use ReLU function for hidden layer activation, based on my experimentation, this is the best. Do feel free to try yours.
Below add the output layer.
classifier.add(Dense(output_dim = 1, init = ‘uniform’, activation = ‘sigmoid’))
For the output layer, we use Sigmoid function to get the probability of the customer leave or stay at the bank. If dealing with multi-classification, use Softmax function.
4. Model compiling
Model compiling is to apply Stochastic Gradient Descent (SGD) on the network.
classifier.compile(optimizer = ‘Adam’, loss =’binary_crossentropy’, metrics = [‘accuracy’])
Here we use Adam (one type of SGD) as an optimizer to find the optimized weights that make neural network most powerful. The loss function that the optimizer is based on is binary cross-entropy. The metrics we use to evaluate the model performance are accuracy.
5. Model fit
Since we use SGD, the batch size is set to 10, indicating neural network updates its weight after 10 observations. Epoch is a round of whole data flow through the network. Here we choose 100.
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
Now time to fit the model. After about 35 epochs, model accuracy converges to 0.837. Not bad, right ✨✨?
6. Model prediction
With the model fitted, we test the model on test data. Use a threshold of 0.5, to turn data into True(leaving) and False(stay) data.
y_pred = classifier.predict(X_test)y_pred = (y_pred > 0.5)
Then we use confusion_matrix to investigate the model performance on the test set.
from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_test, y_pred
The accuracy is 0.859, higher than training accuracy, implying over-fitting.
With the above model, the bank can test new customers and get the probability of leaving or stay. Then, the bank can take 10% of customers with the highest possibility and perform deep mining on the customer data to understand why they are likely to leave. That is the purpose of an artificial neural network.
Now one last question: how to make a prediction on new customer data 🤔? For instance, customer data in Figure 5:
As you imagine, we need to follow the same data processing. First, encode the variables. For instance, Geography France is encoded into (0,0) in the dummy variables, Gender male is 1. Following the method, we produce the below array.
new_customer = [[0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]]
Alright, one homework question: why do we use [[]] to create the array 🤔?
The next step is to scale the variables into the same scale as the training set.
new_customer = sc.transform(sc.transform(new_customer))
With the data ready, the prediction is done by:
new_prediction = classifier.predict(new_customer)new_prediction = (new_prediction > 0.5)
The prediction result is False with a possibility of 0.418%, indicating this customer is not likely to leave the bank 👍👍.
Great! That’s all. If you need some extra, visit my Github repos (FYI, the repos is actively maintained) 💕💕. | [
{
"code": null,
"e": 378,
"s": 171,
"text": "This article aims to explain how to create an artificial neural network (ANN) to predict if a banker customer is leaving or not using raw banking customers' data. The article is split into 6 parts as below."
},
{
"code": null,
"e": 469,
"s": 378,
"text": "Problem statementData processingModel buildingModel compilingModel fittingModel prediction"
},
{
"code": null,
"e": 487,
"s": 469,
"text": "Problem statement"
},
{
"code": null,
"e": 503,
"s": 487,
"text": "Data processing"
},
{
"code": null,
"e": 518,
"s": 503,
"text": "Model building"
},
{
"code": null,
"e": 534,
"s": 518,
"text": "Model compiling"
},
{
"code": null,
"e": 548,
"s": 534,
"text": "Model fitting"
},
{
"code": null,
"e": 565,
"s": 548,
"text": "Model prediction"
},
{
"code": null,
"e": 603,
"s": 565,
"text": "Now let’s begin the journey 🏃♂️🏃♀️!"
},
{
"code": null,
"e": 624,
"s": 603,
"text": "1. Problem statement"
},
{
"code": null,
"e": 823,
"s": 624,
"text": "We are tasked by a bank to predict if a customer is likely to leave the bank. 6-month customer banking data is given. The bank plans to use your findings to re-engage with customers who are leaving."
},
{
"code": null,
"e": 842,
"s": 823,
"text": "2. Data processing"
},
{
"code": null,
"e": 904,
"s": 842,
"text": "First, import the data with Pandas using read_csv() as below."
},
{
"code": null,
"e": 949,
"s": 904,
"text": "dataset = pd.read_csv(‘Churn_Modelling.csv’)"
},
{
"code": null,
"e": 1174,
"s": 949,
"text": "Figure 1 shows a snippet of the data. The first 13 columns are independent variables about customer ID, name, Credit Score, Geography, Gender, Age, etc. The last column is a dependent variable if the customer left or stayed."
},
{
"code": null,
"e": 1208,
"s": 1174,
"text": "Now, let’s start data processing."
},
{
"code": null,
"e": 1229,
"s": 1208,
"text": "1) Feature selection"
},
{
"code": null,
"e": 1683,
"s": 1229,
"text": "The first question: do we need all independent variables to fit the model 🤔? The answer is No. For instance, Row Number, Customer ID, or Surname has no impact on the customer leaving or staying. But customer’s age may have, as young customers possibly tend to leave the bank. So with this logic, we tell which independent variables would impact the outcome. But remember only the neural network can tell which features have a high impact on the outcome."
},
{
"code": null,
"e": 1713,
"s": 1683,
"text": "So independent variable X is:"
},
{
"code": null,
"e": 1747,
"s": 1713,
"text": "X = dataset.iloc[:, 3: 13].values"
},
{
"code": null,
"e": 1772,
"s": 1747,
"text": "Dependent variable y is:"
},
{
"code": null,
"e": 1803,
"s": 1772,
"text": "y = dataset.iloc[:, 13].values"
},
{
"code": null,
"e": 1827,
"s": 1803,
"text": "2) Categorical encoding"
},
{
"code": null,
"e": 1884,
"s": 1827,
"text": "Neural networks only take numerical values for learning."
},
{
"code": null,
"e": 2098,
"s": 1884,
"text": "Therefore, categorical variables, such as Geography and Gender need to be encoded into numerical ones. Here we use fit_transform() method of LabelEncoder from sklearn. We create two label encoders for each column."
},
{
"code": null,
"e": 2227,
"s": 2098,
"text": "from sklearn.preprocessing import LabelEncoderlabelencoder_X_1 = LabelEncoder()X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])"
},
{
"code": null,
"e": 2423,
"s": 2227,
"text": "Notice above, we input index 1, as the index of Geography column in X is 1. After encoding, country German becomes 1, France is 0, Spain is 2. With the same method, encode Gender column as below."
},
{
"code": null,
"e": 2506,
"s": 2423,
"text": "labelencoder_X_2 = LabelEncoder()X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])"
},
{
"code": null,
"e": 2615,
"s": 2506,
"text": "Now, the male is 1 and female become 0 (hopefully Dear Lady won’t feel offended as this is purely random 😊)."
},
{
"code": null,
"e": 2635,
"s": 2615,
"text": "3) One-hot encoding"
},
{
"code": null,
"e": 3083,
"s": 2635,
"text": "Notice above after encoding, German becomes 1, France is 0, Spain is 2. However, there is no relational order between countries. Namely, Spain is not higher than German, and France is not lower than Spain. So we need to create dummy variables for the categorical variables to remove the numerical relationship introduced by categorical encoding. Here only need to do it for Geography column, since there is only 2 categories for the Gender column."
},
{
"code": null,
"e": 3232,
"s": 3083,
"text": "from sklearn.preprocessing import OneHotEncoderonehotencoder = OneHotEncoder(categorical_features = [1])X = onehotencoder.fit_transform(X).toarray()"
},
{
"code": null,
"e": 3364,
"s": 3232,
"text": "Figure 2 is the encoded data. Notice the first 3 columns are one-hot encoded dummy variables for Country German, France, and Spain."
},
{
"code": null,
"e": 3486,
"s": 3364,
"text": "To avoid the dummy data trap, we remove the 1st column because two columns with 0 and 1 are enough to encode 3 countries."
},
{
"code": null,
"e": 3499,
"s": 3486,
"text": "X = X[:, 1:]"
},
{
"code": null,
"e": 3513,
"s": 3499,
"text": "4) Data split"
},
{
"code": null,
"e": 3662,
"s": 3513,
"text": "Next, split the data into training and test set with the test set taking 20%. We use random_state to make sure splitting remains the same each time."
},
{
"code": null,
"e": 3806,
"s": 3662,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y,test_size = 0.2, random_state = 0)"
},
{
"code": null,
"e": 3825,
"s": 3806,
"text": "5) Feature scaling"
},
{
"code": null,
"e": 4071,
"s": 3825,
"text": "Scaling the features is to avoid intensive computation and also avoid one variable dominating the others. For a binary classification problem, no need to scale the dependent variable. But for regression, we need to scale the dependent variables."
},
{
"code": null,
"e": 4180,
"s": 4071,
"text": "Normal methods include Standardization and Normalization as shown in Figure 3. Here we take Standardization."
},
{
"code": null,
"e": 4314,
"s": 4180,
"text": "from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)"
},
{
"code": null,
"e": 4473,
"s": 4314,
"text": "Note, we use the scale set from the training set to transform the test set. With this step, data processing is done. Figure 4 is the test data you should get."
},
{
"code": null,
"e": 4491,
"s": 4473,
"text": "3. Model building"
},
{
"code": null,
"e": 4591,
"s": 4491,
"text": "Here we build a Sequential model using Keras. The first step is to initialize the sequential model."
},
{
"code": null,
"e": 4617,
"s": 4591,
"text": "classifier = Sequential()"
},
{
"code": null,
"e": 4675,
"s": 4617,
"text": "For this problem, the model is built with 2 dense layers."
},
{
"code": null,
"e": 4904,
"s": 4675,
"text": "#add input layer and first hidden layerclassifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’, input_dim = 11))#add 2nd hidden layerclassifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’))"
},
{
"code": null,
"e": 5601,
"s": 4904,
"text": "Note that Output_dim for the hidden layer is a choice of art, depending on your experience. As a tip, based on experimentation, choosing it as the average between the number of nodes in the input layer and the number of nodes in the output layer. A more sensible method is to use parameter tuning which tests different models with different parameters using a technique like k-fold cross-validation. Here, the input dimension is 11 features and the output dimension is 1, thus the output dimension is 6. Here we use uniform distributions to randomize weights between 0 and 1. Use ReLU function for hidden layer activation, based on my experimentation, this is the best. Do feel free to try yours."
},
{
"code": null,
"e": 5629,
"s": 5601,
"text": "Below add the output layer."
},
{
"code": null,
"e": 5709,
"s": 5629,
"text": "classifier.add(Dense(output_dim = 1, init = ‘uniform’, activation = ‘sigmoid’))"
},
{
"code": null,
"e": 5881,
"s": 5709,
"text": "For the output layer, we use Sigmoid function to get the probability of the customer leave or stay at the bank. If dealing with multi-classification, use Softmax function."
},
{
"code": null,
"e": 5900,
"s": 5881,
"text": "4. Model compiling"
},
{
"code": null,
"e": 5978,
"s": 5900,
"text": "Model compiling is to apply Stochastic Gradient Descent (SGD) on the network."
},
{
"code": null,
"e": 6070,
"s": 5978,
"text": "classifier.compile(optimizer = ‘Adam’, loss =’binary_crossentropy’, metrics = [‘accuracy’])"
},
{
"code": null,
"e": 6332,
"s": 6070,
"text": "Here we use Adam (one type of SGD) as an optimizer to find the optimized weights that make neural network most powerful. The loss function that the optimizer is based on is binary cross-entropy. The metrics we use to evaluate the model performance are accuracy."
},
{
"code": null,
"e": 6345,
"s": 6332,
"text": "5. Model fit"
},
{
"code": null,
"e": 6537,
"s": 6345,
"text": "Since we use SGD, the batch size is set to 10, indicating neural network updates its weight after 10 observations. Epoch is a round of whole data flow through the network. Here we choose 100."
},
{
"code": null,
"e": 6601,
"s": 6537,
"text": "classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)"
},
{
"code": null,
"e": 6705,
"s": 6601,
"text": "Now time to fit the model. After about 35 epochs, model accuracy converges to 0.837. Not bad, right ✨✨?"
},
{
"code": null,
"e": 6725,
"s": 6705,
"text": "6. Model prediction"
},
{
"code": null,
"e": 6858,
"s": 6725,
"text": "With the model fitted, we test the model on test data. Use a threshold of 0.5, to turn data into True(leaving) and False(stay) data."
},
{
"code": null,
"e": 6917,
"s": 6858,
"text": "y_pred = classifier.predict(X_test)y_pred = (y_pred > 0.5)"
},
{
"code": null,
"e": 7000,
"s": 6917,
"text": "Then we use confusion_matrix to investigate the model performance on the test set."
},
{
"code": null,
"e": 7081,
"s": 7000,
"text": "from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_test, y_pred"
},
{
"code": null,
"e": 7158,
"s": 7081,
"text": "The accuracy is 0.859, higher than training accuracy, implying over-fitting."
},
{
"code": null,
"e": 7468,
"s": 7158,
"text": "With the above model, the bank can test new customers and get the probability of leaving or stay. Then, the bank can take 10% of customers with the highest possibility and perform deep mining on the customer data to understand why they are likely to leave. That is the purpose of an artificial neural network."
},
{
"code": null,
"e": 7581,
"s": 7468,
"text": "Now one last question: how to make a prediction on new customer data 🤔? For instance, customer data in Figure 5:"
},
{
"code": null,
"e": 7815,
"s": 7581,
"text": "As you imagine, we need to follow the same data processing. First, encode the variables. For instance, Geography France is encoded into (0,0) in the dummy variables, Gender male is 1. Following the method, we produce the below array."
},
{
"code": null,
"e": 7877,
"s": 7815,
"text": "new_customer = [[0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]]"
},
{
"code": null,
"e": 7951,
"s": 7877,
"text": "Alright, one homework question: why do we use [[]] to create the array 🤔?"
},
{
"code": null,
"e": 8032,
"s": 7951,
"text": "The next step is to scale the variables into the same scale as the training set."
},
{
"code": null,
"e": 8088,
"s": 8032,
"text": "new_customer = sc.transform(sc.transform(new_customer))"
},
{
"code": null,
"e": 8136,
"s": 8088,
"text": "With the data ready, the prediction is done by:"
},
{
"code": null,
"e": 8225,
"s": 8136,
"text": "new_prediction = classifier.predict(new_customer)new_prediction = (new_prediction > 0.5)"
},
{
"code": null,
"e": 8347,
"s": 8225,
"text": "The prediction result is False with a possibility of 0.418%, indicating this customer is not likely to leave the bank 👍👍."
}
] |
How do I un-escape a backslash-escaped string in Python? | There are two ways to go about unescaping backslash escaped strings in Python. First is using literal_eval to evaluate the string. Note that in this method you need to surround the string in another layer of quotes. For example:
>>> import ast
>>> a = '"Hello,\\nworld"'
>>> print ast.literal_eval(a)
Hello,
world
Another way is to use the decode('string_escape') method from the string class. For example,
>>> print "Hello,\\nworld".decode('string_escape')
Hello,
world | [
{
"code": null,
"e": 1291,
"s": 1062,
"text": "There are two ways to go about unescaping backslash escaped strings in Python. First is using literal_eval to evaluate the string. Note that in this method you need to surround the string in another layer of quotes. For example:"
},
{
"code": null,
"e": 1376,
"s": 1291,
"text": ">>> import ast\n>>> a = '\"Hello,\\\\nworld\"'\n>>> print ast.literal_eval(a)\nHello,\nworld"
},
{
"code": null,
"e": 1469,
"s": 1376,
"text": "Another way is to use the decode('string_escape') method from the string class. For example,"
},
{
"code": null,
"e": 1533,
"s": 1469,
"text": ">>> print \"Hello,\\\\nworld\".decode('string_escape')\nHello,\nworld"
}
] |
Check if all occurrences of a character appear together - GeeksforGeeks | 04 May, 2021
Given a string s and a character c, find if all occurrences of c appear together in s or not. If the character c does not appear in the string at all, the answer is true.
Examples
Input: s = "1110000323", c = '1'
Output: Yes
All occurrences of '1' appear together in
"1110000323"
Input: s = "3231131", c = '1'
Output: No
All occurrences of 1 are not together
Input: s = "abcabc", c = 'c'
Output: No
All occurrences of 'c' are not together
Input: s = "ababcc", c = 'c'
Output: Yes
All occurrences of 'c' are together
The idea is to traverse given string, as soon as we find an occurrence of c, we keep traversing until we find a character which is not c. We also set a flag to indicate that one more occurrences of c are seen. If we see c again and flag is set, then we return false.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if all occurrences// of a character appear together in a string.#include <iostream>#include <string>using namespace std; bool checkIfAllTogether(string s, char c){ // To indicate if one or more occurrences // of 'c' are seen or not. bool oneSeen = false; // Traverse given string int i = 0, n = s.length(); while (i < n) { // If current character is same as c, // we first check if c is already seen. if (s[i] == c) { if (oneSeen == true) return false; // If this is very first appearance of c, // we traverse all consecutive occurrences. while (i < n && s[i] == c) i++; // To indicate that character is seen once. oneSeen = true; } else i++; } return true;} // Driver programint main(){ string s = "110029"; if (checkIfAllTogether(s, '1')) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
// Java program to find if all// occurrences of a character// appear together in a string.import java.io.*; class GFG { static boolean checkIfAllTogether(String s, char c) { // To indicate if one or more // occurrences of 'c' are seen // or not. boolean oneSeen = false; // Traverse given string int i = 0, n = s.length(); while (i < n) { // If current character is // same as c, we first check // if c is already seen. if (s.charAt(i) == c) { if (oneSeen == true) return false; // If this is very first // appearance of c, we // traverse all consecutive // occurrences. while (i < n && s.charAt(i) == c) i++; // To indicate that character // is seen once. oneSeen = true; } else i++; } return true; } // Driver Code public static void main(String[] args) { String s = "110029"; if (checkIfAllTogether(s, '1')) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Sam007.
# Python program to find# if all occurrences# of a character appear# together in a string. # function to find# if all occurrences# of a character appear# together in a string.def checkIfAllTogether(s, c) : # To indicate if one or # more occurrences of # 'c' are seen or not. oneSeen = False # Traverse given string i = 0 n = len(s) while (i < n) : # If current character # is same as c, # we first check # if c is already seen. if (s[i] == c) : if (oneSeen == True) : return False # If this is very first # appearance of c, # we traverse all # consecutive occurrences. while (i < n and s[i] == c) : i = i + 1 # To indicate that character # is seen once. oneSeen = True else : i = i + 1 return True # Driver Codes = "110029";if (checkIfAllTogether(s, '1')) : print ("Yes\n")else : print ("No\n") # This code is contributed by# Manish Shaw (manishshaw1)
// C# program to find if all occurrences// of a character appear together in a// string.using System; public class GFG { static bool checkIfAllTogether(string s, char c) { // To indicate if one or more // occurrences of 'c' are seen // or not. bool oneSeen = false; // Traverse given string int i = 0, n = s.Length; while (i < n) { // If current character is // same as c, we first check // if c is already seen. if (s[i] == c) { if (oneSeen == true) return false; // If this is very first // appearance of c, we // traverse all consecutive // occurrences. while (i < n && s[i] == c) i++; // To indicate that character // is seen once. oneSeen = true; } else i++; } return true; } // Driver code public static void Main() { string s = "110029"; if (checkIfAllTogether(s, '1')) Console.Write( "Yes" ); else Console.Write( "No" ); }} // This code is contributed by Sam007.
<?php// PHP program to find// if all occurrences// of a character appear// together in a string. // function to find// if all occurrences// of a character appear// together in a string.function checkIfAllTogether($s, $c){ // To indicate if one or // more occurrences of // 'c' are seen or not. $oneSeen = false; // Traverse given string $i = 0; $n = strlen($s); while ($i < $n) { // If current character // is same as c, // we first check // if c is already seen. if ($s[$i] == $c) { if ($oneSeen == true) return false; // If this is very first // appearance of c, // we traverse all // consecutive occurrences. while ($i < $n && $s[$i] == $c) $i++; // To indicate that character // is seen once. $oneSeen = true; } else $i++; } return true;} // Driver Code$s = "110029";if (checkIfAllTogether($s, '1')) echo("Yes\n");else echo("No\n"); // This code is contributed by Ajit.?>
<script> // Javascript program to find if all// occurrences of a character appear// together in a string.function checkIfAllTogether(s, c){ // To indicate if one or more // occurrences of 'c' are seen // or not. let oneSeen = false; // Traverse given string let i = 0, n = s.length; while (i < n) { // If current character is // same as c, we first check // if c is already seen. if (s[i] == c) { if (oneSeen == true) return false; // If this is very first // appearance of c, we // traverse all consecutive // occurrences. while (i < n && s[i] == c) i++; // To indicate that character // is seen once. oneSeen = true; } else i++; } return true;} // Driver codelet s = "110029"; if (checkIfAllTogether(s, '1')) document.write("Yes");else document.write("No"); // This code is contributed by mukesh07 </script>
Output:
Yes
The complexity of above program is O(n).
Sam007
jit_t
manishshaw1
mukesh07
Arrays
Searching
Strings
Arrays
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1 | [
{
"code": null,
"e": 25200,
"s": 25172,
"text": "\n04 May, 2021"
},
{
"code": null,
"e": 25371,
"s": 25200,
"text": "Given a string s and a character c, find if all occurrences of c appear together in s or not. If the character c does not appear in the string at all, the answer is true."
},
{
"code": null,
"e": 25381,
"s": 25371,
"text": "Examples "
},
{
"code": null,
"e": 25723,
"s": 25381,
"text": "Input: s = \"1110000323\", c = '1'\nOutput: Yes\nAll occurrences of '1' appear together in\n\"1110000323\"\n\nInput: s = \"3231131\", c = '1'\nOutput: No\nAll occurrences of 1 are not together\n\nInput: s = \"abcabc\", c = 'c'\nOutput: No\nAll occurrences of 'c' are not together\n\nInput: s = \"ababcc\", c = 'c'\nOutput: Yes\nAll occurrences of 'c' are together"
},
{
"code": null,
"e": 25992,
"s": 25723,
"text": "The idea is to traverse given string, as soon as we find an occurrence of c, we keep traversing until we find a character which is not c. We also set a flag to indicate that one more occurrences of c are seen. If we see c again and flag is set, then we return false. "
},
{
"code": null,
"e": 25996,
"s": 25992,
"text": "C++"
},
{
"code": null,
"e": 26001,
"s": 25996,
"text": "Java"
},
{
"code": null,
"e": 26009,
"s": 26001,
"text": "Python3"
},
{
"code": null,
"e": 26012,
"s": 26009,
"text": "C#"
},
{
"code": null,
"e": 26016,
"s": 26012,
"text": "PHP"
},
{
"code": null,
"e": 26027,
"s": 26016,
"text": "Javascript"
},
{
"code": "// C++ program to find if all occurrences// of a character appear together in a string.#include <iostream>#include <string>using namespace std; bool checkIfAllTogether(string s, char c){ // To indicate if one or more occurrences // of 'c' are seen or not. bool oneSeen = false; // Traverse given string int i = 0, n = s.length(); while (i < n) { // If current character is same as c, // we first check if c is already seen. if (s[i] == c) { if (oneSeen == true) return false; // If this is very first appearance of c, // we traverse all consecutive occurrences. while (i < n && s[i] == c) i++; // To indicate that character is seen once. oneSeen = true; } else i++; } return true;} // Driver programint main(){ string s = \"110029\"; if (checkIfAllTogether(s, '1')) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 27058,
"s": 26027,
"text": null
},
{
"code": "// Java program to find if all// occurrences of a character// appear together in a string.import java.io.*; class GFG { static boolean checkIfAllTogether(String s, char c) { // To indicate if one or more // occurrences of 'c' are seen // or not. boolean oneSeen = false; // Traverse given string int i = 0, n = s.length(); while (i < n) { // If current character is // same as c, we first check // if c is already seen. if (s.charAt(i) == c) { if (oneSeen == true) return false; // If this is very first // appearance of c, we // traverse all consecutive // occurrences. while (i < n && s.charAt(i) == c) i++; // To indicate that character // is seen once. oneSeen = true; } else i++; } return true; } // Driver Code public static void main(String[] args) { String s = \"110029\"; if (checkIfAllTogether(s, '1')) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Sam007.",
"e": 28462,
"s": 27058,
"text": null
},
{
"code": "# Python program to find# if all occurrences# of a character appear# together in a string. # function to find# if all occurrences# of a character appear# together in a string.def checkIfAllTogether(s, c) : # To indicate if one or # more occurrences of # 'c' are seen or not. oneSeen = False # Traverse given string i = 0 n = len(s) while (i < n) : # If current character # is same as c, # we first check # if c is already seen. if (s[i] == c) : if (oneSeen == True) : return False # If this is very first # appearance of c, # we traverse all # consecutive occurrences. while (i < n and s[i] == c) : i = i + 1 # To indicate that character # is seen once. oneSeen = True else : i = i + 1 return True # Driver Codes = \"110029\";if (checkIfAllTogether(s, '1')) : print (\"Yes\\n\")else : print (\"No\\n\") # This code is contributed by# Manish Shaw (manishshaw1)",
"e": 29550,
"s": 28462,
"text": null
},
{
"code": "// C# program to find if all occurrences// of a character appear together in a// string.using System; public class GFG { static bool checkIfAllTogether(string s, char c) { // To indicate if one or more // occurrences of 'c' are seen // or not. bool oneSeen = false; // Traverse given string int i = 0, n = s.Length; while (i < n) { // If current character is // same as c, we first check // if c is already seen. if (s[i] == c) { if (oneSeen == true) return false; // If this is very first // appearance of c, we // traverse all consecutive // occurrences. while (i < n && s[i] == c) i++; // To indicate that character // is seen once. oneSeen = true; } else i++; } return true; } // Driver code public static void Main() { string s = \"110029\"; if (checkIfAllTogether(s, '1')) Console.Write( \"Yes\" ); else Console.Write( \"No\" ); }} // This code is contributed by Sam007.",
"e": 30908,
"s": 29550,
"text": null
},
{
"code": "<?php// PHP program to find// if all occurrences// of a character appear// together in a string. // function to find// if all occurrences// of a character appear// together in a string.function checkIfAllTogether($s, $c){ // To indicate if one or // more occurrences of // 'c' are seen or not. $oneSeen = false; // Traverse given string $i = 0; $n = strlen($s); while ($i < $n) { // If current character // is same as c, // we first check // if c is already seen. if ($s[$i] == $c) { if ($oneSeen == true) return false; // If this is very first // appearance of c, // we traverse all // consecutive occurrences. while ($i < $n && $s[$i] == $c) $i++; // To indicate that character // is seen once. $oneSeen = true; } else $i++; } return true;} // Driver Code$s = \"110029\";if (checkIfAllTogether($s, '1')) echo(\"Yes\\n\");else echo(\"No\\n\"); // This code is contributed by Ajit.?>",
"e": 32030,
"s": 30908,
"text": null
},
{
"code": "<script> // Javascript program to find if all// occurrences of a character appear// together in a string.function checkIfAllTogether(s, c){ // To indicate if one or more // occurrences of 'c' are seen // or not. let oneSeen = false; // Traverse given string let i = 0, n = s.length; while (i < n) { // If current character is // same as c, we first check // if c is already seen. if (s[i] == c) { if (oneSeen == true) return false; // If this is very first // appearance of c, we // traverse all consecutive // occurrences. while (i < n && s[i] == c) i++; // To indicate that character // is seen once. oneSeen = true; } else i++; } return true;} // Driver codelet s = \"110029\"; if (checkIfAllTogether(s, '1')) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by mukesh07 </script>",
"e": 33111,
"s": 32030,
"text": null
},
{
"code": null,
"e": 33120,
"s": 33111,
"text": "Output: "
},
{
"code": null,
"e": 33124,
"s": 33120,
"text": "Yes"
},
{
"code": null,
"e": 33166,
"s": 33124,
"text": "The complexity of above program is O(n). "
},
{
"code": null,
"e": 33173,
"s": 33166,
"text": "Sam007"
},
{
"code": null,
"e": 33179,
"s": 33173,
"text": "jit_t"
},
{
"code": null,
"e": 33191,
"s": 33179,
"text": "manishshaw1"
},
{
"code": null,
"e": 33200,
"s": 33191,
"text": "mukesh07"
},
{
"code": null,
"e": 33207,
"s": 33200,
"text": "Arrays"
},
{
"code": null,
"e": 33217,
"s": 33207,
"text": "Searching"
},
{
"code": null,
"e": 33225,
"s": 33217,
"text": "Strings"
},
{
"code": null,
"e": 33232,
"s": 33225,
"text": "Arrays"
},
{
"code": null,
"e": 33242,
"s": 33232,
"text": "Searching"
},
{
"code": null,
"e": 33250,
"s": 33242,
"text": "Strings"
},
{
"code": null,
"e": 33348,
"s": 33250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33396,
"s": 33348,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33440,
"s": 33396,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33472,
"s": 33440,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33495,
"s": 33472,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33509,
"s": 33495,
"text": "Linear Search"
},
{
"code": null,
"e": 33523,
"s": 33509,
"text": "Binary Search"
},
{
"code": null,
"e": 33537,
"s": 33523,
"text": "Linear Search"
},
{
"code": null,
"e": 33605,
"s": 33537,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 33629,
"s": 33605,
"text": "Find the Missing Number"
}
] |
Final static variables in Java | Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many objects are created from it.
There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Static variables are normally declared as constants using the final keyword. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
Static variables are normally declared as constants using the final keyword. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
Static variables are stored in the static memory, mostly declared as final and used as either public or private constants.
Static variables are stored in the static memory, mostly declared as final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class name ClassName.VariableName.
Static variables can be accessed by calling with the class name ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
public class Tester {
// DEPARTMENT is a static constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
String salary = "1000";
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
This will produce the following result −
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block."
},
{
"code": null,
"e": 1346,
"s": 1204,
"text": "Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block."
},
{
"code": null,
"e": 1461,
"s": 1346,
"text": "There would only be one copy of each class variable per class, regardless of how many objects are created from it."
},
{
"code": null,
"e": 1576,
"s": 1461,
"text": "There would only be one copy of each class variable per class, regardless of how many objects are created from it."
},
{
"code": null,
"e": 1791,
"s": 1576,
"text": "Static variables are normally declared as constants using the final keyword. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value."
},
{
"code": null,
"e": 2006,
"s": 1791,
"text": "Static variables are normally declared as constants using the final keyword. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value."
},
{
"code": null,
"e": 2129,
"s": 2006,
"text": "Static variables are stored in the static memory, mostly declared as final and used as either public or private constants."
},
{
"code": null,
"e": 2252,
"s": 2129,
"text": "Static variables are stored in the static memory, mostly declared as final and used as either public or private constants."
},
{
"code": null,
"e": 2343,
"s": 2252,
"text": "Static variables are created when the program starts and destroyed when the program stops."
},
{
"code": null,
"e": 2434,
"s": 2343,
"text": "Static variables are created when the program starts and destroyed when the program stops."
},
{
"code": null,
"e": 2583,
"s": 2434,
"text": "Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class."
},
{
"code": null,
"e": 2732,
"s": 2583,
"text": "Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class."
},
{
"code": null,
"e": 3030,
"s": 2732,
"text": "Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks."
},
{
"code": null,
"e": 3328,
"s": 3030,
"text": "Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks."
},
{
"code": null,
"e": 3416,
"s": 3328,
"text": "Static variables can be accessed by calling with the class name ClassName.VariableName."
},
{
"code": null,
"e": 3504,
"s": 3416,
"text": "Static variables can be accessed by calling with the class name ClassName.VariableName."
},
{
"code": null,
"e": 3727,
"s": 3504,
"text": "When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables."
},
{
"code": null,
"e": 3950,
"s": 3727,
"text": "When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables."
},
{
"code": null,
"e": 4219,
"s": 3950,
"text": "public class Tester {\n // DEPARTMENT is a static constant\n public static final String DEPARTMENT = \"Development \";\n\n public static void main(String args[]) {\n\n String salary = \"1000\";\n System.out.println(DEPARTMENT + \"average salary:\" + salary);\n }\n}"
},
{
"code": null,
"e": 4260,
"s": 4219,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4292,
"s": 4260,
"text": "Development average salary:1000"
},
{
"code": null,
"e": 4407,
"s": 4292,
"text": "Note − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT"
}
] |
Check if n is divisible by power of 2 without using arithmetic operators - GeeksforGeeks | 16 Aug, 2021
Given two positive integers n and m. The problem is to check whether n is divisible by 2m or not without using arithmetic operators.
Examples:
Input : n = 8, m = 2
Output : Yes
Input : n = 14, m = 3
Output : No
Approach: If a number is divisible by 2 then it has its least significant bit (LSB) set to 0, if divisible by 4 then two LSB’s set to 0, if by 8 then three LSB’s set to 0, and so on. Keeping this in mind, a number n is divisible by 2m if (n & ((1 << m) – 1)) is equal to 0 else not.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to check whether n// is divisible by pow(2, m)#include <bits/stdc++.h> using namespace std; // function to check whether n// is divisible by pow(2, m)bool isDivBy2PowerM(unsigned int n, unsigned int m){ // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false;} // Driver program to test aboveint main(){ unsigned int n = 8, m = 2; if (isDivBy2PowerM(n, m)) cout << "Yes"; else cout << "No"; return 0;}
// JAVA Code for Check if n is divisible // by power of 2 without using arithmetic// operatorsimport java.util.*; class GFG { // function to check whether n // is divisible by pow(2, m) static boolean isDivBy2PowerM(int n, int m) { // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false; } /* Driver program to test above function */ public static void main(String[] args) { int n = 8, m = 2; if (isDivBy2PowerM(n, m)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 implementation to check# whether n is divisible by pow(2, m) # function to check whether n# is divisible by pow(2, m)def isDivBy2PowerM (n, m): # if expression results to 0, then # n is divisible by pow(2, m) if (n & ((1 << m) - 1)) == 0: return True # n is not divisible return False # Driver program to test aboven = 8m = 2if isDivBy2PowerM(n, m): print("Yes")else: print( "No") # This code is contributed by "Sharad_Bhardwaj".
// C# Code for Check if n is divisible// by power of 2 without using arithmetic// operatorsusing System; class GFG { // function to check whether n // is divisible by pow(2, m) static bool isDivBy2PowerM(int n, int m) { // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false; } /* Driver program to test above function */ public static void Main() { int n = 8, m = 2; if (isDivBy2PowerM(n, m)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by Sam007
<?php// PHP implementation to check whether// n is divisible by pow(2, m) // function to check whether n// is divisible by pow(2, m)function isDivBy2PowerM($n, $m){ // if expression results to 0, then // n is divisible by pow(2, m) if (($n & ((1 << $m) - 1)) == 0) return true; // n is not divisible return false;} // Driver Code $n = 8; $m = 2; if (isDivBy2PowerM($n, $m)) echo "Yes"; else echo "No"; // This code is contributed by ajit?>
<script> // JavaScript implementation to check whether n// is divisible by pow(2, m) // function to check whether n// is divisible by pow(2, m)function isDivBy2PowerM(n, m){ // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false;} // Driver program to test above let n = 8, m = 2; if (isDivBy2PowerM(n, m)) document.write("Yes"); else document.write("No"); // This code is contributed by Surbhi Tyagi. </script>
Output:
Yes
YouTubeGeeksforGeeks501K subscribersCheck if n is divisible by power of 2 without using arithmetic operators | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4UgLrh_foDE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
jit_t
surbhityagi15
akshaysingh98088
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Implementation of Bit Stuffing and Bit Destuffing
Builtin functions of GCC compiler
Count total bits in a number
Swap bits in a given number
Check for Integer Overflow | [
{
"code": null,
"e": 25014,
"s": 24986,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 25147,
"s": 25014,
"text": "Given two positive integers n and m. The problem is to check whether n is divisible by 2m or not without using arithmetic operators."
},
{
"code": null,
"e": 25158,
"s": 25147,
"text": "Examples: "
},
{
"code": null,
"e": 25227,
"s": 25158,
"text": "Input : n = 8, m = 2\nOutput : Yes\n\nInput : n = 14, m = 3\nOutput : No"
},
{
"code": null,
"e": 25511,
"s": 25227,
"text": "Approach: If a number is divisible by 2 then it has its least significant bit (LSB) set to 0, if divisible by 4 then two LSB’s set to 0, if by 8 then three LSB’s set to 0, and so on. Keeping this in mind, a number n is divisible by 2m if (n & ((1 << m) – 1)) is equal to 0 else not. "
},
{
"code": null,
"e": 25515,
"s": 25511,
"text": "C++"
},
{
"code": null,
"e": 25520,
"s": 25515,
"text": "Java"
},
{
"code": null,
"e": 25528,
"s": 25520,
"text": "Python3"
},
{
"code": null,
"e": 25531,
"s": 25528,
"text": "C#"
},
{
"code": null,
"e": 25535,
"s": 25531,
"text": "PHP"
},
{
"code": null,
"e": 25546,
"s": 25535,
"text": "Javascript"
},
{
"code": "// C++ implementation to check whether n// is divisible by pow(2, m)#include <bits/stdc++.h> using namespace std; // function to check whether n// is divisible by pow(2, m)bool isDivBy2PowerM(unsigned int n, unsigned int m){ // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false;} // Driver program to test aboveint main(){ unsigned int n = 8, m = 2; if (isDivBy2PowerM(n, m)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26128,
"s": 25546,
"text": null
},
{
"code": "// JAVA Code for Check if n is divisible // by power of 2 without using arithmetic// operatorsimport java.util.*; class GFG { // function to check whether n // is divisible by pow(2, m) static boolean isDivBy2PowerM(int n, int m) { // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false; } /* Driver program to test above function */ public static void main(String[] args) { int n = 8, m = 2; if (isDivBy2PowerM(n, m)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 26948,
"s": 26128,
"text": null
},
{
"code": "# Python3 implementation to check# whether n is divisible by pow(2, m) # function to check whether n# is divisible by pow(2, m)def isDivBy2PowerM (n, m): # if expression results to 0, then # n is divisible by pow(2, m) if (n & ((1 << m) - 1)) == 0: return True # n is not divisible return False # Driver program to test aboven = 8m = 2if isDivBy2PowerM(n, m): print(\"Yes\")else: print( \"No\") # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 27434,
"s": 26948,
"text": null
},
{
"code": "// C# Code for Check if n is divisible// by power of 2 without using arithmetic// operatorsusing System; class GFG { // function to check whether n // is divisible by pow(2, m) static bool isDivBy2PowerM(int n, int m) { // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false; } /* Driver program to test above function */ public static void Main() { int n = 8, m = 2; if (isDivBy2PowerM(n, m)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by Sam007",
"e": 28128,
"s": 27434,
"text": null
},
{
"code": "<?php// PHP implementation to check whether// n is divisible by pow(2, m) // function to check whether n// is divisible by pow(2, m)function isDivBy2PowerM($n, $m){ // if expression results to 0, then // n is divisible by pow(2, m) if (($n & ((1 << $m) - 1)) == 0) return true; // n is not divisible return false;} // Driver Code $n = 8; $m = 2; if (isDivBy2PowerM($n, $m)) echo \"Yes\"; else echo \"No\"; // This code is contributed by ajit?>",
"e": 28626,
"s": 28128,
"text": null
},
{
"code": "<script> // JavaScript implementation to check whether n// is divisible by pow(2, m) // function to check whether n// is divisible by pow(2, m)function isDivBy2PowerM(n, m){ // if expression results to 0, then // n is divisible by pow(2, m) if ((n & ((1 << m) - 1)) == 0) return true; // n is not divisible return false;} // Driver program to test above let n = 8, m = 2; if (isDivBy2PowerM(n, m)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 29176,
"s": 28626,
"text": null
},
{
"code": null,
"e": 29185,
"s": 29176,
"text": "Output: "
},
{
"code": null,
"e": 29189,
"s": 29185,
"text": "Yes"
},
{
"code": null,
"e": 30060,
"s": 29189,
"text": "YouTubeGeeksforGeeks501K subscribersCheck if n is divisible by power of 2 without using arithmetic operators | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4UgLrh_foDE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 30068,
"s": 30062,
"text": "jit_t"
},
{
"code": null,
"e": 30082,
"s": 30068,
"text": "surbhityagi15"
},
{
"code": null,
"e": 30099,
"s": 30082,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 30109,
"s": 30099,
"text": "Bit Magic"
},
{
"code": null,
"e": 30119,
"s": 30109,
"text": "Bit Magic"
},
{
"code": null,
"e": 30217,
"s": 30119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30226,
"s": 30217,
"text": "Comments"
},
{
"code": null,
"e": 30239,
"s": 30226,
"text": "Old Comments"
},
{
"code": null,
"e": 30290,
"s": 30239,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 30313,
"s": 30290,
"text": "Program to find parity"
},
{
"code": null,
"e": 30350,
"s": 30313,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 30387,
"s": 30350,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 30451,
"s": 30387,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 30501,
"s": 30451,
"text": "Implementation of Bit Stuffing and Bit Destuffing"
},
{
"code": null,
"e": 30535,
"s": 30501,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 30564,
"s": 30535,
"text": "Count total bits in a number"
},
{
"code": null,
"e": 30592,
"s": 30564,
"text": "Swap bits in a given number"
}
] |
Reverse a number in JavaScript | Our aim is to write a JavaScript function that takes in a number and returns its reversed number
For example, reverse of 678 −
876
Here’s the code to reverse a number in JavaScript −
const num = 124323;
const reverse = (num) => parseInt(String(num)
.split("")
.reverse()
.join(""), 10);
console.log(reverse(num));
Output in the console will be −
323421
Explanation
Let’s say num = 123
We convert the num to string → num becomes ‘123’
We split ‘123’ → it becomes [‘1’, ‘2’, ‘3’]
We reverse the array → it becomes [‘3’, ‘2’, ‘1’]
We join the array to form a string → it becomes ‘321’
Lastly we parse the string into a Int and returns it → 321 | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "Our aim is to write a JavaScript function that takes in a number and returns its reversed number"
},
{
"code": null,
"e": 1189,
"s": 1159,
"text": "For example, reverse of 678 −"
},
{
"code": null,
"e": 1193,
"s": 1189,
"text": "876"
},
{
"code": null,
"e": 1245,
"s": 1193,
"text": "Here’s the code to reverse a number in JavaScript −"
},
{
"code": null,
"e": 1376,
"s": 1245,
"text": "const num = 124323;\nconst reverse = (num) => parseInt(String(num)\n.split(\"\")\n.reverse()\n.join(\"\"), 10);\nconsole.log(reverse(num));"
},
{
"code": null,
"e": 1408,
"s": 1376,
"text": "Output in the console will be −"
},
{
"code": null,
"e": 1415,
"s": 1408,
"text": "323421"
},
{
"code": null,
"e": 1427,
"s": 1415,
"text": "Explanation"
},
{
"code": null,
"e": 1447,
"s": 1427,
"text": "Let’s say num = 123"
},
{
"code": null,
"e": 1496,
"s": 1447,
"text": "We convert the num to string → num becomes ‘123’"
},
{
"code": null,
"e": 1540,
"s": 1496,
"text": "We split ‘123’ → it becomes [‘1’, ‘2’, ‘3’]"
},
{
"code": null,
"e": 1590,
"s": 1540,
"text": "We reverse the array → it becomes [‘3’, ‘2’, ‘1’]"
},
{
"code": null,
"e": 1644,
"s": 1590,
"text": "We join the array to form a string → it becomes ‘321’"
},
{
"code": null,
"e": 1703,
"s": 1644,
"text": "Lastly we parse the string into a Int and returns it → 321"
}
] |
Sort strings in Alphanumeric sequence | A list of given strings is sorted in alphanumeric order or Dictionary Order. Like for these words: Apple, Book, Aim, they will be sorted as Aim, Apple, Book.If there are some numbers, they can be placed before the alphabetic strings.
Input:
A list of strings: Ball Apple Data Area 517 April Man 506
Output:
Strings after sort: 506 517 Apple April Area Ball Data Man
sortStr(strArr, n)
Input: The list of all strings, number of elements.
Output − Strings in alphanumeric sorted order.
Begin
for round := 1 to n-1, do
for i := 0 to n-round, do
res := compare str[i] and str[i+1] //either +ve, or –ve or 0
if res > 0, then
swap str[i] and str[i+1]
done
done
End
#include<iostream>
#define N 8
using namespace std;
void display(int n, string str[]) {
for(int i = 0; i<n; i++)
cout << str[i] << " "; //print the string from array
cout << endl;
}
void sortStr(int n, string str[]) {
int i, round, res;
for(round = 1; round<n; round++)
for(i = 0; i<n-round; i++) {
res = str[i].compare(str[i+1]);
if(res > 0)
swap(str[i], str[i+1]);//swap strings
}
}
main() {
string str[N] = {"Ball", "Apple", "Data", "Area", "517", "April", "Man", "506"};
cout << "Strings before sort:"<< endl;
display(N, str);
sortStr(N, str);
cout << "Strings after sort:"<<endl;
display(N, str);
}
Strings before sort:
Ball Apple Data Area 517 April Man 506
Strings after sort:
506 517 Apple April Area Ball Data Man | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "A list of given strings is sorted in alphanumeric order or Dictionary Order. Like for these words: Apple, Book, Aim, they will be sorted as Aim, Apple, Book.If there are some numbers, they can be placed before the alphabetic strings."
},
{
"code": null,
"e": 1428,
"s": 1296,
"text": "Input:\nA list of strings: Ball Apple Data Area 517 April Man 506\nOutput:\nStrings after sort: 506 517 Apple April Area Ball Data Man"
},
{
"code": null,
"e": 1447,
"s": 1428,
"text": "sortStr(strArr, n)"
},
{
"code": null,
"e": 1499,
"s": 1447,
"text": "Input: The list of all strings, number of elements."
},
{
"code": null,
"e": 1546,
"s": 1499,
"text": "Output − Strings in alphanumeric sorted order."
},
{
"code": null,
"e": 1775,
"s": 1546,
"text": "Begin\n for round := 1 to n-1, do\n for i := 0 to n-round, do\n res := compare str[i] and str[i+1] //either +ve, or –ve or 0\n if res > 0, then\n swap str[i] and str[i+1]\n done\n done\nEnd"
},
{
"code": null,
"e": 2468,
"s": 1775,
"text": "#include<iostream>\n#define N 8\nusing namespace std;\n\nvoid display(int n, string str[]) {\n for(int i = 0; i<n; i++)\n cout << str[i] << \" \"; //print the string from array\n cout << endl;\n}\n\nvoid sortStr(int n, string str[]) {\n int i, round, res;\n for(round = 1; round<n; round++)\n for(i = 0; i<n-round; i++) {\n res = str[i].compare(str[i+1]);\n if(res > 0)\n swap(str[i], str[i+1]);//swap strings\n }\n}\n\nmain() {\n string str[N] = {\"Ball\", \"Apple\", \"Data\", \"Area\", \"517\", \"April\", \"Man\", \"506\"};\n cout << \"Strings before sort:\"<< endl;\n display(N, str);\n sortStr(N, str);\n cout << \"Strings after sort:\"<<endl;\n display(N, str);\n}"
},
{
"code": null,
"e": 2587,
"s": 2468,
"text": "Strings before sort:\nBall Apple Data Area 517 April Man 506\nStrings after sort:\n506 517 Apple April Area Ball Data Man"
}
] |
How does free() know the size of memory to be deallocated? - GeeksforGeeks | 28 May, 2017
Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc().
void free(void *ptr);
Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer?
Following is the most common way to store size of memory so that free() knows the size of memory to be deallocated.When memory allocation is done, the actual heap space allocated is one word larger than the requested memory. The extra word is used to store the size of the allocation and is later used by free( )
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
References:http://www.cs.cmu.edu/afs/cs/academic/class/15213-f10/www/lectures/17-allocation-basic.pptxhttp://en.wikipedia.org/wiki/Malloc
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
UDP Server-Client implementation in C
Understanding "extern" keyword in C
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
How to split a string in C/C++, Python and Java? | [
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 24364,
"s": 24232,
"text": "Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc()."
},
{
"code": "void free(void *ptr);",
"e": 24386,
"s": 24364,
"text": null
},
{
"code": null,
"e": 24527,
"s": 24386,
"text": "Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer?"
},
{
"code": null,
"e": 24840,
"s": 24527,
"text": "Following is the most common way to store size of memory so that free() knows the size of memory to be deallocated.When memory allocation is done, the actual heap space allocated is one word larger than the requested memory. The extra word is used to store the size of the allocation and is later used by free( )"
},
{
"code": null,
"e": 24965,
"s": 24840,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25103,
"s": 24965,
"text": "References:http://www.cs.cmu.edu/afs/cs/academic/class/15213-f10/www/lectures/17-allocation-basic.pptxhttp://en.wikipedia.org/wiki/Malloc"
},
{
"code": null,
"e": 25131,
"s": 25103,
"text": "C-Dynamic Memory Allocation"
},
{
"code": null,
"e": 25142,
"s": 25131,
"text": "C Language"
},
{
"code": null,
"e": 25240,
"s": 25142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25278,
"s": 25240,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25298,
"s": 25278,
"text": "Multithreading in C"
},
{
"code": null,
"e": 25324,
"s": 25298,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 25365,
"s": 25324,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 25387,
"s": 25365,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 25425,
"s": 25387,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 25461,
"s": 25425,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 25503,
"s": 25461,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 25531,
"s": 25503,
"text": "Multiple Inheritance in C++"
}
] |
How to click on sign up button using Java in Selenium I am able to open page but not able to click? | We can click on the Sign up button using Java in Selenium. First of all, we have to identify the Sign up button with the help of any of the locators like id, class name, name, link text, xpath, css or partial link text. After identification, we have to click on the Sign up the button with the help of the method click.
WebElement m=driver. findElement(By.id("loc-txt"));
m.click();
Code Implementation with click
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class SignIn{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.linkedin.com/");
// identify element with class name then use click method
WebElement m=driver.
findElement(By.className("sign-in-form__submit-button"));
m.click();
driver.close();
}
}
Also, we can click on the Sign up button with the help of the sendKeys method and pass Keys.ENTER as a parameter to that method.
WebElement m=driver. findElement(By.id("loc-txt"));
m.sendKeys(Keys.ENTER);
Code Implementation with sendKeys
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class SignInSendKeys{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.linkedin.com/");
// identify element with class name then use sendKeys method
WebElement m=driver.
findElement(By.className("sign-in-form__submit-button"));
m.sendKeys(Keys.ENTER);
driver.close();
}
} | [
{
"code": null,
"e": 1382,
"s": 1062,
"text": "We can click on the Sign up button using Java in Selenium. First of all, we have to identify the Sign up button with the help of any of the locators like id, class name, name, link text, xpath, css or partial link text. After identification, we have to click on the Sign up the button with the help of the method click."
},
{
"code": null,
"e": 1445,
"s": 1382,
"text": "WebElement m=driver. findElement(By.id(\"loc-txt\"));\nm.click();"
},
{
"code": null,
"e": 1476,
"s": 1445,
"text": "Code Implementation with click"
},
{
"code": null,
"e": 2257,
"s": 1476,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class SignIn{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.linkedin.com/\");\n // identify element with class name then use click method\n WebElement m=driver.\n findElement(By.className(\"sign-in-form__submit-button\"));\n m.click();\n driver.close();\n }\n}"
},
{
"code": null,
"e": 2386,
"s": 2257,
"text": "Also, we can click on the Sign up button with the help of the sendKeys method and pass Keys.ENTER as a parameter to that method."
},
{
"code": null,
"e": 2462,
"s": 2386,
"text": "WebElement m=driver. findElement(By.id(\"loc-txt\"));\nm.sendKeys(Keys.ENTER);"
},
{
"code": null,
"e": 2496,
"s": 2462,
"text": "Code Implementation with sendKeys"
},
{
"code": null,
"e": 3334,
"s": 2496,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.Keys;\npublic class SignInSendKeys{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.linkedin.com/\");\n // identify element with class name then use sendKeys method\n WebElement m=driver.\n findElement(By.className(\"sign-in-form__submit-button\"));\n m.sendKeys(Keys.ENTER);\n driver.close();\n }\n}"
}
] |
Matplotlib.axes.Axes.bar() in Python | 13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.bar() function in axes module of matplotlib library is used to make a bar plot.
Syntax: Axes.bar(self, x, height, width=0.8, bottom=None, *, align=’center’, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the sequence of horizontal coordinates of the bar.
height: This parameter is the height(s) of the bars.
width: This parameter is an optional parameter. And it is the width(s) of the bars with default value 0.8.
bottom: This parameter is also an optional parameter. And it is the y coordinate(s) of the bars bases with default value 0.
alighn: This parameter is also an optional parameter. And it is used for alignment of the bars to the x coordinates.
Returns: This returns the following:
BarContainer:This returns the container with all the bars and optionally errorbars.
Below examples illustrate the matplotlib.axes.Axes.bar() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np data = ((30, 1000), (10, 28), (100, 30), (500, 800), (50, 10)) dim = len(data[0])w = 0.6dimw = w / dim fig, ax = plt.subplots()x = np.arange(len(data))for i in range(len(data[0])): y = [d[i] for d in data] b = ax.bar(x + i * dimw, y, dimw, bottom = 0.001) ax.set_xticks(x + dimw / 2)ax.set_xticklabels(map(str, x))ax.set_yscale('log') ax.set_xlabel('x')ax.set_ylabel('y') ax.set_title('matplotlib.axes.Axes.bar Example') plt.show()
Output:
Example #2:
# ImpleMinetation of matplotlib function import numpy as npimport matplotlib.pyplot as plt labels = ['Month1', 'Month2', 'Month3', 'Month4']mine = [21, 52, 33, 54]others = [54, 23, 32, 41]Mine_std = [2, 3, 4, 1]Others_std = [3, 5, 2, 3]width = 0.3 fig, ax = plt.subplots() ax.bar(labels, mine, width, yerr = Mine_std, label ='Mine') ax.bar(labels, others, width, yerr = Others_std, bottom = mine, label ='Others') ax.set_ylabel('Articles')ax.legend() ax.set_title('matplotlib.axes.Axes.bar Example') plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 417,
"s": 328,
"text": "The Axes.bar() function in axes module of matplotlib library is used to make a bar plot."
},
{
"code": null,
"e": 515,
"s": 417,
"text": "Syntax: Axes.bar(self, x, height, width=0.8, bottom=None, *, align=’center’, data=None, **kwargs)"
},
{
"code": null,
"e": 597,
"s": 515,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 669,
"s": 597,
"text": "x: This parameter is the sequence of horizontal coordinates of the bar."
},
{
"code": null,
"e": 722,
"s": 669,
"text": "height: This parameter is the height(s) of the bars."
},
{
"code": null,
"e": 829,
"s": 722,
"text": "width: This parameter is an optional parameter. And it is the width(s) of the bars with default value 0.8."
},
{
"code": null,
"e": 953,
"s": 829,
"text": "bottom: This parameter is also an optional parameter. And it is the y coordinate(s) of the bars bases with default value 0."
},
{
"code": null,
"e": 1070,
"s": 953,
"text": "alighn: This parameter is also an optional parameter. And it is used for alignment of the bars to the x coordinates."
},
{
"code": null,
"e": 1107,
"s": 1070,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 1191,
"s": 1107,
"text": "BarContainer:This returns the container with all the bars and optionally errorbars."
},
{
"code": null,
"e": 1277,
"s": 1191,
"text": "Below examples illustrate the matplotlib.axes.Axes.bar() function in matplotlib.axes:"
},
{
"code": null,
"e": 1289,
"s": 1277,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np data = ((30, 1000), (10, 28), (100, 30), (500, 800), (50, 10)) dim = len(data[0])w = 0.6dimw = w / dim fig, ax = plt.subplots()x = np.arange(len(data))for i in range(len(data[0])): y = [d[i] for d in data] b = ax.bar(x + i * dimw, y, dimw, bottom = 0.001) ax.set_xticks(x + dimw / 2)ax.set_xticklabels(map(str, x))ax.set_yscale('log') ax.set_xlabel('x')ax.set_ylabel('y') ax.set_title('matplotlib.axes.Axes.bar Example') plt.show()",
"e": 1870,
"s": 1289,
"text": null
},
{
"code": null,
"e": 1878,
"s": 1870,
"text": "Output:"
},
{
"code": null,
"e": 1890,
"s": 1878,
"text": "Example #2:"
},
{
"code": "# ImpleMinetation of matplotlib function import numpy as npimport matplotlib.pyplot as plt labels = ['Month1', 'Month2', 'Month3', 'Month4']mine = [21, 52, 33, 54]others = [54, 23, 32, 41]Mine_std = [2, 3, 4, 1]Others_std = [3, 5, 2, 3]width = 0.3 fig, ax = plt.subplots() ax.bar(labels, mine, width, yerr = Mine_std, label ='Mine') ax.bar(labels, others, width, yerr = Others_std, bottom = mine, label ='Others') ax.set_ylabel('Articles')ax.legend() ax.set_title('matplotlib.axes.Axes.bar Example') plt.show()",
"e": 2452,
"s": 1890,
"text": null
},
{
"code": null,
"e": 2460,
"s": 2452,
"text": "Output:"
},
{
"code": null,
"e": 2478,
"s": 2460,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2485,
"s": 2478,
"text": "Python"
},
{
"code": null,
"e": 2583,
"s": 2485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2601,
"s": 2583,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2643,
"s": 2601,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2665,
"s": 2643,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2700,
"s": 2665,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2726,
"s": 2700,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2758,
"s": 2726,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2787,
"s": 2758,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2814,
"s": 2787,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2835,
"s": 2814,
"text": "Python OOPs Concepts"
}
] |
How to Convert Epoch Time to Date in SQL? | 17 Dec, 2021
DATEADD() function in SQL Server is used to sum up a time or a date interval to a specified date then returns the modified date. There are some features of DATEADD() below:
This function is used to sum up a time or a date interval to a date specified.
This function comes under Date Functions.
This function accepts three parameters namely interval, number, and date.
This function can also include time in the interval section.
Here we will see, how to convert epoch time to date in SQL Server using the DATEADD() function. For the purpose of demonstration, we will be creating an EpochDB table in a database called “geeks“.
Step 1: Creating the Database
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks:
USE geeks;
Step 3: Table Definition
We have the following EpochDB in our geeks database.
CREATE TABLE EpochDOB (
Id INT,
Person VARCHAR(50),
Dt BIGINT
);
Step 4: Adding data to the table
Use the below statement to add data to the EpochDB table:
INSERT INTO EpochDOB VALUES
(1,'Anuj',848698632000),
(2,'Harsh',957532509000),
(3,'Ravi',1547455833000);
Step 5: To verify the contents of the table use the below statement
SELECT * FROM EpochDOB;
Step 6: Result
Because our Epoch time is specified in milliseconds, we may convert it to seconds. To convert milliseconds to seconds, first, divide the millisecond count by 1000. Later, we use DATEADD() to add the number of seconds since the epoch, which is January 1, 1970 and cast the result to retrieve the date since the epoch.
SELECT *, CAST(DATEADD(SECOND, Dt/1000
,'1970/1/1') AS DATE) DOBDate
FROM EpochDOB;
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "DATEADD() function in SQL Server is used to sum up a time or a date interval to a specified date then returns the modified date. There are some features of DATEADD() below: "
},
{
"code": null,
"e": 281,
"s": 202,
"text": "This function is used to sum up a time or a date interval to a date specified."
},
{
"code": null,
"e": 323,
"s": 281,
"text": "This function comes under Date Functions."
},
{
"code": null,
"e": 397,
"s": 323,
"text": "This function accepts three parameters namely interval, number, and date."
},
{
"code": null,
"e": 459,
"s": 397,
"text": "This function can also include time in the interval section. "
},
{
"code": null,
"e": 656,
"s": 459,
"text": "Here we will see, how to convert epoch time to date in SQL Server using the DATEADD() function. For the purpose of demonstration, we will be creating an EpochDB table in a database called “geeks“."
},
{
"code": null,
"e": 686,
"s": 656,
"text": "Step 1: Creating the Database"
},
{
"code": null,
"e": 749,
"s": 686,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 772,
"s": 749,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 799,
"s": 772,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 868,
"s": 799,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 879,
"s": 868,
"text": "USE geeks;"
},
{
"code": null,
"e": 904,
"s": 879,
"text": "Step 3: Table Definition"
},
{
"code": null,
"e": 957,
"s": 904,
"text": "We have the following EpochDB in our geeks database."
},
{
"code": null,
"e": 1024,
"s": 957,
"text": "CREATE TABLE EpochDOB (\nId INT,\nPerson VARCHAR(50), \nDt BIGINT \n);"
},
{
"code": null,
"e": 1057,
"s": 1024,
"text": "Step 4: Adding data to the table"
},
{
"code": null,
"e": 1115,
"s": 1057,
"text": "Use the below statement to add data to the EpochDB table:"
},
{
"code": null,
"e": 1220,
"s": 1115,
"text": "INSERT INTO EpochDOB VALUES\n(1,'Anuj',848698632000),\n(2,'Harsh',957532509000),\n(3,'Ravi',1547455833000);"
},
{
"code": null,
"e": 1288,
"s": 1220,
"text": "Step 5: To verify the contents of the table use the below statement"
},
{
"code": null,
"e": 1312,
"s": 1288,
"text": "SELECT * FROM EpochDOB;"
},
{
"code": null,
"e": 1327,
"s": 1312,
"text": "Step 6: Result"
},
{
"code": null,
"e": 1644,
"s": 1327,
"text": "Because our Epoch time is specified in milliseconds, we may convert it to seconds. To convert milliseconds to seconds, first, divide the millisecond count by 1000. Later, we use DATEADD() to add the number of seconds since the epoch, which is January 1, 1970 and cast the result to retrieve the date since the epoch."
},
{
"code": null,
"e": 1729,
"s": 1644,
"text": "SELECT *, CAST(DATEADD(SECOND, Dt/1000\n ,'1970/1/1') AS DATE) DOBDate\nFROM EpochDOB;"
},
{
"code": null,
"e": 1736,
"s": 1729,
"text": "Picked"
},
{
"code": null,
"e": 1746,
"s": 1736,
"text": "SQL-Query"
},
{
"code": null,
"e": 1750,
"s": 1746,
"text": "SQL"
},
{
"code": null,
"e": 1754,
"s": 1750,
"text": "SQL"
}
] |
Preferences in ESP32 | Non−volatile storage is an important requirement for embedded systems. Often, we want the chip to remember a couple of things, like setup variables, WiFi credentials, etc. even between power cycles. It would be so inconvenient if we had to perform setup or config every time the device undergoes a power reset. ESP32 has two popular non-volatile storage methods: preferences and SPIFFS. While preferences are generally used for storing key-value pairs, SPIFFS (SPI Flash File System), as the name suggests, is used for storing files and documents. In this chapter, let's focus on preferences.
Preferences are stored in a section of the main flash memory with type as data and subtype as nvs. nvs stands for non−volatile storage. By default, 20 KB of space is reserved for preferences, so don't try to store a lot of bulky data in preferences. Use SPIFFS for bulky data (SPIFFS has 1.5 MB of reserved space by default). What kind of key−value pairs can be stored within preferences? Let's understand through the example code.
We will use the example code provided. Go to File −> Examples −> Preferences −> StartCounter. It can also be found on GitHub.
This code keeps a count of how many times the ESP32 was reset. Therefore, every time it wakes up, it fetches the existing count from preferences, increments it by one, and saves the updated count back to preferences. It then resets the ESP32. You can see using the printed statements on the ESP32 that the value of the count is not lost between resets, that it is indeed non−volatile.
This code is very heavily commented, and therefore, largely, self-explanatory. Nevertheless, let's walk through the code.
We begin by including the Preferences library.
#include <Preferences.h>
Next, we create an object of Class Preferences.
Preferences preferences;
Now let's look at the setup line by line. We begin by initializing Serial.
void setup() {
Serial.begin(115200);
Serial.println();
Next, we open preferences with a namespace. Now, think of the preference storage like a bank locker−room. There are several lockers, and you open one at a time. The namespace is like the name of the locker. Within each locker, there are key−value pairs that you can access. If the locker whose name you mentioned does not exist, then it will be created, and then you can add key−value pairs to that locker. Why are there different lockers? To avoid clashes in the name. Say you have a WiFi library that uses preferences to store credentials and a BlueTooth library that also uses preferences to store credentials. Say both of these are being developed by different developers. What if both use the same key name credentials? This will obviously create a lot of confusion. However, if both of them have their keys in different lockers, there will be no confusion at all.
// Open Preferences with my-app namespace. Each application module, library, etc
// has to use a namespace name to prevent key name collisions. We will open storage in
// RW-mode (second parameter has to be false).
// Note: Namespace name is limited to 15 chars.
preferences.begin("my−app", false);
The second argument false of preferences.begin() indicates that we want to both read from and write to this locker. If it was true, we could only read from the locker, not write to it.
Also, the namespace, as mentioned in the comments, shouldn't be more than 15 characters in length.
Next, the code has a couple of commented statements, which you can make use of depending on the requirement. One enables you to clear the locker, and the other helps you delete a particular key−value
pair from the locker (having the key as "counter")
// Remove all preferences under the opened namespace
//preferences.clear();
// Or remove the counter key only
//preferences.remove("counter");
As a next step, we get the value associated with the key "counter". Now, for the first time when you run this program, there may be no such key existing. Therefore, we also provide a default value of 0 as an argument to the preferences.getUInt() function. What this tells ESP32 is that if the key "counter" doesn't exist, create a new key-value pair, with
key as "counter" and value as 0. Also, note that we are using getUInt because the value is of type unsigned int. Other functions like getFloat, getString, etc.
need to be called depending on the type of the value. The full list of options can be found here.
unsigned int counter = preferences.getUInt("counter", 0);
Next, we increment this count by one and print it on the Serial Monitor.
// Increase counter by 1
counter++;
// Print the counter to Serial Monitor
Serial.printf("Current counter value: %u\n", counter);
We then store this updated value back to non-volatile storage. We are basically updating the value for the key "counter". Next time the ESP32 reads the value of the key "counter",
it will get the incremented value.
// Store the counter to the Preferences
preferences.putUInt("counter", counter);
Finally, we close the preferences locker and restart the ESP32 in 10 seconds.
// Close the Preferences
preferences.end();
// Wait 10 seconds
Serial.println("Restarting in 10 seconds...");
delay(10000);
// Restart ESP
ESP.restart();
}
Because we restart ESP32 before diving into the loop, the loop is never executed. Therefore, it is kept blank
void loop() {}
This example demonstrates quite well how ESP32 preferences storage is indeed non−volatile. When you check the printed statements on the Serial Monitor, you can see the count getting incremented between successive resets. This would not have happened with a local variable. It was only possible by using non−volatile storage through preferences.
ESP32 Preferences Library
ESP32 Preferences Library
ESP32 Non−volatile storage
ESP32 Non−volatile storage | [
{
"code": null,
"e": 2911,
"s": 2317,
"text": "Non−volatile storage is an important requirement for embedded systems. Often, we want the chip to remember a couple of things, like setup variables, WiFi credentials, etc. even between power cycles. It would be so inconvenient if we had to perform setup or config every time the device undergoes a power reset. ESP32 has two popular non-volatile storage methods: preferences and SPIFFS. While preferences are generally used for storing key-value pairs, SPIFFS (SPI Flash File System), as the name suggests, is used for storing files and documents. In this chapter, let's focus on preferences. "
},
{
"code": null,
"e": 3343,
"s": 2911,
"text": "Preferences are stored in a section of the main flash memory with type as data and subtype as nvs. nvs stands for non−volatile storage. By default, 20 KB of space is reserved for preferences, so don't try to store a lot of bulky data in preferences. Use SPIFFS for bulky data (SPIFFS has 1.5 MB of reserved space by default). What kind of key−value pairs can be stored within preferences? Let's understand through the example code."
},
{
"code": null,
"e": 3469,
"s": 3343,
"text": "We will use the example code provided. Go to File −> Examples −> Preferences −> StartCounter. It can also be found on GitHub."
},
{
"code": null,
"e": 3854,
"s": 3469,
"text": "This code keeps a count of how many times the ESP32 was reset. Therefore, every time it wakes up, it fetches the existing count from preferences, increments it by one, and saves the updated count back to preferences. It then resets the ESP32. You can see using the printed statements on the ESP32 that the value of the count is not lost between resets, that it is indeed non−volatile."
},
{
"code": null,
"e": 3977,
"s": 3854,
"text": "This code is very heavily commented, and therefore, largely, self-explanatory. Nevertheless, let's walk through the code. "
},
{
"code": null,
"e": 4024,
"s": 3977,
"text": "We begin by including the Preferences library."
},
{
"code": null,
"e": 4049,
"s": 4024,
"text": "#include <Preferences.h>"
},
{
"code": null,
"e": 4097,
"s": 4049,
"text": "Next, we create an object of Class Preferences."
},
{
"code": null,
"e": 4122,
"s": 4097,
"text": "Preferences preferences;"
},
{
"code": null,
"e": 4197,
"s": 4122,
"text": "Now let's look at the setup line by line. We begin by initializing Serial."
},
{
"code": null,
"e": 4258,
"s": 4197,
"text": "void setup() {\n Serial.begin(115200);\n Serial.println();"
},
{
"code": null,
"e": 5129,
"s": 4258,
"text": "Next, we open preferences with a namespace. Now, think of the preference storage like a bank locker−room. There are several lockers, and you open one at a time. The namespace is like the name of the locker. Within each locker, there are key−value pairs that you can access. If the locker whose name you mentioned does not exist, then it will be created, and then you can add key−value pairs to that locker. Why are there different lockers? To avoid clashes in the name. Say you have a WiFi library that uses preferences to store credentials and a BlueTooth library that also uses preferences to store credentials. Say both of these are being developed by different developers. What if both use the same key name credentials? This will obviously create a lot of confusion. However, if both of them have their keys in different lockers, there will be no confusion at all. "
},
{
"code": null,
"e": 5428,
"s": 5129,
"text": "// Open Preferences with my-app namespace. Each application module, library, etc\n// has to use a namespace name to prevent key name collisions. We will open storage in\n// RW-mode (second parameter has to be false).\n// Note: Namespace name is limited to 15 chars.\npreferences.begin(\"my−app\", false);"
},
{
"code": null,
"e": 5713,
"s": 5428,
"text": "The second argument false of preferences.begin() indicates that we want to both read from and write to this locker. If it was true, we could only read from the locker, not write to it. \nAlso, the namespace, as mentioned in the comments, shouldn't be more than 15 characters in length."
},
{
"code": null,
"e": 5966,
"s": 5713,
"text": "Next, the code has a couple of commented statements, which you can make use of depending on the requirement. One enables you to clear the locker, and the other helps you delete a particular key−value\npair from the locker (having the key as \"counter\") \n"
},
{
"code": null,
"e": 6110,
"s": 5966,
"text": "// Remove all preferences under the opened namespace\n//preferences.clear();\n\n// Or remove the counter key only\n//preferences.remove(\"counter\");"
},
{
"code": null,
"e": 6724,
"s": 6110,
"text": "As a next step, we get the value associated with the key \"counter\". Now, for the first time when you run this program, there may be no such key existing. Therefore, we also provide a default value of 0 as an argument to the preferences.getUInt() function. What this tells ESP32 is that if the key \"counter\" doesn't exist, create a new key-value pair, with\nkey as \"counter\" and value as 0. Also, note that we are using getUInt because the value is of type unsigned int. Other functions like getFloat, getString, etc.\nneed to be called depending on the type of the value. The full list of options can be found here."
},
{
"code": null,
"e": 6782,
"s": 6724,
"text": "unsigned int counter = preferences.getUInt(\"counter\", 0);"
},
{
"code": null,
"e": 6856,
"s": 6782,
"text": "Next, we increment this count by one and print it on the Serial Monitor. "
},
{
"code": null,
"e": 6987,
"s": 6856,
"text": "// Increase counter by 1\ncounter++;\n\n// Print the counter to Serial Monitor\nSerial.printf(\"Current counter value: %u\\n\", counter);"
},
{
"code": null,
"e": 7202,
"s": 6987,
"text": "We then store this updated value back to non-volatile storage. We are basically updating the value for the key \"counter\". Next time the ESP32 reads the value of the key \"counter\",\nit will get the incremented value."
},
{
"code": null,
"e": 7284,
"s": 7202,
"text": "// Store the counter to the Preferences\npreferences.putUInt(\"counter\", counter);\n"
},
{
"code": null,
"e": 7362,
"s": 7284,
"text": "Finally, we close the preferences locker and restart the ESP32 in 10 seconds."
},
{
"code": null,
"e": 7523,
"s": 7362,
"text": "// Close the Preferences\npreferences.end();\n\n// Wait 10 seconds\nSerial.println(\"Restarting in 10 seconds...\");\ndelay(10000);\n \n// Restart ESP\nESP.restart();\n}"
},
{
"code": null,
"e": 7633,
"s": 7523,
"text": "Because we restart ESP32 before diving into the loop, the loop is never executed. Therefore, it is kept blank"
},
{
"code": null,
"e": 7649,
"s": 7633,
"text": "void loop() {}\n"
},
{
"code": null,
"e": 7994,
"s": 7649,
"text": "This example demonstrates quite well how ESP32 preferences storage is indeed non−volatile. When you check the printed statements on the Serial Monitor, you can see the count getting incremented between successive resets. This would not have happened with a local variable. It was only possible by using non−volatile storage through preferences."
},
{
"code": null,
"e": 8020,
"s": 7994,
"text": "ESP32 Preferences Library"
},
{
"code": null,
"e": 8046,
"s": 8020,
"text": "ESP32 Preferences Library"
},
{
"code": null,
"e": 8073,
"s": 8046,
"text": "ESP32 Non−volatile storage"
}
] |
stdev() method in Python statistics module | 16 Jul, 2021
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population.
To calculate standard deviation of an entire population, another function known as pstdev() is used.
Standard Deviation is a measure of spread in Statistics. It is used to quantify the measure of spread, variation of a set of data values. It is very much similar to variance, gives the measure of deviation whereas variance provides the squared value. A low measure of Standard Deviation indicates that the data are less spread out, whereas a high value of Standard Deviation shows that the data in a set are spread apart from their mean average values. A useful property of the standard deviation is that, unlike the variance, it is expressed in the same units as the data.
Standard Deviation is calculated by :
where x1, x2, x3.....xn are observed values in sample data,
is the mean value of observations and
N is the number of sample observations.
Syntax : stdev( [data-set], xbar )Parameters : [data] : An iterable with real valued numbers. xbar (Optional): Takes actual mean of data-set as value.Returnype : Returns the actual standard deviation of the values passed as parameter.Exceptions : StatisticsError is raised for data-set less than 2 values passed as parameter. Impossible/precision-less values when the value provided as xbar doesn’t match actual mean of the data-set.
Code #1 :
Python3
# Python code to demonstrate stdev() function # importing Statistics moduleimport statistics # creating a simple data - setsample = [1, 2, 3, 4, 5] # Prints standard deviation# xbar is set to default value of 1print("Standard Deviation of sample is % s " % (statistics.stdev(sample)))
Output :
Standard Deviation of the sample is 1.5811388300841898
Code #2 : Demonstrate stdev() on a varying set of data types
Python3
# Python code to demonstrate stdev() # function on various range of datasets # importing the statistics modulefrom statistics import stdev # importing fractions as parameter valuesfrom fractions import Fraction as fr # creating a varying range of sample sets# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of floating point valuessample4 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the standard deviation of # following sample sets of observationsprint("The Standard Deviation of Sample1 is % s" %(stdev(sample1))) print("The Standard Deviation of Sample2 is % s" %(stdev(sample2))) print("The Standard Deviation of Sample3 is % s" %(stdev(sample3))) print("The Standard Deviation of Sample4 is % s" %(stdev(sample4)))
Output :
The Standard Deviation of Sample1 is 3.9761191895520196
The Standard Deviation of Sample2 is 1.8708286933869707
The Standard Deviation of Sample3 is 7.8182478855559445
The Standard Deviation of Sample4 is 0.41967844833872525
Code #3 :Demonstrate the difference between results of variance() and stdev()
Python3
# Python code to demonstrate difference# in results of stdev() and variance() # importing Statistics moduleimport statistics # creating a simple data-setsample = [1, 2, 3, 4, 5] # Printing standard deviation# xbar is set to default value of 1print("Standard Deviation of the sample is % s " %(statistics.stdev(sample))) # variance is approximately the# squared result of what stdev isprint("Variance of the sample is % s" %(statistics.variance(sample)))
Output :
Standard Deviation of the sample is 1.5811388300841898
Variance of the sample is 2.5
Code #4 : Demonstrate the use of xbar parameter
Python3
# Python code to demonstrate use of xbar# parameter while using stdev() function # Importing statistics moduleimport statistics # creating a sample listsample = (1, 1.3, 1.2, 1.9, 2.5, 2.2) # calculating the mean of sample setm = statistics.mean(sample) # xbar is nothing but stores# the mean of the sample set # calculating the variance of sample setprint("Standard Deviation of Sample set is % s" %(statistics.stdev(sample, xbar = m)))
Output :
Standard Deviation of Sample set is 0.6047037842337906
Code #5 : Demonstrates StatisticsError
Python3
# Python code to demonstrate StatisticsError # importing the statistics moduleimport statistics # creating a data-set with one elementsample = [1] # will raise StatisticsErrorprint(statistics.stdev(sample))
Output :
Traceback (most recent call last):
File "/home/f921f9269b061f1cc4e5fc74abf6ce10.py", line 12, in
print(statistics.stdev(sample))
File "/usr/lib/python3.5/statistics.py", line 617, in stdev
var = variance(data, xbar)
File "/usr/lib/python3.5/statistics.py", line 555, in variance
raise StatisticsError('variance requires at least two data points')
statistics.StatisticsError: variance requires at least two data points
Applications :
Standard Deviation is highly essential in the field of statistical maths and statistical study. It is commonly used to measure confidence in statistical calculations. For example, the margin of error in calculating marks of an exam is determined by calculating the expected standard deviation in the results if the same exam were to be conducted multiple times.
It is very useful in the field of financial studies as well as it helps to determine the margin of profit and loss. The standard deviation is also important, where the standard deviation on the rate of return on an investment is a measure of the volatility of the investment.
nidhi_biet
anikaseth98
akshaysingh98088
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 286,
"s": 54,
"text": "Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. "
},
{
"code": null,
"e": 388,
"s": 286,
"text": "To calculate standard deviation of an entire population, another function known as pstdev() is used. "
},
{
"code": null,
"e": 963,
"s": 388,
"text": "Standard Deviation is a measure of spread in Statistics. It is used to quantify the measure of spread, variation of a set of data values. It is very much similar to variance, gives the measure of deviation whereas variance provides the squared value. A low measure of Standard Deviation indicates that the data are less spread out, whereas a high value of Standard Deviation shows that the data in a set are spread apart from their mean average values. A useful property of the standard deviation is that, unlike the variance, it is expressed in the same units as the data. "
},
{
"code": null,
"e": 1142,
"s": 963,
"text": "Standard Deviation is calculated by :\n\n\nwhere x1, x2, x3.....xn are observed values in sample data,\n is the mean value of observations and\nN is the number of sample observations."
},
{
"code": null,
"e": 1578,
"s": 1142,
"text": "Syntax : stdev( [data-set], xbar )Parameters : [data] : An iterable with real valued numbers. xbar (Optional): Takes actual mean of data-set as value.Returnype : Returns the actual standard deviation of the values passed as parameter.Exceptions : StatisticsError is raised for data-set less than 2 values passed as parameter. Impossible/precision-less values when the value provided as xbar doesn’t match actual mean of the data-set. "
},
{
"code": null,
"e": 1590,
"s": 1578,
"text": "Code #1 : "
},
{
"code": null,
"e": 1598,
"s": 1590,
"text": "Python3"
},
{
"code": "# Python code to demonstrate stdev() function # importing Statistics moduleimport statistics # creating a simple data - setsample = [1, 2, 3, 4, 5] # Prints standard deviation# xbar is set to default value of 1print(\"Standard Deviation of sample is % s \" % (statistics.stdev(sample)))",
"e": 1898,
"s": 1598,
"text": null
},
{
"code": null,
"e": 1908,
"s": 1898,
"text": "Output : "
},
{
"code": null,
"e": 1964,
"s": 1908,
"text": "Standard Deviation of the sample is 1.5811388300841898 "
},
{
"code": null,
"e": 2027,
"s": 1964,
"text": "Code #2 : Demonstrate stdev() on a varying set of data types "
},
{
"code": null,
"e": 2035,
"s": 2027,
"text": "Python3"
},
{
"code": "# Python code to demonstrate stdev() # function on various range of datasets # importing the statistics modulefrom statistics import stdev # importing fractions as parameter valuesfrom fractions import Fraction as fr # creating a varying range of sample sets# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of floating point valuessample4 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the standard deviation of # following sample sets of observationsprint(\"The Standard Deviation of Sample1 is % s\" %(stdev(sample1))) print(\"The Standard Deviation of Sample2 is % s\" %(stdev(sample2))) print(\"The Standard Deviation of Sample3 is % s\" %(stdev(sample3))) print(\"The Standard Deviation of Sample4 is % s\" %(stdev(sample4)))",
"e": 3234,
"s": 2035,
"text": null
},
{
"code": null,
"e": 3244,
"s": 3234,
"text": "Output : "
},
{
"code": null,
"e": 3469,
"s": 3244,
"text": "The Standard Deviation of Sample1 is 3.9761191895520196\nThe Standard Deviation of Sample2 is 1.8708286933869707\nThe Standard Deviation of Sample3 is 7.8182478855559445\nThe Standard Deviation of Sample4 is 0.41967844833872525"
},
{
"code": null,
"e": 3549,
"s": 3469,
"text": "Code #3 :Demonstrate the difference between results of variance() and stdev() "
},
{
"code": null,
"e": 3557,
"s": 3549,
"text": "Python3"
},
{
"code": "# Python code to demonstrate difference# in results of stdev() and variance() # importing Statistics moduleimport statistics # creating a simple data-setsample = [1, 2, 3, 4, 5] # Printing standard deviation# xbar is set to default value of 1print(\"Standard Deviation of the sample is % s \" %(statistics.stdev(sample))) # variance is approximately the# squared result of what stdev isprint(\"Variance of the sample is % s\" %(statistics.variance(sample)))",
"e": 4034,
"s": 3557,
"text": null
},
{
"code": null,
"e": 4044,
"s": 4034,
"text": "Output : "
},
{
"code": null,
"e": 4130,
"s": 4044,
"text": "Standard Deviation of the sample is 1.5811388300841898 \nVariance of the sample is 2.5"
},
{
"code": null,
"e": 4180,
"s": 4130,
"text": "Code #4 : Demonstrate the use of xbar parameter "
},
{
"code": null,
"e": 4188,
"s": 4180,
"text": "Python3"
},
{
"code": "# Python code to demonstrate use of xbar# parameter while using stdev() function # Importing statistics moduleimport statistics # creating a sample listsample = (1, 1.3, 1.2, 1.9, 2.5, 2.2) # calculating the mean of sample setm = statistics.mean(sample) # xbar is nothing but stores# the mean of the sample set # calculating the variance of sample setprint(\"Standard Deviation of Sample set is % s\" %(statistics.stdev(sample, xbar = m)))",
"e": 4634,
"s": 4188,
"text": null
},
{
"code": null,
"e": 4644,
"s": 4634,
"text": "Output : "
},
{
"code": null,
"e": 4699,
"s": 4644,
"text": "Standard Deviation of Sample set is 0.6047037842337906"
},
{
"code": null,
"e": 4740,
"s": 4699,
"text": "Code #5 : Demonstrates StatisticsError "
},
{
"code": null,
"e": 4748,
"s": 4740,
"text": "Python3"
},
{
"code": "# Python code to demonstrate StatisticsError # importing the statistics moduleimport statistics # creating a data-set with one elementsample = [1] # will raise StatisticsErrorprint(statistics.stdev(sample))",
"e": 4955,
"s": 4748,
"text": null
},
{
"code": null,
"e": 4965,
"s": 4955,
"text": "Output : "
},
{
"code": null,
"e": 5402,
"s": 4965,
"text": "Traceback (most recent call last):\n File \"/home/f921f9269b061f1cc4e5fc74abf6ce10.py\", line 12, in \n print(statistics.stdev(sample))\n File \"/usr/lib/python3.5/statistics.py\", line 617, in stdev\n var = variance(data, xbar)\n File \"/usr/lib/python3.5/statistics.py\", line 555, in variance\n raise StatisticsError('variance requires at least two data points')\nstatistics.StatisticsError: variance requires at least two data points"
},
{
"code": null,
"e": 5419,
"s": 5402,
"text": "Applications : "
},
{
"code": null,
"e": 5781,
"s": 5419,
"text": "Standard Deviation is highly essential in the field of statistical maths and statistical study. It is commonly used to measure confidence in statistical calculations. For example, the margin of error in calculating marks of an exam is determined by calculating the expected standard deviation in the results if the same exam were to be conducted multiple times."
},
{
"code": null,
"e": 6057,
"s": 5781,
"text": "It is very useful in the field of financial studies as well as it helps to determine the margin of profit and loss. The standard deviation is also important, where the standard deviation on the rate of return on an investment is a measure of the volatility of the investment."
},
{
"code": null,
"e": 6068,
"s": 6057,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6080,
"s": 6068,
"text": "anikaseth98"
},
{
"code": null,
"e": 6097,
"s": 6080,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 6123,
"s": 6097,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 6130,
"s": 6123,
"text": "Python"
},
{
"code": null,
"e": 6228,
"s": 6130,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6246,
"s": 6228,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6288,
"s": 6246,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6310,
"s": 6288,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6345,
"s": 6310,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 6371,
"s": 6345,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6403,
"s": 6371,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6432,
"s": 6403,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 6459,
"s": 6432,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6480,
"s": 6459,
"text": "Python OOPs Concepts"
}
] |
Property binding in angular 8 | 11 Sep, 2020
Property Binding is a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code. Actually, Angular internally converts string interpolation into property binding.
In this, we bind the property of a defined element to an HTML DOM element.
Syntax:
<element [property]= 'typescript_property'>
Approach:
Define a property element in the app.component.ts file.
In the app.component.html file, set the property of the HTML element by assigning the property value to the app.component.ts file’s element.
Example 1: setting value of an input element using property binding.
app.component.html
<input style = "color:green; margin-top: 40px; margin-left: 100px;" [value]='title'>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'GeeksforGeeks'; }
Output:
Example 2: getting source of the image using property binding.
app.component.html
<img [src]='src'>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { src = 'https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png'; }
Output:
Example 3: disabling a button using property binding.
app.component.html
<button [disabled]='bool' style="margin-top: 20px;">GeekyButton</button>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { bool = 'true'; }
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Sep, 2020"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "Property Binding is a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code. Actually, Angular internally converts string interpolation into property binding."
},
{
"code": null,
"e": 369,
"s": 294,
"text": "In this, we bind the property of a defined element to an HTML DOM element."
},
{
"code": null,
"e": 377,
"s": 369,
"text": "Syntax:"
},
{
"code": null,
"e": 421,
"s": 377,
"text": "<element [property]= 'typescript_property'>"
},
{
"code": null,
"e": 431,
"s": 421,
"text": "Approach:"
},
{
"code": null,
"e": 487,
"s": 431,
"text": "Define a property element in the app.component.ts file."
},
{
"code": null,
"e": 628,
"s": 487,
"text": "In the app.component.html file, set the property of the HTML element by assigning the property value to the app.component.ts file’s element."
},
{
"code": null,
"e": 697,
"s": 628,
"text": "Example 1: setting value of an input element using property binding."
},
{
"code": null,
"e": 716,
"s": 697,
"text": "app.component.html"
},
{
"code": "<input style = \"color:green; margin-top: 40px; margin-left: 100px;\" [value]='title'>",
"e": 832,
"s": 716,
"text": null
},
{
"code": null,
"e": 849,
"s": 832,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'GeeksforGeeks'; }",
"e": 1085,
"s": 849,
"text": null
},
{
"code": null,
"e": 1093,
"s": 1085,
"text": "Output:"
},
{
"code": null,
"e": 1156,
"s": 1093,
"text": "Example 2: getting source of the image using property binding."
},
{
"code": null,
"e": 1175,
"s": 1156,
"text": "app.component.html"
},
{
"code": "<img [src]='src'>",
"e": 1193,
"s": 1175,
"text": null
},
{
"code": null,
"e": 1210,
"s": 1193,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { src = 'https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png'; }",
"e": 1497,
"s": 1210,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Output:"
},
{
"code": null,
"e": 1559,
"s": 1505,
"text": "Example 3: disabling a button using property binding."
},
{
"code": null,
"e": 1578,
"s": 1559,
"text": "app.component.html"
},
{
"code": "<button [disabled]='bool' style=\"margin-top: 20px;\">GeekyButton</button>",
"e": 1651,
"s": 1578,
"text": null
},
{
"code": null,
"e": 1668,
"s": 1651,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { bool = 'true'; }",
"e": 1894,
"s": 1668,
"text": null
},
{
"code": null,
"e": 1902,
"s": 1894,
"text": "Output:"
},
{
"code": null,
"e": 1917,
"s": 1902,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 1924,
"s": 1917,
"text": "Picked"
},
{
"code": null,
"e": 1934,
"s": 1924,
"text": "AngularJS"
},
{
"code": null,
"e": 1951,
"s": 1934,
"text": "Web Technologies"
}
] |
Head command in Linux with examples | 22 Feb, 2022
It is the complementary of Tail command. The head command, as the name implies, print the top N number of data of the given input. By default, it prints the first 10 lines of the specified files. If more than one file name is provided then data from each file is preceded by its file name.
Syntax:
head [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Without any option, it displays only the first 10 lines of the file specified. Example:
$ head state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Options
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
1. -n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory to be specified in command otherwise it displays an error.
$ head -n 5 state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
2. -c num: Prints the first ‘num’ bytes from the file specified. Newline count as a single character, so if head prints out a newline, it will count it as a byte. num is mandatory to be specified in command otherwise displays an error.
$ head -c 6 state.txt
Andhra
3. -q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name.
Without using -q option
$ head state.txt capital.txt
==> state.txt <==
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
==> capital.txt <==
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
With using -q option
$ head -q state.txt capital.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
4. -v: By using this option, data from the specified file is always preceded by its file name.
$ head -v state.txt
==> state.txt <==
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Applications of head Command
Print line between M and N lines(M>N): For this purpose, we use the head, tail, and pipeline(|) commands. The command is: head -M file_name | tail +N since the head command takes first M lines and from M lines tail command cuts lines starting from +N till the end, we can also use head -M file_name | tail +(M-N+1) command since the head command takes first M lines and from M lines tail command cuts (M-N+1) lines starting from the end. Let say from the state.txt file we have to print lines between 10 and 20.
Print line between M and N lines(M>N): For this purpose, we use the head, tail, and pipeline(|) commands. The command is: head -M file_name | tail +N since the head command takes first M lines and from M lines tail command cuts lines starting from +N till the end, we can also use head -M file_name | tail +(M-N+1) command since the head command takes first M lines and from M lines tail command cuts (M-N+1) lines starting from the end. Let say from the state.txt file we have to print lines between 10 and 20.
$ head -n 20 state.txt | tail -10
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
How to use the head with pipeline(|): The head command can be piped with other commands. In the following example, the output of the ls command is piped to head to show only the three most recently modified files or folders.
How to use the head with pipeline(|): The head command can be piped with other commands. In the following example, the output of the ls command is piped to head to show only the three most recently modified files or folders.
Display all recently modified or recently used files.
$ ls -t
e.txt
d.txt
c.txt
b.txt
a.txt
Cut three most recently used file.
$ ls -t | head -n 3
e.txt
d.txt
c.txt
It can also be piped with one or more filters for additional processing. For example, the sort filter could be used to sort the three most recently used files or folders in the alphabetic order.
It can also be piped with one or more filters for additional processing. For example, the sort filter could be used to sort the three most recently used files or folders in the alphabetic order.
$ ls -t | head -n 3 | sort
c.txt
d.txt
e.txt
There are number of other filters or commands along which we use head command. Mainly, it can be used for viewing huge log files in Unix.
There are number of other filters or commands along which we use head command. Mainly, it can be used for viewing huge log files in Unix.
Linux Tutorials | head command | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | head command | GeeksforGeeksWatch laterShareCopy link21/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ZZACz-filWU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
SampathraoVoni
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
chown command in Linux with Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 343,
"s": 52,
"text": "It is the complementary of Tail command. The head command, as the name implies, print the top N number of data of the given input. By default, it prints the first 10 lines of the specified files. If more than one file name is provided then data from each file is preceded by its file name. "
},
{
"code": null,
"e": 353,
"s": 343,
"text": "Syntax: "
},
{
"code": null,
"e": 380,
"s": 353,
"text": "head [OPTION]... [FILE]..."
},
{
"code": null,
"e": 517,
"s": 380,
"text": "Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states and capitals respectively. "
},
{
"code": null,
"e": 833,
"s": 517,
"text": "$ cat state.txt\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh\nGoa\nGujarat\nHaryana\nHimachal Pradesh\nJammu and Kashmir\nJharkhand\nKarnataka\nKerala\nMadhya Pradesh\nMaharashtra\nManipur\nMeghalaya\nMizoram\nNagaland\nOdisha\nPunjab\nRajasthan\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal"
},
{
"code": null,
"e": 937,
"s": 833,
"text": "$ cat capital.txt\nHyderabad\nItanagar\nDispur\nPatna\nRaipur\nPanaji\nGandhinagar\nChandigarh\nShimla\nSrinagar\n"
},
{
"code": null,
"e": 1027,
"s": 937,
"text": "Without any option, it displays only the first 10 lines of the file specified. Example: "
},
{
"code": null,
"e": 1157,
"s": 1027,
"text": "$ head state.txt\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh\nGoa\nGujarat\nHaryana\nHimachal Pradesh\nJammu and Kashmir"
},
{
"code": null,
"e": 1166,
"s": 1157,
"text": "Options "
},
{
"code": null,
"e": 1175,
"s": 1166,
"text": "Chapters"
},
{
"code": null,
"e": 1202,
"s": 1175,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1252,
"s": 1202,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1275,
"s": 1252,
"text": "captions off, selected"
},
{
"code": null,
"e": 1283,
"s": 1275,
"text": "English"
},
{
"code": null,
"e": 1307,
"s": 1283,
"text": "This is a modal window."
},
{
"code": null,
"e": 1376,
"s": 1307,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1398,
"s": 1376,
"text": "End of dialog window."
},
{
"code": null,
"e": 1545,
"s": 1400,
"text": "1. -n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory to be specified in command otherwise it displays an error. "
},
{
"code": null,
"e": 1625,
"s": 1545,
"text": "$ head -n 5 state.txt\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh"
},
{
"code": null,
"e": 1863,
"s": 1625,
"text": "2. -c num: Prints the first ‘num’ bytes from the file specified. Newline count as a single character, so if head prints out a newline, it will count it as a byte. num is mandatory to be specified in command otherwise displays an error. "
},
{
"code": null,
"e": 1892,
"s": 1863,
"text": "$ head -c 6 state.txt\nAndhra"
},
{
"code": null,
"e": 2021,
"s": 1892,
"text": "3. -q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name. "
},
{
"code": null,
"e": 2565,
"s": 2021,
"text": "Without using -q option\n$ head state.txt capital.txt\n==> state.txt <==\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh\nGoa\nGujarat\nHaryana\nHimachal Pradesh\nJammu and Kashmir\n\n==> capital.txt <==\nHyderabad\nItanagar\nDispur\nPatna\nRaipur\nPanaji\nGandhinagar\nChandigarh\nShimla\nSrinagar\n\n\nWith using -q option\n$ head -q state.txt capital.txt\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh\nGoa\nGujarat\nHaryana\nHimachal Pradesh\nJammu and Kashmir\nHyderabad\nItanagar\nDispur\nPatna\nRaipur\nPanaji\nGandhinagar\nChandigarh\nShimla\nSrinagar"
},
{
"code": null,
"e": 2662,
"s": 2565,
"text": "4. -v: By using this option, data from the specified file is always preceded by its file name. "
},
{
"code": null,
"e": 2813,
"s": 2662,
"text": "$ head -v state.txt\n==> state.txt <==\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh\nGoa\nGujarat\nHaryana\nHimachal Pradesh\nJammu and Kashmir"
},
{
"code": null,
"e": 2844,
"s": 2815,
"text": "Applications of head Command"
},
{
"code": null,
"e": 3360,
"s": 2846,
"text": "Print line between M and N lines(M>N): For this purpose, we use the head, tail, and pipeline(|) commands. The command is: head -M file_name | tail +N since the head command takes first M lines and from M lines tail command cuts lines starting from +N till the end, we can also use head -M file_name | tail +(M-N+1) command since the head command takes first M lines and from M lines tail command cuts (M-N+1) lines starting from the end. Let say from the state.txt file we have to print lines between 10 and 20. "
},
{
"code": null,
"e": 3874,
"s": 3360,
"text": "Print line between M and N lines(M>N): For this purpose, we use the head, tail, and pipeline(|) commands. The command is: head -M file_name | tail +N since the head command takes first M lines and from M lines tail command cuts lines starting from +N till the end, we can also use head -M file_name | tail +(M-N+1) command since the head command takes first M lines and from M lines tail command cuts (M-N+1) lines starting from the end. Let say from the state.txt file we have to print lines between 10 and 20. "
},
{
"code": null,
"e": 4004,
"s": 3874,
"text": "$ head -n 20 state.txt | tail -10\nJharkhand\nKarnataka\nKerala\nMadhya Pradesh\nMaharashtra\nManipur\nMeghalaya\nMizoram\nNagaland\nOdisha"
},
{
"code": null,
"e": 4231,
"s": 4004,
"text": "How to use the head with pipeline(|): The head command can be piped with other commands. In the following example, the output of the ls command is piped to head to show only the three most recently modified files or folders. "
},
{
"code": null,
"e": 4458,
"s": 4231,
"text": "How to use the head with pipeline(|): The head command can be piped with other commands. In the following example, the output of the ls command is piped to head to show only the three most recently modified files or folders. "
},
{
"code": null,
"e": 4627,
"s": 4458,
"text": "Display all recently modified or recently used files.\n$ ls -t\ne.txt \nd.txt\nc.txt\nb.txt \na.txt\n\nCut three most recently used file.\n$ ls -t | head -n 3\ne.txt\nd.txt\nc.txt"
},
{
"code": null,
"e": 4824,
"s": 4627,
"text": "It can also be piped with one or more filters for additional processing. For example, the sort filter could be used to sort the three most recently used files or folders in the alphabetic order. "
},
{
"code": null,
"e": 5021,
"s": 4824,
"text": "It can also be piped with one or more filters for additional processing. For example, the sort filter could be used to sort the three most recently used files or folders in the alphabetic order. "
},
{
"code": null,
"e": 5066,
"s": 5021,
"text": "$ ls -t | head -n 3 | sort\nc.txt\nd.txt\ne.txt"
},
{
"code": null,
"e": 5204,
"s": 5066,
"text": "There are number of other filters or commands along which we use head command. Mainly, it can be used for viewing huge log files in Unix."
},
{
"code": null,
"e": 5342,
"s": 5204,
"text": "There are number of other filters or commands along which we use head command. Mainly, it can be used for viewing huge log files in Unix."
},
{
"code": null,
"e": 6225,
"s": 5342,
"text": "Linux Tutorials | head command | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | head command | GeeksforGeeksWatch laterShareCopy link21/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:13•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ZZACz-filWU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 6521,
"s": 6225,
"text": "This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 6647,
"s": 6521,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6660,
"s": 6647,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6675,
"s": 6660,
"text": "SampathraoVoni"
},
{
"code": null,
"e": 6689,
"s": 6675,
"text": "linux-command"
},
{
"code": null,
"e": 6720,
"s": 6689,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 6731,
"s": 6720,
"text": "Linux-Unix"
},
{
"code": null,
"e": 6829,
"s": 6731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6864,
"s": 6829,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 6900,
"s": 6864,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 6938,
"s": 6900,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 6964,
"s": 6938,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 6999,
"s": 6964,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 7037,
"s": 6999,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7072,
"s": 7037,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 7108,
"s": 7072,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 7145,
"s": 7108,
"text": "touch command in Linux with Examples"
}
] |
Python | Pandas dataframe.skew() | 19 Feb, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.skew() function return unbiased skew over requested axis Normalized by N-1. Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean. For more information on skewness, refer this link.
Pandas: DataFrame.skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Return : skew : Series or DataFrame (if level specified)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
For link to the CSV file used in the code, click here
Example #1: Use skew() function to find the skewness in data over the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf
Let’s use the dataframe.skew() function to find skewness
# skewness along the index axisdf.skew(axis = 0, skipna = True)
Output : Example #2: Use skew() function to find the skewness of the data over the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # skip the na values# find skewness in each rowdf.skew(axis = 1, skipna = True)
Output :Python | Pandas dataframe.skew() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.skew() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=wbDxmlpV3t0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 266,
"s": 52,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 530,
"s": 266,
"text": "Pandas dataframe.skew() function return unbiased skew over requested axis Normalized by N-1. Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean. For more information on skewness, refer this link."
},
{
"code": null,
"e": 618,
"s": 530,
"text": "Pandas: DataFrame.skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 981,
"s": 618,
"text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series."
},
{
"code": null,
"e": 1038,
"s": 981,
"text": "Return : skew : Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 1047,
"s": 1038,
"text": "Chapters"
},
{
"code": null,
"e": 1074,
"s": 1047,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1124,
"s": 1074,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1147,
"s": 1124,
"text": "captions off, selected"
},
{
"code": null,
"e": 1155,
"s": 1147,
"text": "English"
},
{
"code": null,
"e": 1179,
"s": 1155,
"text": "This is a modal window."
},
{
"code": null,
"e": 1248,
"s": 1179,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1270,
"s": 1248,
"text": "End of dialog window."
},
{
"code": null,
"e": 1324,
"s": 1270,
"text": "For link to the CSV file used in the code, click here"
},
{
"code": null,
"e": 1406,
"s": 1324,
"text": "Example #1: Use skew() function to find the skewness in data over the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf",
"e": 1529,
"s": 1406,
"text": null
},
{
"code": null,
"e": 1586,
"s": 1529,
"text": "Let’s use the dataframe.skew() function to find skewness"
},
{
"code": "# skewness along the index axisdf.skew(axis = 0, skipna = True)",
"e": 1650,
"s": 1586,
"text": null
},
{
"code": null,
"e": 1746,
"s": 1650,
"text": "Output : Example #2: Use skew() function to find the skewness of the data over the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # skip the na values# find skewness in each rowdf.skew(axis = 1, skipna = True)",
"e": 1925,
"s": 1746,
"text": null
},
{
"code": null,
"e": 2815,
"s": 1925,
"text": "Output :Python | Pandas dataframe.skew() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.skew() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=wbDxmlpV3t0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 2839,
"s": 2815,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2871,
"s": 2839,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2885,
"s": 2871,
"text": "Python-pandas"
},
{
"code": null,
"e": 2892,
"s": 2885,
"text": "Python"
},
{
"code": null,
"e": 2990,
"s": 2892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3008,
"s": 2990,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3050,
"s": 3008,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3072,
"s": 3050,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3104,
"s": 3072,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3133,
"s": 3104,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3160,
"s": 3133,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3196,
"s": 3160,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3227,
"s": 3196,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3264,
"s": 3227,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Python Program for QuickSort | In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using the concept of quicksort
Here we first partition the array and sort the separate partition to get the sorted array.
Now let’s observe the solution in the implementation below −
Live Demo
# divide function
def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high] # pivot element
for j in range(low , high):
# If current element is smaller
if arr[j] <= pivot:
# increment
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
# sort
def quickSort(arr,low,high):
if low < high:
# index
pi = partition(arr,low,high)
# sort the partitions
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
# main
arr = [2,5,3,8,6,5,4,7]
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
print (arr[i],end=" ")
Sorted array is
2 3 4 5 5 6 7 8
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for QuickSort | [
{
"code": null,
"e": 1275,
"s": 1187,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1368,
"s": 1275,
"text": "Problem statement − We are given an array, we need to sort it using the concept of quicksort"
},
{
"code": null,
"e": 1459,
"s": 1368,
"text": "Here we first partition the array and sort the separate partition to get the sorted array."
},
{
"code": null,
"e": 1520,
"s": 1459,
"text": "Now let’s observe the solution in the implementation below −"
},
{
"code": null,
"e": 1531,
"s": 1520,
"text": " Live Demo"
},
{
"code": null,
"e": 2198,
"s": 1531,
"text": "# divide function\ndef partition(arr,low,high):\n i = ( low-1 )\n pivot = arr[high] # pivot element\n for j in range(low , high):\n # If current element is smaller\n if arr[j] <= pivot:\n # increment\n i = i+1\n arr[i],arr[j] = arr[j],arr[i]\n arr[i+1],arr[high] = arr[high],arr[i+1]\n return ( i+1 )\n# sort\ndef quickSort(arr,low,high):\n if low < high:\n # index\n pi = partition(arr,low,high)\n # sort the partitions\n quickSort(arr, low, pi-1)\n quickSort(arr, pi+1, high)\n# main\narr = [2,5,3,8,6,5,4,7]\nn = len(arr)\nquickSort(arr,0,n-1)\nprint (\"Sorted array is:\")\nfor i in range(n):\n print (arr[i],end=\" \")"
},
{
"code": null,
"e": 2230,
"s": 2198,
"text": "Sorted array is\n2 3 4 5 5 6 7 8"
},
{
"code": null,
"e": 2331,
"s": 2230,
"text": "All the variables are declared in the local scope and their references are seen in the figure above."
},
{
"code": null,
"e": 2417,
"s": 2331,
"text": "In this article, we have learned about how we can make a Python Program for QuickSort"
}
] |
Android Listview in Java with Example | 18 Feb, 2021
A ListView is a type of AdapterView that displays a vertical list of scroll-able views and each view is placed one below the other. Using adapter, items are inserted into the list from an array or database. For displaying the items in the list method setAdaptor() is used. setAdaptor() method conjoins an adapter with the list.
Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list.
The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result. So, it is the main source to pull data from strings.xml file which contains all the required strings in Java or XML files.
Now let’s understand how to use a listview in an android application with an example. In the example, let’s create an android application that will display a list of tutorials available in GeeksforGeeks portal.
Step 1: Create a new project
Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Java.Select the minimum SDK as per your need.
Click on File, then New => New Project.
Choose “Empty Activity” for the project template.
Select language as Java.
Select the minimum SDK as per your need.
Step 2: Modify activity_main.xml fileAdd a ListView in the activity_main.xml file.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent"/></LinearLayout>
Step 3: Modify MainActivity.java fileIn this section, let’s design the backend of the application. Go to MainActivity.java. Now in the java file create a string array and store the values you want to display in the list. Also, create an object of ListView class. In onCreate() method find Listview by id using findViewById() method. Create an object of ArrayAdapter using a new keyword followed by a constructor call. The ArrayAdaptor public constructor description is below:
public ArrayAdapter (Context context, int Resource, T[ ] objects)
Description
According to this pass the argument in ArrayAdapter Constructor and create an object. At last, conjoin the adapter with the list using setAdapter() method.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView; public class MainActivity extends AppCompatActivity { ListView l; String tutorials[] = { "Algorithms", "Data Structures", "Languages", "Interview Corner", "GATE", "ISRO CS", "UGC NET CS", "CS Subjects", "Web Technologies" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); l = findViewById(R.id.list); ArrayAdapter<String> arr; arr = new ArrayAdapter<String>( this, R.layout.support_simple_spinner_dropdown_item, tutorials); l.setAdapter(arr); }}
Output
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 380,
"s": 52,
"text": "A ListView is a type of AdapterView that displays a vertical list of scroll-able views and each view is placed one below the other. Using adapter, items are inserted into the list from an array or database. For displaying the items in the list method setAdaptor() is used. setAdaptor() method conjoins an adapter with the list."
},
{
"code": null,
"e": 547,
"s": 380,
"text": "Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list."
},
{
"code": null,
"e": 816,
"s": 547,
"text": "The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result. So, it is the main source to pull data from strings.xml file which contains all the required strings in Java or XML files."
},
{
"code": null,
"e": 1027,
"s": 816,
"text": "Now let’s understand how to use a listview in an android application with an example. In the example, let’s create an android application that will display a list of tutorials available in GeeksforGeeks portal."
},
{
"code": null,
"e": 1056,
"s": 1027,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 1209,
"s": 1056,
"text": "Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Java.Select the minimum SDK as per your need."
},
{
"code": null,
"e": 1249,
"s": 1209,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 1299,
"s": 1249,
"text": "Choose “Empty Activity” for the project template."
},
{
"code": null,
"e": 1324,
"s": 1299,
"text": "Select language as Java."
},
{
"code": null,
"e": 1365,
"s": 1324,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 1448,
"s": 1365,
"text": "Step 2: Modify activity_main.xml fileAdd a ListView in the activity_main.xml file."
},
{
"code": null,
"e": 1466,
"s": 1448,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ListView android:id=\"@+id/list\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/></LinearLayout>",
"e": 1948,
"s": 1466,
"text": null
},
{
"code": null,
"e": 2424,
"s": 1948,
"text": "Step 3: Modify MainActivity.java fileIn this section, let’s design the backend of the application. Go to MainActivity.java. Now in the java file create a string array and store the values you want to display in the list. Also, create an object of ListView class. In onCreate() method find Listview by id using findViewById() method. Create an object of ArrayAdapter using a new keyword followed by a constructor call. The ArrayAdaptor public constructor description is below:"
},
{
"code": null,
"e": 2490,
"s": 2424,
"text": "public ArrayAdapter (Context context, int Resource, T[ ] objects)"
},
{
"code": null,
"e": 2502,
"s": 2490,
"text": "Description"
},
{
"code": null,
"e": 2658,
"s": 2502,
"text": "According to this pass the argument in ArrayAdapter Constructor and create an object. At last, conjoin the adapter with the list using setAdapter() method."
},
{
"code": null,
"e": 2676,
"s": 2658,
"text": "MainActivity.java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView; public class MainActivity extends AppCompatActivity { ListView l; String tutorials[] = { \"Algorithms\", \"Data Structures\", \"Languages\", \"Interview Corner\", \"GATE\", \"ISRO CS\", \"UGC NET CS\", \"CS Subjects\", \"Web Technologies\" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); l = findViewById(R.id.list); ArrayAdapter<String> arr; arr = new ArrayAdapter<String>( this, R.layout.support_simple_spinner_dropdown_item, tutorials); l.setAdapter(arr); }}",
"e": 3560,
"s": 2676,
"text": null
},
{
"code": null,
"e": 3567,
"s": 3560,
"text": "Output"
},
{
"code": null,
"e": 3575,
"s": 3567,
"text": "android"
},
{
"code": null,
"e": 3588,
"s": 3575,
"text": "Android-View"
},
{
"code": null,
"e": 3596,
"s": 3588,
"text": "Android"
},
{
"code": null,
"e": 3601,
"s": 3596,
"text": "Java"
},
{
"code": null,
"e": 3606,
"s": 3601,
"text": "Java"
},
{
"code": null,
"e": 3614,
"s": 3606,
"text": "Android"
},
{
"code": null,
"e": 3712,
"s": 3614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3781,
"s": 3712,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 3812,
"s": 3781,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 3855,
"s": 3812,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 3887,
"s": 3855,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 3926,
"s": 3887,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 3941,
"s": 3926,
"text": "Arrays in Java"
},
{
"code": null,
"e": 3977,
"s": 3941,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 4021,
"s": 3977,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 4046,
"s": 4021,
"text": "Reverse a string in Java"
}
] |
What is the Need of Inheritance in Java? | 17 Mar, 2021
Inheritance, as we have all heard is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is the need for Inheritance? Why is it so an important concept
Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e. data members) and behavior (i.e. member functions or methods) of a parent object.
The basic idea of Inheritance is to create the new class (called child class or derived or subclass) from an existing class (called parent class or Base or Superclass). That is, the child class inherits the properties (methods and fields) of the parent class.
Thinking to achieve something without Inheritance will be the misuse of time and resources as we have to write the same code again and again.
Let us take an example, three classes Person, Employee and Student have some attributes, some common and some different. See the code below.
Java
// Java program without inheritanceimport java.io.*;import java.math.BigDecimal; // class personclass Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return String.format( "Person :- name : %s , age : %d", name, age); }} //class studentclass Student { private String name; private int age; private int rollno; private String school; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String toString() { return String.format( "Student :- name : %s , age : %d , roll : %d , school : %s", name, age, rollno, school); }} //class Employeeclass Employee { private String name; private int age; private double salary; private String organisation; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getOrganisation() { return organisation; } public void setOrganisation(String organisation) { this.organisation = organisation; } public String toString() { return String.format( "Employee :- name : %s , age : %d , organisation : %s , salary : %f", name, age, organisation, salary); }} // class PersonRunnerpublic class PersonRunner { public static void main(String[] args) { Person person = new Person(); Student student = new Student(); Employee employee = new Employee(); person.setName("Saurabh"); person.setAge(20); student.setName("Prateek"); student.setAge(21); student.setRollno(101); student.setSchool("New Era HS"); employee.setName("Sushant"); employee.setAge(25); employee.setOrganisation("GeeksforGeeks"); employee.setSalary(50000.00); System.out.println(person); System.out.println(student); System.out.println(employee); }}
Person :- name : Saurabh , age : 20
Student :- name : Prateek , age : 21 , roll : 101 , school : New Era HS
Employee :- name : Sushant , age : 25 , organisation : GeeksforGeeks , salary : 50000.000000
Note that we have to write the same code which is already written in Person class again in Student and in Employee class. This takes time and memory.
Now read the code below carefully where we are using Inheritance.
Java
// Java program with inheritanceimport java.io.*; class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return String.format( "Person :- name : %s , age : %d", getName(), getAge()); }} // Student class is inheriting the properties of Person// class( through extend keyword) Therefore, we don't need to// declare name and age (and their related methods which are// covered in Person) again.class Student extends Person { private int rollno; private String school; public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String toString() { return String.format( "Student :- name : %s , age : %d , roll : %d , school : %s", getName(), getAge(), getRollno(), getSchool()); }} // Employee class is inheriting the properties of Person// class( through extend keyword) Therefore, we don't need to// declare name and age (and their related methods which are// covered in Person) again.class Employee extends Person { private double salary; private String organisation; public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getOrganisation() { return organisation; } public void setOrganisation(String organisation) { this.organisation = organisation; } public String toString() { return String.format( "Employee :- name : %s , age : %d , organisation : %s , salary : %f", getName(), getAge(), getOrganisation(), getSalary()); }} public class PersonRunner { public static void main(String[] args) { Person person = new Person(); Student student = new Student(); Employee employee = new Employee(); person.setName("Saurabh"); person.setAge(20); student.setName("Prateek"); student.setAge(21); student.setRollno(101); student.setSchool("New Era HS"); employee.setName("Sushant"); employee.setAge(25); employee.setOrganisation("GeeksforGeeks"); employee.setSalary(50000.00); System.out.println(person); System.out.println(student); System.out.println(employee); }}
Person :- name : Saurabh , age : 20
Student :- name : Prateek , age : 21 , roll : 101 , school : New Era HS
Employee :- name : Sushant , age : 25 , organisation : GeeksforGeeks , salary : 50000.000000
Note that we have written less code in the above example when Inheritance is used compare to the first example where Inheritance was not used and thus we had to define the name, age, and their related methods again and again.
That is, we have utilized the concept of reusability as we have reused the code written in Person class over and over again.
Also, the above example shows Method Overriding (as toString function of Person class is overridden in both the Student and the Employee class, which is also a major feature of Inheritance.
Thus, it concludes that the main aim of inheritance is to implement the concept of reusability, saving our time and resources and also creating better connections between different classes, and achieve method overriding.
java-inheritance
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 291,
"s": 54,
"text": "Inheritance, as we have all heard is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is the need for Inheritance? Why is it so an important concept"
},
{
"code": null,
"e": 472,
"s": 291,
"text": "Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e. data members) and behavior (i.e. member functions or methods) of a parent object."
},
{
"code": null,
"e": 732,
"s": 472,
"text": "The basic idea of Inheritance is to create the new class (called child class or derived or subclass) from an existing class (called parent class or Base or Superclass). That is, the child class inherits the properties (methods and fields) of the parent class."
},
{
"code": null,
"e": 874,
"s": 732,
"text": "Thinking to achieve something without Inheritance will be the misuse of time and resources as we have to write the same code again and again."
},
{
"code": null,
"e": 1015,
"s": 874,
"text": "Let us take an example, three classes Person, Employee and Student have some attributes, some common and some different. See the code below."
},
{
"code": null,
"e": 1020,
"s": 1015,
"text": "Java"
},
{
"code": "// Java program without inheritanceimport java.io.*;import java.math.BigDecimal; // class personclass Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return String.format( \"Person :- name : %s , age : %d\", name, age); }} //class studentclass Student { private String name; private int age; private int rollno; private String school; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String toString() { return String.format( \"Student :- name : %s , age : %d , roll : %d , school : %s\", name, age, rollno, school); }} //class Employeeclass Employee { private String name; private int age; private double salary; private String organisation; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getOrganisation() { return organisation; } public void setOrganisation(String organisation) { this.organisation = organisation; } public String toString() { return String.format( \"Employee :- name : %s , age : %d , organisation : %s , salary : %f\", name, age, organisation, salary); }} // class PersonRunnerpublic class PersonRunner { public static void main(String[] args) { Person person = new Person(); Student student = new Student(); Employee employee = new Employee(); person.setName(\"Saurabh\"); person.setAge(20); student.setName(\"Prateek\"); student.setAge(21); student.setRollno(101); student.setSchool(\"New Era HS\"); employee.setName(\"Sushant\"); employee.setAge(25); employee.setOrganisation(\"GeeksforGeeks\"); employee.setSalary(50000.00); System.out.println(person); System.out.println(student); System.out.println(employee); }}",
"e": 3786,
"s": 1020,
"text": null
},
{
"code": null,
"e": 3987,
"s": 3786,
"text": "Person :- name : Saurabh , age : 20\nStudent :- name : Prateek , age : 21 , roll : 101 , school : New Era HS\nEmployee :- name : Sushant , age : 25 , organisation : GeeksforGeeks , salary : 50000.000000"
},
{
"code": null,
"e": 4138,
"s": 3987,
"text": "Note that we have to write the same code which is already written in Person class again in Student and in Employee class. This takes time and memory. "
},
{
"code": null,
"e": 4204,
"s": 4138,
"text": "Now read the code below carefully where we are using Inheritance."
},
{
"code": null,
"e": 4209,
"s": 4204,
"text": "Java"
},
{
"code": "// Java program with inheritanceimport java.io.*; class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return String.format( \"Person :- name : %s , age : %d\", getName(), getAge()); }} // Student class is inheriting the properties of Person// class( through extend keyword) Therefore, we don't need to// declare name and age (and their related methods which are// covered in Person) again.class Student extends Person { private int rollno; private String school; public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String toString() { return String.format( \"Student :- name : %s , age : %d , roll : %d , school : %s\", getName(), getAge(), getRollno(), getSchool()); }} // Employee class is inheriting the properties of Person// class( through extend keyword) Therefore, we don't need to// declare name and age (and their related methods which are// covered in Person) again.class Employee extends Person { private double salary; private String organisation; public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getOrganisation() { return organisation; } public void setOrganisation(String organisation) { this.organisation = organisation; } public String toString() { return String.format( \"Employee :- name : %s , age : %d , organisation : %s , salary : %f\", getName(), getAge(), getOrganisation(), getSalary()); }} public class PersonRunner { public static void main(String[] args) { Person person = new Person(); Student student = new Student(); Employee employee = new Employee(); person.setName(\"Saurabh\"); person.setAge(20); student.setName(\"Prateek\"); student.setAge(21); student.setRollno(101); student.setSchool(\"New Era HS\"); employee.setName(\"Sushant\"); employee.setAge(25); employee.setOrganisation(\"GeeksforGeeks\"); employee.setSalary(50000.00); System.out.println(person); System.out.println(student); System.out.println(employee); }}",
"e": 6900,
"s": 4209,
"text": null
},
{
"code": null,
"e": 7101,
"s": 6900,
"text": "Person :- name : Saurabh , age : 20\nStudent :- name : Prateek , age : 21 , roll : 101 , school : New Era HS\nEmployee :- name : Sushant , age : 25 , organisation : GeeksforGeeks , salary : 50000.000000"
},
{
"code": null,
"e": 7327,
"s": 7101,
"text": "Note that we have written less code in the above example when Inheritance is used compare to the first example where Inheritance was not used and thus we had to define the name, age, and their related methods again and again."
},
{
"code": null,
"e": 7452,
"s": 7327,
"text": "That is, we have utilized the concept of reusability as we have reused the code written in Person class over and over again."
},
{
"code": null,
"e": 7642,
"s": 7452,
"text": "Also, the above example shows Method Overriding (as toString function of Person class is overridden in both the Student and the Employee class, which is also a major feature of Inheritance."
},
{
"code": null,
"e": 7864,
"s": 7642,
"text": "Thus, it concludes that the main aim of inheritance is to implement the concept of reusability, saving our time and resources and also creating better connections between different classes, and achieve method overriding. "
},
{
"code": null,
"e": 7881,
"s": 7864,
"text": "java-inheritance"
},
{
"code": null,
"e": 7902,
"s": 7881,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 7907,
"s": 7902,
"text": "Java"
},
{
"code": null,
"e": 7912,
"s": 7907,
"text": "Java"
}
] |
Python File seek() Method | Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
Following is the syntax for seek() method −
fileObject.seek(offset[, whence])
offset − This is the position of the read/write pointer within the file.
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
This method does not return any value.
The following example shows the usage of seek() method.
Python is a great language
Python is a great language
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print "Read Line: %s" % (line)
# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)
# Close opend file
fo.close()
When we run above program, it produces following result −
Name of the file: foo.txt
Read Line: Python is a great language.
Read Line: Python is a great language. | [
{
"code": null,
"e": 2656,
"s": 2378,
"text": "Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end."
},
{
"code": null,
"e": 2810,
"s": 2656,
"text": "There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write."
},
{
"code": null,
"e": 2999,
"s": 2810,
"text": "If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+')."
},
{
"code": null,
"e": 3136,
"s": 2999,
"text": "If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior."
},
{
"code": null,
"e": 3181,
"s": 3136,
"text": "Note that not all file objects are seekable."
},
{
"code": null,
"e": 3225,
"s": 3181,
"text": "Following is the syntax for seek() method −"
},
{
"code": null,
"e": 3260,
"s": 3225,
"text": "fileObject.seek(offset[, whence])\n"
},
{
"code": null,
"e": 3333,
"s": 3260,
"text": "offset − This is the position of the read/write pointer within the file."
},
{
"code": null,
"e": 3406,
"s": 3333,
"text": "offset − This is the position of the read/write pointer within the file."
},
{
"code": null,
"e": 3603,
"s": 3406,
"text": "whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end."
},
{
"code": null,
"e": 3800,
"s": 3603,
"text": "whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end."
},
{
"code": null,
"e": 3839,
"s": 3800,
"text": "This method does not return any value."
},
{
"code": null,
"e": 3895,
"s": 3839,
"text": "The following example shows the usage of seek() method."
},
{
"code": null,
"e": 3950,
"s": 3895,
"text": "Python is a great language\nPython is a great language\n"
},
{
"code": null,
"e": 4373,
"s": 3950,
"text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"rw+\")\nprint \"Name of the file: \", fo.name\n\n# Assuming file has following 5 lines\n# This is 1st line\n# This is 2nd line\n# This is 3rd line\n# This is 4th line\n# This is 5th line\n\nline = fo.readline()\nprint \"Read Line: %s\" % (line)\n\n# Again set the pointer to the beginning\nfo.seek(0, 0)\nline = fo.readline()\nprint \"Read Line: %s\" % (line)\n\n# Close opend file\nfo.close()"
},
{
"code": null,
"e": 4431,
"s": 4373,
"text": "When we run above program, it produces following result −"
}
] |
PyQt5 QCalendarWidget – Clicked signal | 25 Nov, 2021
In this article we will see how we can get the clicked signal from the QCalendarWidget. Clicked signal is emitted when a mouse button is clicked i.e when the mouse was clicked on the specified date. The signal is only emitted when clicked on a valid date, e.g., dates are not outside the minimum date and maximum date. If the selection mode is NoSelection, this signal will not be emitted.
In order to do this we will use clicked method with the QCalendarWidget object.Syntax : calendar.clicked.connect(lambda: print(“Clicked”))Argument : It takes method as argumentAction Performed : It will print the message whenever activated signal get emitted
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sysclass Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # creating a label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 280, 250, 60) # making label multi line label.setWordWrap(True) # text text = "Clicked Signals received (No.) : " # current count self.count = 0 # getting the clicked signal and # when receives the signal printing the message calendar.clicked.connect(lambda: label.setText(text + str(get_count()))) # method to increase the count value def get_count(): self.count += 1 return self.count # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 418,
"s": 28,
"text": "In this article we will see how we can get the clicked signal from the QCalendarWidget. Clicked signal is emitted when a mouse button is clicked i.e when the mouse was clicked on the specified date. The signal is only emitted when clicked on a valid date, e.g., dates are not outside the minimum date and maximum date. If the selection mode is NoSelection, this signal will not be emitted."
},
{
"code": null,
"e": 679,
"s": 418,
"text": "In order to do this we will use clicked method with the QCalendarWidget object.Syntax : calendar.clicked.connect(lambda: print(“Clicked”))Argument : It takes method as argumentAction Performed : It will print the message whenever activated signal get emitted "
},
{
"code": null,
"e": 708,
"s": 679,
"text": "Below is the implementation "
},
{
"code": null,
"e": 716,
"s": 708,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sysclass Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # creating a label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 280, 250, 60) # making label multi line label.setWordWrap(True) # text text = \"Clicked Signals received (No.) : \" # current count self.count = 0 # getting the clicked signal and # when receives the signal printing the message calendar.clicked.connect(lambda: label.setText(text + str(get_count()))) # method to increase the count value def get_count(): self.count += 1 return self.count # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2154,
"s": 716,
"text": null
},
{
"code": null,
"e": 2164,
"s": 2154,
"text": "Output : "
},
{
"code": null,
"e": 2174,
"s": 2166,
"text": "clintra"
},
{
"code": null,
"e": 2202,
"s": 2174,
"text": "Python PyQt-QCalendarWidget"
},
{
"code": null,
"e": 2213,
"s": 2202,
"text": "Python-gui"
},
{
"code": null,
"e": 2225,
"s": 2213,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2232,
"s": 2225,
"text": "Python"
},
{
"code": null,
"e": 2330,
"s": 2232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2348,
"s": 2330,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2390,
"s": 2348,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2412,
"s": 2390,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2447,
"s": 2412,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2473,
"s": 2447,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2505,
"s": 2473,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2534,
"s": 2505,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2564,
"s": 2534,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2591,
"s": 2564,
"text": "Python Classes and Objects"
}
] |
How to insert a line break in PHP string ? | 07 Oct, 2021
In this article, we will discuss how to insert a line break in PHP string. We will get it by using nl2br() function. This function is used to give a new line break wherever ‘\n’ is placed.
Syntax:
nl2br("string \n");
where, string is the input string.
Example 1: PHP Program to insert a line break in a string.
PHP
<?php // Insert a new line breakecho nl2br("This is first line \n This is second line"); ?>
This is first line <br />
This is second line
Example 2:
PHP
<?php // Insert a line break with new lineecho nl2br("This is first line \n This is second " + "line \n This is third line \n This is forth line"); ?>
This is first line <br />
This is second line <br />
This is third line <br />
This is forth line
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "In this article, we will discuss how to insert a line break in PHP string. We will get it by using nl2br() function. This function is used to give a new line break wherever ‘\\n’ is placed."
},
{
"code": null,
"e": 225,
"s": 217,
"text": "Syntax:"
},
{
"code": null,
"e": 245,
"s": 225,
"text": "nl2br(\"string \\n\");"
},
{
"code": null,
"e": 280,
"s": 245,
"text": "where, string is the input string."
},
{
"code": null,
"e": 339,
"s": 280,
"text": "Example 1: PHP Program to insert a line break in a string."
},
{
"code": null,
"e": 343,
"s": 339,
"text": "PHP"
},
{
"code": "<?php // Insert a new line breakecho nl2br(\"This is first line \\n This is second line\"); ?>",
"e": 437,
"s": 343,
"text": null
},
{
"code": null,
"e": 484,
"s": 437,
"text": "This is first line <br />\n This is second line"
},
{
"code": null,
"e": 495,
"s": 484,
"text": "Example 2:"
},
{
"code": null,
"e": 499,
"s": 495,
"text": "PHP"
},
{
"code": "<?php // Insert a line break with new lineecho nl2br(\"This is first line \\n This is second \" + \"line \\n This is third line \\n This is forth line\"); ?>",
"e": 654,
"s": 499,
"text": null
},
{
"code": null,
"e": 755,
"s": 654,
"text": "This is first line <br />\n This is second line <br />\n This is third line <br />\n This is forth line"
},
{
"code": null,
"e": 768,
"s": 755,
"text": "PHP-function"
},
{
"code": null,
"e": 782,
"s": 768,
"text": "PHP-Questions"
},
{
"code": null,
"e": 793,
"s": 782,
"text": "PHP-string"
},
{
"code": null,
"e": 800,
"s": 793,
"text": "Picked"
},
{
"code": null,
"e": 804,
"s": 800,
"text": "PHP"
},
{
"code": null,
"e": 821,
"s": 804,
"text": "Web Technologies"
},
{
"code": null,
"e": 825,
"s": 821,
"text": "PHP"
}
] |
Intent Filter in Android with Demo App | 07 Mar, 2021
The intent is a messaging object which tells what kind of action to be performed. The intent’s most significant use is the launching of the activity. Intent facilitates the communication between the components.
Note: App components are the basic building blocks of App.
Starting Activity
An activity represents the single screen in an app, Bypassing intent instance we can start an activity.
Example:
Kotlin
var intent = Intent(this, SecondActivity:: class.java)startIntent(intent)
You can add extra information by using putExtra().
Starting a Service
A Service is a component that performs operations in the background without a user interface, which is also called a background process.
Delivering a Broadcast
A broadcast is a message that any app can receive. In android, the system delivers various broadcast system events like device starts charging, disable or enable airplane mode, etc.
There are two types of intent
Explicit intent: Explicit intent can do the specific application action which is set by the code like changing activity, In explicit intent user knows about all the things like after clicking a button which activity will start and Explicit intents are used for communication inside the applicationImplicit Intent: Implicit intents do not name a specific component like explicit intent, instead declare general action to perform, which allows a component from another app to handle.
Explicit intent: Explicit intent can do the specific application action which is set by the code like changing activity, In explicit intent user knows about all the things like after clicking a button which activity will start and Explicit intents are used for communication inside the application
Implicit Intent: Implicit intents do not name a specific component like explicit intent, instead declare general action to perform, which allows a component from another app to handle.
For example: when you tap the share button in any app you can see the Gmail, Bluetooth, and other sharing app options.
Implicit intent uses the intent filter to serve the user request.
The intent filter specifies the types of intents that an activity, service, or broadcast receiver can respond.
Intent filters are declared in the Android manifest file.
Intent filter must contain <action>
Example:
XML
<intent-filter android:icon="drawable resource" android:label="string resource" android:priority="integer" > . . .</intent-filter>
Most of the intent filter are describe by its
<action>, <category> and<data>.
<action>,
<category> and
<data>.
Syntax:
XML
<action android:name="string" />
Adds an action to an intent filter. An <intent-filter> element must contain one or more <action> elements. If there are no <action> elements in an intent filter, the filter doesn’t accept any Intent objects.
Examples of common action:
ACTION_VIEW: Use this action in intent with startActivity() when you have some information that activity can show to the user like showing an image in a gallery app or an address to view in a map app
ACTION_SEND: You should use this in intent with startActivity() when you have some data that the user can share through another app, such as an email app or social sharing app.
Syntax:
XML
<category android:name="string" />
Adds a category name to an intent filter. A string containing additional information about the kind of component that should handle the intent.
Example of common categories:
CATEGORY_BROWSABLE: The target activity allows itself to be started by a web browser to display data referenced by a link.
Syntax:
XML
<data android:scheme="string" android:host="string" android:port="string" android:path="string" android:pathPattern="string" android:pathPrefix="string" android:mimeType="string" />
Adds a data specification to an intent filter. The specification can be just a data type, just a URI, or both a data type and a URI.
Note: Uniform Resource Identifier (URI) is a string of characters used to identify a resource. A URI identifies a resource either by location, or a name, or both.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add dependencies to the build.gradle(Module:app) file
Add the following dependency to the build.gradle(Module:app) file. We are adding these two dependencies because to avoid using findViewById() in our MainActivity.kt file. Try this out otherwise use the normal way like findViewById().
apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/sendButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SEND" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.476" app:layout_constraintStart_toStartOf="parent" app:layout_constraintVertical_bias="0.153" /> <Button android:id="@+id/buttonView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.826" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Working with the AndroidManifest.xml File
Following is the code for the AndroidManifest.xml File.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.menuapplication"> <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/Theme.MenuApplication"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!--SEND INTENT FILTER--> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter> <!--VIEW INTENT FILTER--> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:scheme="http"/> </intent-filter> </activity> </application> </manifest>
Step 5: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.example.intentfilter import android.content.Intentimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // send button on click listener sendButton.setOnClickListener { var intent = Intent(Intent.ACTION_SEND) // intent intent.type = "text/plain" intent.putExtra(Intent.EXTRA_EMAIL, "[email protected]") intent.putExtra(Intent.EXTRA_SUBJECT, "This is a dummy message") intent.putExtra(Intent.EXTRA_TEXT, "Dummy test message") startActivity(intent) } // View on click listener buttonView.setOnClickListener { var intent = Intent(Intent.ACTION_VIEW) startActivity(intent) } }}
Output with Explanation:
Click on Send Button, you will see a screen like this,
Now choose Gmail app,
Now go to our app and click the view button,
our app dummy app. You can any app from these options because we are using a view intent filter.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Kotlin constructor
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Mar, 2021"
},
{
"code": null,
"e": 263,
"s": 52,
"text": "The intent is a messaging object which tells what kind of action to be performed. The intent’s most significant use is the launching of the activity. Intent facilitates the communication between the components."
},
{
"code": null,
"e": 322,
"s": 263,
"text": "Note: App components are the basic building blocks of App."
},
{
"code": null,
"e": 340,
"s": 322,
"text": "Starting Activity"
},
{
"code": null,
"e": 444,
"s": 340,
"text": "An activity represents the single screen in an app, Bypassing intent instance we can start an activity."
},
{
"code": null,
"e": 453,
"s": 444,
"text": "Example:"
},
{
"code": null,
"e": 460,
"s": 453,
"text": "Kotlin"
},
{
"code": "var intent = Intent(this, SecondActivity:: class.java)startIntent(intent)",
"e": 534,
"s": 460,
"text": null
},
{
"code": null,
"e": 585,
"s": 534,
"text": "You can add extra information by using putExtra()."
},
{
"code": null,
"e": 604,
"s": 585,
"text": "Starting a Service"
},
{
"code": null,
"e": 741,
"s": 604,
"text": "A Service is a component that performs operations in the background without a user interface, which is also called a background process."
},
{
"code": null,
"e": 764,
"s": 741,
"text": "Delivering a Broadcast"
},
{
"code": null,
"e": 946,
"s": 764,
"text": "A broadcast is a message that any app can receive. In android, the system delivers various broadcast system events like device starts charging, disable or enable airplane mode, etc."
},
{
"code": null,
"e": 976,
"s": 946,
"text": "There are two types of intent"
},
{
"code": null,
"e": 1458,
"s": 976,
"text": "Explicit intent: Explicit intent can do the specific application action which is set by the code like changing activity, In explicit intent user knows about all the things like after clicking a button which activity will start and Explicit intents are used for communication inside the applicationImplicit Intent: Implicit intents do not name a specific component like explicit intent, instead declare general action to perform, which allows a component from another app to handle."
},
{
"code": null,
"e": 1756,
"s": 1458,
"text": "Explicit intent: Explicit intent can do the specific application action which is set by the code like changing activity, In explicit intent user knows about all the things like after clicking a button which activity will start and Explicit intents are used for communication inside the application"
},
{
"code": null,
"e": 1941,
"s": 1756,
"text": "Implicit Intent: Implicit intents do not name a specific component like explicit intent, instead declare general action to perform, which allows a component from another app to handle."
},
{
"code": null,
"e": 2061,
"s": 1941,
"text": "For example: when you tap the share button in any app you can see the Gmail, Bluetooth, and other sharing app options. "
},
{
"code": null,
"e": 2127,
"s": 2061,
"text": "Implicit intent uses the intent filter to serve the user request."
},
{
"code": null,
"e": 2238,
"s": 2127,
"text": "The intent filter specifies the types of intents that an activity, service, or broadcast receiver can respond."
},
{
"code": null,
"e": 2296,
"s": 2238,
"text": "Intent filters are declared in the Android manifest file."
},
{
"code": null,
"e": 2332,
"s": 2296,
"text": "Intent filter must contain <action>"
},
{
"code": null,
"e": 2341,
"s": 2332,
"text": "Example:"
},
{
"code": null,
"e": 2345,
"s": 2341,
"text": "XML"
},
{
"code": "<intent-filter android:icon=\"drawable resource\" android:label=\"string resource\" android:priority=\"integer\" > . . .</intent-filter>",
"e": 2481,
"s": 2345,
"text": null
},
{
"code": null,
"e": 2528,
"s": 2481,
"text": "Most of the intent filter are describe by its "
},
{
"code": null,
"e": 2560,
"s": 2528,
"text": "<action>, <category> and<data>."
},
{
"code": null,
"e": 2571,
"s": 2560,
"text": "<action>, "
},
{
"code": null,
"e": 2586,
"s": 2571,
"text": "<category> and"
},
{
"code": null,
"e": 2594,
"s": 2586,
"text": "<data>."
},
{
"code": null,
"e": 2602,
"s": 2594,
"text": "Syntax:"
},
{
"code": null,
"e": 2606,
"s": 2602,
"text": "XML"
},
{
"code": "<action android:name=\"string\" />",
"e": 2639,
"s": 2606,
"text": null
},
{
"code": null,
"e": 2847,
"s": 2639,
"text": "Adds an action to an intent filter. An <intent-filter> element must contain one or more <action> elements. If there are no <action> elements in an intent filter, the filter doesn’t accept any Intent objects."
},
{
"code": null,
"e": 2874,
"s": 2847,
"text": "Examples of common action:"
},
{
"code": null,
"e": 3075,
"s": 2874,
"text": "ACTION_VIEW: Use this action in intent with startActivity() when you have some information that activity can show to the user like showing an image in a gallery app or an address to view in a map app"
},
{
"code": null,
"e": 3252,
"s": 3075,
"text": "ACTION_SEND: You should use this in intent with startActivity() when you have some data that the user can share through another app, such as an email app or social sharing app."
},
{
"code": null,
"e": 3260,
"s": 3252,
"text": "Syntax:"
},
{
"code": null,
"e": 3264,
"s": 3260,
"text": "XML"
},
{
"code": "<category android:name=\"string\" />",
"e": 3299,
"s": 3264,
"text": null
},
{
"code": null,
"e": 3443,
"s": 3299,
"text": "Adds a category name to an intent filter. A string containing additional information about the kind of component that should handle the intent."
},
{
"code": null,
"e": 3473,
"s": 3443,
"text": "Example of common categories:"
},
{
"code": null,
"e": 3596,
"s": 3473,
"text": "CATEGORY_BROWSABLE: The target activity allows itself to be started by a web browser to display data referenced by a link."
},
{
"code": null,
"e": 3604,
"s": 3596,
"text": "Syntax:"
},
{
"code": null,
"e": 3608,
"s": 3604,
"text": "XML"
},
{
"code": "<data android:scheme=\"string\" android:host=\"string\" android:port=\"string\" android:path=\"string\" android:pathPattern=\"string\" android:pathPrefix=\"string\" android:mimeType=\"string\" />",
"e": 3820,
"s": 3608,
"text": null
},
{
"code": null,
"e": 3953,
"s": 3820,
"text": "Adds a data specification to an intent filter. The specification can be just a data type, just a URI, or both a data type and a URI."
},
{
"code": null,
"e": 4116,
"s": 3953,
"text": "Note: Uniform Resource Identifier (URI) is a string of characters used to identify a resource. A URI identifies a resource either by location, or a name, or both."
},
{
"code": null,
"e": 4145,
"s": 4116,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 4309,
"s": 4145,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 4371,
"s": 4309,
"text": "Step 2: Add dependencies to the build.gradle(Module:app) file"
},
{
"code": null,
"e": 4605,
"s": 4371,
"text": "Add the following dependency to the build.gradle(Module:app) file. We are adding these two dependencies because to avoid using findViewById() in our MainActivity.kt file. Try this out otherwise use the normal way like findViewById()."
},
{
"code": null,
"e": 4636,
"s": 4605,
"text": "apply plugin: ‘kotlin-android’"
},
{
"code": null,
"e": 4678,
"s": 4636,
"text": "apply plugin: ‘kotlin-android-extensions’"
},
{
"code": null,
"e": 4726,
"s": 4678,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 4869,
"s": 4726,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 4873,
"s": 4869,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/sendButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"SEND\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.476\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintVertical_bias=\"0.153\" /> <Button android:id=\"@+id/buttonView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"View\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.826\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 6144,
"s": 4873,
"text": null
},
{
"code": null,
"e": 6194,
"s": 6144,
"text": "Step 4: Working with the AndroidManifest.xml File"
},
{
"code": null,
"e": 6250,
"s": 6194,
"text": "Following is the code for the AndroidManifest.xml File."
},
{
"code": null,
"e": 6254,
"s": 6250,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.menuapplication\"> <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/Theme.MenuApplication\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> <!--SEND INTENT FILTER--> <intent-filter> <action android:name=\"android.intent.action.SEND\"/> <category android:name=\"android.intent.category.DEFAULT\"/> <data android:mimeType=\"text/plain\"/> </intent-filter> <!--VIEW INTENT FILTER--> <intent-filter> <action android:name=\"android.intent.action.VIEW\"/> <category android:name=\"android.intent.category.DEFAULT\"/> <category android:name=\"android.intent.category.BROWSABLE\"/> <data android:scheme=\"http\"/> </intent-filter> </activity> </application> </manifest>",
"e": 7621,
"s": 6254,
"text": null
},
{
"code": null,
"e": 7667,
"s": 7621,
"text": "Step 5: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 7853,
"s": 7667,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 7860,
"s": 7853,
"text": "Kotlin"
},
{
"code": "package com.example.intentfilter import android.content.Intentimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // send button on click listener sendButton.setOnClickListener { var intent = Intent(Intent.ACTION_SEND) // intent intent.type = \"text/plain\" intent.putExtra(Intent.EXTRA_EMAIL, \"[email protected]\") intent.putExtra(Intent.EXTRA_SUBJECT, \"This is a dummy message\") intent.putExtra(Intent.EXTRA_TEXT, \"Dummy test message\") startActivity(intent) } // View on click listener buttonView.setOnClickListener { var intent = Intent(Intent.ACTION_VIEW) startActivity(intent) } }}",
"e": 8848,
"s": 7860,
"text": null
},
{
"code": null,
"e": 8873,
"s": 8848,
"text": "Output with Explanation:"
},
{
"code": null,
"e": 8928,
"s": 8873,
"text": "Click on Send Button, you will see a screen like this,"
},
{
"code": null,
"e": 8950,
"s": 8928,
"text": "Now choose Gmail app,"
},
{
"code": null,
"e": 8995,
"s": 8950,
"text": "Now go to our app and click the view button,"
},
{
"code": null,
"e": 9092,
"s": 8995,
"text": "our app dummy app. You can any app from these options because we are using a view intent filter."
},
{
"code": null,
"e": 9100,
"s": 9092,
"text": "Android"
},
{
"code": null,
"e": 9107,
"s": 9100,
"text": "Kotlin"
},
{
"code": null,
"e": 9115,
"s": 9107,
"text": "Android"
},
{
"code": null,
"e": 9213,
"s": 9115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9245,
"s": 9213,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 9284,
"s": 9245,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 9353,
"s": 9284,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 9395,
"s": 9353,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 9446,
"s": 9395,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 9465,
"s": 9446,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 9478,
"s": 9465,
"text": "Kotlin Array"
},
{
"code": null,
"e": 9497,
"s": 9478,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 9539,
"s": 9497,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
Express.js req.cookies Property | 08 Jul, 2020
The req.cookies property is used when the user is using cookie-parser middleware. This property is an object that contains cookies sent by the request.
Syntax:
req.cookies
Parameter: No parameters.
Return Value: Object
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing the express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
var cookieParser = require('cookie-parser');var express = require('express');var app = express(); var PORT = 3000; app.use(cookieParser()); app.get('/', function (req, res) { req.cookies.title='GeeksforGeeks'; console.log(req.cookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express and cookie-parser module using the following command:npm install express
npm install cookie-parser
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000
[Object: null prototype] { title: 'GeeksforGeeks' }
The project structure will look like this:
Make sure you have installed express and cookie-parser module using the following command:npm install express
npm install cookie-parser
npm install express
npm install cookie-parser
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000
[Object: null prototype] { title: 'GeeksforGeeks' }
Server listening on PORT 3000
[Object: null prototype] { title: 'GeeksforGeeks' }
Example 2: Filename: index.js
var cookieParser = require('cookie-parser');var express = require('express');var app = express(); var PORT = 3000; app.use(cookieParser()); app.get('/user', function (req, res) { req.cookies.name='Gourav'; req.cookies.age=12; console.log(req.cookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:
Server listening on PORT 3000
[Object: null prototype] { name: 'Gourav', age: 12 }
Reference: https://expressjs.com/en/4x/api.html#req.cookies
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "The req.cookies property is used when the user is using cookie-parser middleware. This property is an object that contains cookies sent by the request."
},
{
"code": null,
"e": 188,
"s": 180,
"text": "Syntax:"
},
{
"code": null,
"e": 200,
"s": 188,
"text": "req.cookies"
},
{
"code": null,
"e": 226,
"s": 200,
"text": "Parameter: No parameters."
},
{
"code": null,
"e": 247,
"s": 226,
"text": "Return Value: Object"
},
{
"code": null,
"e": 279,
"s": 247,
"text": "Installation of express module:"
},
{
"code": null,
"e": 674,
"s": 279,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 795,
"s": 674,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 815,
"s": 795,
"text": "npm install express"
},
{
"code": null,
"e": 943,
"s": 815,
"text": "After installing the express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 963,
"s": 943,
"text": "npm version express"
},
{
"code": null,
"e": 1111,
"s": 963,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1125,
"s": 1111,
"text": "node index.js"
},
{
"code": null,
"e": 1155,
"s": 1125,
"text": "Example 1: Filename: index.js"
},
{
"code": "var cookieParser = require('cookie-parser');var express = require('express');var app = express(); var PORT = 3000; app.use(cookieParser()); app.get('/', function (req, res) { req.cookies.title='GeeksforGeeks'; console.log(req.cookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1529,
"s": 1155,
"text": null
},
{
"code": null,
"e": 1555,
"s": 1529,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 2013,
"s": 1555,
"text": "The project structure will look like this:Make sure you have installed express and cookie-parser module using the following command:npm install express\nnpm install cookie-parser\nRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000\n[Object: null prototype] { title: 'GeeksforGeeks' }\n"
},
{
"code": null,
"e": 2056,
"s": 2013,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 2193,
"s": 2056,
"text": "Make sure you have installed express and cookie-parser module using the following command:npm install express\nnpm install cookie-parser\n"
},
{
"code": null,
"e": 2240,
"s": 2193,
"text": "npm install express\nnpm install cookie-parser\n"
},
{
"code": null,
"e": 2329,
"s": 2240,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2343,
"s": 2329,
"text": "node index.js"
},
{
"code": null,
"e": 2351,
"s": 2343,
"text": "Output:"
},
{
"code": null,
"e": 2382,
"s": 2351,
"text": "Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2574,
"s": 2382,
"text": "Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000\n[Object: null prototype] { title: 'GeeksforGeeks' }\n"
},
{
"code": null,
"e": 2657,
"s": 2574,
"text": "Server listening on PORT 3000\n[Object: null prototype] { title: 'GeeksforGeeks' }\n"
},
{
"code": null,
"e": 2687,
"s": 2657,
"text": "Example 2: Filename: index.js"
},
{
"code": "var cookieParser = require('cookie-parser');var express = require('express');var app = express(); var PORT = 3000; app.use(cookieParser()); app.get('/user', function (req, res) { req.cookies.name='Gourav'; req.cookies.age=12; console.log(req.cookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 3083,
"s": 2687,
"text": null
},
{
"code": null,
"e": 3122,
"s": 3083,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 3136,
"s": 3122,
"text": "node index.js"
},
{
"code": null,
"e": 3272,
"s": 3136,
"text": "Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:"
},
{
"code": null,
"e": 3356,
"s": 3272,
"text": "Server listening on PORT 3000\n[Object: null prototype] { name: 'Gourav', age: 12 }\n"
},
{
"code": null,
"e": 3416,
"s": 3356,
"text": "Reference: https://expressjs.com/en/4x/api.html#req.cookies"
},
{
"code": null,
"e": 3427,
"s": 3416,
"text": "Express.js"
},
{
"code": null,
"e": 3435,
"s": 3427,
"text": "Node.js"
},
{
"code": null,
"e": 3452,
"s": 3435,
"text": "Web Technologies"
},
{
"code": null,
"e": 3550,
"s": 3452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3598,
"s": 3550,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3631,
"s": 3598,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3664,
"s": 3631,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3721,
"s": 3664,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 3751,
"s": 3721,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 3784,
"s": 3751,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3846,
"s": 3784,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3907,
"s": 3846,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3957,
"s": 3907,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Sum of numbers from 1 to N which are divisible by 3 or 4 | 13 Jun, 2022
Given a number N. The task is to find the sum of all those numbers from 1 to N that are divisible by 3 or by 4.Examples:
Input : N = 5
Output : 7
sum = 3 + 4
Input : N = 12
Output : 42
sum = 3 + 4 + 6 + 8 + 9 + 12
Approach: To solve the problem, follow the below steps:
Find the sum of numbers that are divisible by 3 upto N. Denote it by S1.Find the sum of numbers that are divisible by 4 upto N. Denote it by S2.Find the sum of numbers that are divisible by 12(3*4) upto N. Denote it by S3.The final answer will be S1 + S2 – S3.
Find the sum of numbers that are divisible by 3 upto N. Denote it by S1.
Find the sum of numbers that are divisible by 4 upto N. Denote it by S2.
Find the sum of numbers that are divisible by 12(3*4) upto N. Denote it by S3.
The final answer will be S1 + S2 – S3.
In order to find the sum, we can use the general formula of A.P. which is:
Sn = (n/2) * {2*a + (n-1)*d}
Where,
n -> total number of terms
a -> first term
d -> common difference
For S1: The total numbers that will be divisible by 3 upto N will be N/3 and the series will be 3, 6, 9, 12, ....
Hence,
S1 = ((N/3)/2) * (2 * 3 + (N/3 - 1) * 3)
For S2: The total numbers that will be divisible by 4 up to N will be N/4 and the series will be 4, 8, 12, 16, ......
Hence,
S2 = ((N/4)/2) * (2 * 4 + (N/4 - 1) * 4)
For S3: The total numbers that will be divisible by 12 upto N will be N/12.
Hence,
S3 = ((N/12)/2) * (2 * 12 + (N/12 - 1) * 12)
Therefore, the result will be:
S = S1 + S2 - S3
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of numbers from 1 to N// which are divisible by 3 or 4#include <bits/stdc++.h>using namespace std; // Function to calculate the sum// of numbers divisible by 3 or 4int sum(int N){ int S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver codeint main(){ int N = 20; cout << sum(12); return 0;}
// Java program to find sum of numbers from 1 to N// which are divisible by 3 or 4class GFG{ // Function to calculate the sum// of numbers divisible by 3 or 4static int sum(int N){ int S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver code public static void main (String[] args) { int N = 20; System.out.print(sum(12));} }
# Python3 program to find sum of numbers# from 1 to N# which are divisible by 3 or 4 # Function to calculate the sum# of numbers divisible by 3 or 4def sum(N): global S1,S2,S3 S1 = (((N // 3)) * (2 * 3 + (N //3 - 1) * 3) //2) S2 = (((N // 4)) * (2 * 4 + (N // 4 - 1) * 4) // 2) S3 = (((N // 12)) * (2 * 12 + (N // 12 - 1) * 12) // 2) return int(S1 + S2 - S3) if __name__=='__main__': N = 12 print(sum(N)) # This code is contributed by Shrikant13
// C# program to find sum of// numbers from 1 to N which// are divisible by 3 or 4using System; class GFG{ // Function to calculate the sum// of numbers divisible by 3 or 4static int sum(int N){ int S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver codepublic static void Main (){ int N = 20; Console.WriteLine(sum(12));}} // This code is contributed// by inder_verma
<?php// PHP program to find sum of// numbers from 1 to N which// are divisible by 3 or 4 // Function to calculate the sum// of numbers divisible by 3 or 4function sum($N){ $S1; $S2; $S3; $S1 = (($N / 3)) * (2 * 3 + ($N / 3 - 1) * 3) / 2; $S2 = (($N / 4)) * (2 * 4 + ($N / 4 - 1) * 4) / 2; $S3 = (($N / 12)) * (2 * 12 + ($N / 12 - 1) * 12) / 2; return $S1 + $S2 - $S3;} // Driver Code$N = 20; echo sum(12); // This code is contributed// by inder_verma?>
<script> // Javascript program to find sum of numbers from 1 to N// which are divisible by 3 or 4 // Function to calculate the sum// of numbers divisible by 3 or 4function sum(N){ var S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver codevar N = 20;document.write( sum(12)); </script>
42
Time Complexity: O(1)
Auxiliary Space: O(1)
shrikanth13
Smitha Dinesh Semwal
inderDuMCA
rrrtnx
hasani
divisibility
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
Program for factorial of a number
Merge two sorted arrays with O(1) extra space
Program to find sum of elements in a given array
Program to print prime numbers from 1 to N.
Print all possible combinations of r elements in a given array of size n | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 175,
"s": 52,
"text": "Given a number N. The task is to find the sum of all those numbers from 1 to N that are divisible by 3 or by 4.Examples: "
},
{
"code": null,
"e": 270,
"s": 175,
"text": "Input : N = 5\nOutput : 7\nsum = 3 + 4\n\nInput : N = 12 \nOutput : 42\nsum = 3 + 4 + 6 + 8 + 9 + 12"
},
{
"code": null,
"e": 330,
"s": 272,
"text": "Approach: To solve the problem, follow the below steps: "
},
{
"code": null,
"e": 591,
"s": 330,
"text": "Find the sum of numbers that are divisible by 3 upto N. Denote it by S1.Find the sum of numbers that are divisible by 4 upto N. Denote it by S2.Find the sum of numbers that are divisible by 12(3*4) upto N. Denote it by S3.The final answer will be S1 + S2 – S3."
},
{
"code": null,
"e": 664,
"s": 591,
"text": "Find the sum of numbers that are divisible by 3 upto N. Denote it by S1."
},
{
"code": null,
"e": 737,
"s": 664,
"text": "Find the sum of numbers that are divisible by 4 upto N. Denote it by S2."
},
{
"code": null,
"e": 816,
"s": 737,
"text": "Find the sum of numbers that are divisible by 12(3*4) upto N. Denote it by S3."
},
{
"code": null,
"e": 855,
"s": 816,
"text": "The final answer will be S1 + S2 – S3."
},
{
"code": null,
"e": 932,
"s": 855,
"text": "In order to find the sum, we can use the general formula of A.P. which is: "
},
{
"code": null,
"e": 1035,
"s": 932,
"text": "Sn = (n/2) * {2*a + (n-1)*d}\n\nWhere,\nn -> total number of terms\na -> first term\nd -> common difference"
},
{
"code": null,
"e": 1151,
"s": 1035,
"text": "For S1: The total numbers that will be divisible by 3 upto N will be N/3 and the series will be 3, 6, 9, 12, .... "
},
{
"code": null,
"e": 1200,
"s": 1151,
"text": "Hence, \nS1 = ((N/3)/2) * (2 * 3 + (N/3 - 1) * 3)"
},
{
"code": null,
"e": 1320,
"s": 1200,
"text": "For S2: The total numbers that will be divisible by 4 up to N will be N/4 and the series will be 4, 8, 12, 16, ...... "
},
{
"code": null,
"e": 1369,
"s": 1320,
"text": "Hence, \nS2 = ((N/4)/2) * (2 * 4 + (N/4 - 1) * 4)"
},
{
"code": null,
"e": 1447,
"s": 1369,
"text": "For S3: The total numbers that will be divisible by 12 upto N will be N/12. "
},
{
"code": null,
"e": 1500,
"s": 1447,
"text": "Hence, \nS3 = ((N/12)/2) * (2 * 12 + (N/12 - 1) * 12)"
},
{
"code": null,
"e": 1533,
"s": 1500,
"text": "Therefore, the result will be: "
},
{
"code": null,
"e": 1550,
"s": 1533,
"text": "S = S1 + S2 - S3"
},
{
"code": null,
"e": 1603,
"s": 1550,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1607,
"s": 1603,
"text": "C++"
},
{
"code": null,
"e": 1612,
"s": 1607,
"text": "Java"
},
{
"code": null,
"e": 1620,
"s": 1612,
"text": "Python3"
},
{
"code": null,
"e": 1623,
"s": 1620,
"text": "C#"
},
{
"code": null,
"e": 1627,
"s": 1623,
"text": "PHP"
},
{
"code": null,
"e": 1638,
"s": 1627,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of numbers from 1 to N// which are divisible by 3 or 4#include <bits/stdc++.h>using namespace std; // Function to calculate the sum// of numbers divisible by 3 or 4int sum(int N){ int S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver codeint main(){ int N = 20; cout << sum(12); return 0;}",
"e": 2125,
"s": 1638,
"text": null
},
{
"code": "// Java program to find sum of numbers from 1 to N// which are divisible by 3 or 4class GFG{ // Function to calculate the sum// of numbers divisible by 3 or 4static int sum(int N){ int S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver code public static void main (String[] args) { int N = 20; System.out.print(sum(12));} }",
"e": 2615,
"s": 2125,
"text": null
},
{
"code": "# Python3 program to find sum of numbers# from 1 to N# which are divisible by 3 or 4 # Function to calculate the sum# of numbers divisible by 3 or 4def sum(N): global S1,S2,S3 S1 = (((N // 3)) * (2 * 3 + (N //3 - 1) * 3) //2) S2 = (((N // 4)) * (2 * 4 + (N // 4 - 1) * 4) // 2) S3 = (((N // 12)) * (2 * 12 + (N // 12 - 1) * 12) // 2) return int(S1 + S2 - S3) if __name__=='__main__': N = 12 print(sum(N)) # This code is contributed by Shrikant13",
"e": 3109,
"s": 2615,
"text": null
},
{
"code": "// C# program to find sum of// numbers from 1 to N which// are divisible by 3 or 4using System; class GFG{ // Function to calculate the sum// of numbers divisible by 3 or 4static int sum(int N){ int S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver codepublic static void Main (){ int N = 20; Console.WriteLine(sum(12));}} // This code is contributed// by inder_verma",
"e": 3670,
"s": 3109,
"text": null
},
{
"code": "<?php// PHP program to find sum of// numbers from 1 to N which// are divisible by 3 or 4 // Function to calculate the sum// of numbers divisible by 3 or 4function sum($N){ $S1; $S2; $S3; $S1 = (($N / 3)) * (2 * 3 + ($N / 3 - 1) * 3) / 2; $S2 = (($N / 4)) * (2 * 4 + ($N / 4 - 1) * 4) / 2; $S3 = (($N / 12)) * (2 * 12 + ($N / 12 - 1) * 12) / 2; return $S1 + $S2 - $S3;} // Driver Code$N = 20; echo sum(12); // This code is contributed// by inder_verma?>",
"e": 4170,
"s": 3670,
"text": null
},
{
"code": "<script> // Javascript program to find sum of numbers from 1 to N// which are divisible by 3 or 4 // Function to calculate the sum// of numbers divisible by 3 or 4function sum(N){ var S1, S2, S3; S1 = ((N / 3)) * (2 * 3 + (N / 3 - 1) * 3) / 2; S2 = ((N / 4)) * (2 * 4 + (N / 4 - 1) * 4) / 2; S3 = ((N / 12)) * (2 * 12 + (N / 12 - 1) * 12) / 2; return S1 + S2 - S3;} // Driver codevar N = 20;document.write( sum(12)); </script>",
"e": 4615,
"s": 4170,
"text": null
},
{
"code": null,
"e": 4618,
"s": 4615,
"text": "42"
},
{
"code": null,
"e": 4642,
"s": 4620,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 4664,
"s": 4642,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4676,
"s": 4664,
"text": "shrikanth13"
},
{
"code": null,
"e": 4697,
"s": 4676,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 4708,
"s": 4697,
"text": "inderDuMCA"
},
{
"code": null,
"e": 4715,
"s": 4708,
"text": "rrrtnx"
},
{
"code": null,
"e": 4722,
"s": 4715,
"text": "hasani"
},
{
"code": null,
"e": 4735,
"s": 4722,
"text": "divisibility"
},
{
"code": null,
"e": 4748,
"s": 4735,
"text": "Mathematical"
},
{
"code": null,
"e": 4761,
"s": 4748,
"text": "Mathematical"
},
{
"code": null,
"e": 4859,
"s": 4761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4880,
"s": 4859,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4933,
"s": 4880,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4976,
"s": 4933,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 5008,
"s": 4976,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5035,
"s": 5008,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 5069,
"s": 5035,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 5115,
"s": 5069,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 5164,
"s": 5115,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 5208,
"s": 5164,
"text": "Program to print prime numbers from 1 to N."
}
] |
What is the difference between inline-flex and inline-block in CSS? | 29 Mar, 2022
The display property specifies how an element should be displayed in a webpage. There can be many values, related to this property in CSS. Inline-block and inline-flex are two such properties. Although there are several values that this property can have, to understand the aforementioned, let us first look into three other values: inline, block, flex.
Inline: Just as the name suggests, inline displays an element in the same line as the rest. Specifying any height and width properties will be of no use, as it follows the height and width of the line, of which it is a part.
Block: Displays an element as a block element. It starts on a new line and takes up take up as much horizontal space as they can. Block-level elements do not appear in the same line, but breaks the existing line and appear in the next line.
Flex: Flex displays an element as a flexible structure. To use flex display, a flex level container has to be created. Flex level container is nothing, but an element with the display property set to flex. The flex container itself is displayed in a new line, just like the block element. The flex container can contain other elements in it and thus, the flex container is the parent element and the elements that are part of it are the child elements. Display flex property helps us to align and distribute space among items in a container, even when their size is unknown and/or dynamic.
Inline-Block: Displays an element as an inline-level block container. An element set to inline-block is very similar to inline in that it will be set in line with the natural flow of text, i.e; unlike display: block, display:inline-block does not add a line-break after the element. So, the element can sit next to other elements. The element itself is formatted as an inline element, but it allows you to set a width and height on the element, which is not possible in the display: inline. Example:
html
<!DOCTYPE html><html><title>CSS inline-block</title><style> body { text-align: center; font-size: 28px; } h1 { color: green; }</style> <body> <h1>GeeksforGeeks</h1> A Online <div style="display:inline-block; background-color:yellow; width:auto; height:auto"> <div style="display:inline; background-color:purple;">Computer</div> <div style="display:inline; background-color:orange;">Science</div> <div style="display:inline; background-color:cyan;">Portal</div> </div> for Geeks</body> </html>
Output:
Inline-flex: Displays an element as an inline-level flex container. The display:inline-flex does not make flex items display inline. It makes the flex container display inline. The main difference between display: flex and display: inline-flex is that display: inline-flex will make the flex container an inline element while its content maintains its flexbox properties. In the below picture, the flex container comprises Computer, Science, Portal, and the yellow area. Example:
html
<!DOCTYPE html><html><title>CSS inline-block</title><style> body { text-align: center; font-size: 28px; } h1 { color: green; }</style> <body> <h1>GeeksforGeeks</h1> A Online <div style="display:inline-flex; background-color:yellow; width:auto; height:auto"> <div style="display:inline; background-color:purple;">Computer</div> <div style="display:inline; background-color:orange;">Science</div> <div style="display:inline; background-color:cyan;">Portal</div> </div> for Geeks</body> </html>
Output:
There is only one main difference between the inline-block and inline-flex: inline-block: Create specific block for each element under its section maintain the structure of each element. inline-flex: Does not reserved any specific space in normal form.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
singghakshay
johnbernalfsd
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 408,
"s": 52,
"text": "The display property specifies how an element should be displayed in a webpage. There can be many values, related to this property in CSS. Inline-block and inline-flex are two such properties. Although there are several values that this property can have, to understand the aforementioned, let us first look into three other values: inline, block, flex. "
},
{
"code": null,
"e": 633,
"s": 408,
"text": "Inline: Just as the name suggests, inline displays an element in the same line as the rest. Specifying any height and width properties will be of no use, as it follows the height and width of the line, of which it is a part."
},
{
"code": null,
"e": 874,
"s": 633,
"text": "Block: Displays an element as a block element. It starts on a new line and takes up take up as much horizontal space as they can. Block-level elements do not appear in the same line, but breaks the existing line and appear in the next line."
},
{
"code": null,
"e": 1464,
"s": 874,
"text": "Flex: Flex displays an element as a flexible structure. To use flex display, a flex level container has to be created. Flex level container is nothing, but an element with the display property set to flex. The flex container itself is displayed in a new line, just like the block element. The flex container can contain other elements in it and thus, the flex container is the parent element and the elements that are part of it are the child elements. Display flex property helps us to align and distribute space among items in a container, even when their size is unknown and/or dynamic."
},
{
"code": null,
"e": 1966,
"s": 1464,
"text": "Inline-Block: Displays an element as an inline-level block container. An element set to inline-block is very similar to inline in that it will be set in line with the natural flow of text, i.e; unlike display: block, display:inline-block does not add a line-break after the element. So, the element can sit next to other elements. The element itself is formatted as an inline element, but it allows you to set a width and height on the element, which is not possible in the display: inline. Example: "
},
{
"code": null,
"e": 1971,
"s": 1966,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><title>CSS inline-block</title><style> body { text-align: center; font-size: 28px; } h1 { color: green; }</style> <body> <h1>GeeksforGeeks</h1> A Online <div style=\"display:inline-block; background-color:yellow; width:auto; height:auto\"> <div style=\"display:inline; background-color:purple;\">Computer</div> <div style=\"display:inline; background-color:orange;\">Science</div> <div style=\"display:inline; background-color:cyan;\">Portal</div> </div> for Geeks</body> </html>",
"e": 2535,
"s": 1971,
"text": null
},
{
"code": null,
"e": 2545,
"s": 2535,
"text": "Output: "
},
{
"code": null,
"e": 3027,
"s": 2545,
"text": "Inline-flex: Displays an element as an inline-level flex container. The display:inline-flex does not make flex items display inline. It makes the flex container display inline. The main difference between display: flex and display: inline-flex is that display: inline-flex will make the flex container an inline element while its content maintains its flexbox properties. In the below picture, the flex container comprises Computer, Science, Portal, and the yellow area. Example: "
},
{
"code": null,
"e": 3032,
"s": 3027,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><title>CSS inline-block</title><style> body { text-align: center; font-size: 28px; } h1 { color: green; }</style> <body> <h1>GeeksforGeeks</h1> A Online <div style=\"display:inline-flex; background-color:yellow; width:auto; height:auto\"> <div style=\"display:inline; background-color:purple;\">Computer</div> <div style=\"display:inline; background-color:orange;\">Science</div> <div style=\"display:inline; background-color:cyan;\">Portal</div> </div> for Geeks</body> </html>",
"e": 3598,
"s": 3032,
"text": null
},
{
"code": null,
"e": 3608,
"s": 3598,
"text": "Output: "
},
{
"code": null,
"e": 3862,
"s": 3608,
"text": "There is only one main difference between the inline-block and inline-flex: inline-block: Create specific block for each element under its section maintain the structure of each element. inline-flex: Does not reserved any specific space in normal form. "
},
{
"code": null,
"e": 4048,
"s": 3862,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 4063,
"s": 4050,
"text": "singghakshay"
},
{
"code": null,
"e": 4077,
"s": 4063,
"text": "johnbernalfsd"
},
{
"code": null,
"e": 4092,
"s": 4077,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4096,
"s": 4092,
"text": "CSS"
},
{
"code": null,
"e": 4113,
"s": 4096,
"text": "Web Technologies"
}
] |
Why Does BufferedReader Throw IOException in Java? | 30 Aug, 2021
IOException is a type of checked exception which occurs during input/output operation. BufferedReader is used to read data from a file, input stream, database, etc. Below is the simplified steps of how a file is read using a BufferedReader in java.
In RAM a buffered reader object is created.Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM.Now with the help of a buffered reader object our program can read the buffer in RAM.If all the lines are read then next some lines of the file are copied from secondary memory into the buffer.
In RAM a buffered reader object is created.
Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM.
Now with the help of a buffered reader object our program can read the buffer in RAM.
If all the lines are read then next some lines of the file are copied from secondary memory into the buffer.
Buffered Reader Work Flow Overview
This file system reading can fail at any time for many reasons. It may occur due to the file deleted or viruses in the file. Sometimes BufferedReader takes data from a network stream where the reading system can fail at any time.
So this type of error can occur in input operation when a BufferedReader is used. This is why a buffered reader throws IOException.
Below is an example of BufferedReader use
Input: a = 5, b = 3
Output: 8
Implementation:
Java
// This is an example of use of BufferedReader Class import java.io.*; class GFG { // Define BufferedReader object static BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // If you delete 'throws IOException' // you will get an error public static void main(String[] args) throws IOException { int a = Integer.parseInt(br.readLine()); int b = Integer.parseInt(br.readLine()); System.out.println(a + b); }}
Output:
If the file is deleted from the server-side while reading the input from the server-side, IOException is thrown.
surindertarika1234
adnanirshad158
Java-Exceptions
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "IOException is a type of checked exception which occurs during input/output operation. BufferedReader is used to read data from a file, input stream, database, etc. Below is the simplified steps of how a file is read using a BufferedReader in java."
},
{
"code": null,
"e": 619,
"s": 277,
"text": "In RAM a buffered reader object is created.Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM.Now with the help of a buffered reader object our program can read the buffer in RAM.If all the lines are read then next some lines of the file are copied from secondary memory into the buffer."
},
{
"code": null,
"e": 663,
"s": 619,
"text": "In RAM a buffered reader object is created."
},
{
"code": null,
"e": 769,
"s": 663,
"text": "Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM."
},
{
"code": null,
"e": 855,
"s": 769,
"text": "Now with the help of a buffered reader object our program can read the buffer in RAM."
},
{
"code": null,
"e": 964,
"s": 855,
"text": "If all the lines are read then next some lines of the file are copied from secondary memory into the buffer."
},
{
"code": null,
"e": 999,
"s": 964,
"text": "Buffered Reader Work Flow Overview"
},
{
"code": null,
"e": 1229,
"s": 999,
"text": "This file system reading can fail at any time for many reasons. It may occur due to the file deleted or viruses in the file. Sometimes BufferedReader takes data from a network stream where the reading system can fail at any time."
},
{
"code": null,
"e": 1361,
"s": 1229,
"text": "So this type of error can occur in input operation when a BufferedReader is used. This is why a buffered reader throws IOException."
},
{
"code": null,
"e": 1403,
"s": 1361,
"text": "Below is an example of BufferedReader use"
},
{
"code": null,
"e": 1433,
"s": 1403,
"text": "Input: a = 5, b = 3\nOutput: 8"
},
{
"code": null,
"e": 1449,
"s": 1433,
"text": "Implementation:"
},
{
"code": null,
"e": 1454,
"s": 1449,
"text": "Java"
},
{
"code": "// This is an example of use of BufferedReader Class import java.io.*; class GFG { // Define BufferedReader object static BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // If you delete 'throws IOException' // you will get an error public static void main(String[] args) throws IOException { int a = Integer.parseInt(br.readLine()); int b = Integer.parseInt(br.readLine()); System.out.println(a + b); }}",
"e": 1944,
"s": 1454,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1944,
"text": " Output:"
},
{
"code": null,
"e": 2067,
"s": 1954,
"text": "If the file is deleted from the server-side while reading the input from the server-side, IOException is thrown."
},
{
"code": null,
"e": 2088,
"s": 2069,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2103,
"s": 2088,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2119,
"s": 2103,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 2126,
"s": 2119,
"text": "Picked"
},
{
"code": null,
"e": 2150,
"s": 2126,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2155,
"s": 2150,
"text": "Java"
},
{
"code": null,
"e": 2174,
"s": 2155,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2179,
"s": 2174,
"text": "Java"
},
{
"code": null,
"e": 2277,
"s": 2179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2292,
"s": 2277,
"text": "Stream In Java"
},
{
"code": null,
"e": 2313,
"s": 2292,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2334,
"s": 2313,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2353,
"s": 2334,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2370,
"s": 2353,
"text": "Generics in Java"
},
{
"code": null,
"e": 2400,
"s": 2370,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2416,
"s": 2400,
"text": "Strings in Java"
},
{
"code": null,
"e": 2442,
"s": 2416,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2462,
"s": 2442,
"text": "Abstraction in Java"
}
] |
Eight “No-Code” Features In Python | by Christopher Tao | Towards Data Science | One of the reasons why Python become popular is that we can write relatively less code to achieve complex features. The Python developers’ community welcomes libraries that encapsulate complicated implementations with simple interfaces exposed for use.
However, that’s even not the simplest. Can you believe that we can even use Python without any code?
In this article, I’ll introduce 8 Python built-in features that we can leverage without writing any code.
Let’s start with Python CLI (Command-Line Interface) before everything. Although we don’t have to write code to use the features that will be introduced later on, we still need to let Python know what we want to execute. To do this, we can use Python CLI.
As long as we have Python installed on our machine, we can display all the supported arguments in Python CLI.
$ python --help
The screenshot shows only part of the help output because it is too long. The one I want to emphasise is the -m option. It will run a library module as a script. Therefore, if the module is implemented to support CLI, we will be able to use it directly.
Now we should begin :)
Sometimes, we would like to test the outbound network traffic to an IP:Port. Usually, telnet is a not bad choice, especially on the Windows platform. However, it is often not installed by default. We have to download and install it before use, which could be a waste if we just want a simple test and then dispose of it.
However, if you have Python installed, you don’t have to download telnet because Python already has it. Let’s try an IP of Google Search for its 443 port.
python -m telnetlib -d 142.250.70.174 443
As the screenshot is shown, the traffic is OK and we even received an empty string from Google. If we try to telnet a random port that we are not supposed to access, an error will be thrown.
python -m telnetlib -d 142.250.70.174 999
If you don’t know this before, it could be surprised I guess. Yes, we can spin up a web server using Python without writing any code. Just run the command as follows.
python -m http.server
After we run it, it shows that the server is listening to the localhost on port 8000. Then, we can try to access http://localhost:8000/ from our browser.
The web server will render our local file system using whichever path we started the server as root. In other words, we won’t be able to access any directories above the root.
Are you asking what is this used for? For example, if we have many text/PDF/image files in the directory or any sub-directories, we can very easily and quickly access them.
If you want to know more interesting usage, please check out this article.
towardsdatascience.com
If you follow the article above and turn this into a “low-code” solution, you may be able to add more customised features to it.
If you have a long JSON string without formatting, it could be difficult to read. Usually, I would prefer to use text editors such as Sublime or VS code with JSON plugins to make the string pretty. However, if we don’t have these tools handy, Python will be able to help temporarily.
Suppose we have such a JSON string. I’ll use a short one for demonstrating purposes.
echo '{"name": {"first_name":"Chris", "last_name":"Tao"} "age":33}'
Our operating systems do not recognise it, so the String will be displayed as-is. However, if we add the Python json.tool as the magic, it will be well formatted.
echo '{"name": {"first_name":"Chris", "last_name":"Tao"} "age":33}' | python -m json.tool
Oops! The JSON string is not valid, and the json.tool helped us to identify the issue. We missed a comma after the name object. Let me add the comma to make it valid.
echo '{"name": {"first_name":"Chris", "last_name":"Tao"}, "age":33}' | python -m json.tool
Now, it is output with perfect indentation! Easy to read now.
Yes, we can use Python to “create” a text editor. Of course, it is not very powerful, but it will be convenient if you don’t have a better one installed. Also, it won’t be more powerful than Vim and Nanos, but it is totally UI-based rather than a command-line text editor. This editor is created by the idlelib with Tkinter, so it is even cross-platform.
Suppose we are going to write a simple Python app to display the current time. We want to quickly write the code but don’t want to download and install a code editor. Now, let’s run this command.
mkdir get_time_apppython -m idlelib get_time_app/print_time.py
idlelib cannot create the directory if it doesn’t exist, so we need to create one if we need it. After we run this command, the print_time.py will NOT be created until we save it.
The editor should pop up now. We can write some code in it. The code can even be syntax-coloured.
Now, we can press ctrl+s to save it and then close it. Let’s go back to the command line and display the content of the file, the code is definitely there.
cat get_time_app/print_time.py
If we just want to create a simple application like the one we’ve just written above, we don’t need any 3rd party libraries such as PyInstaller. Python built-in Zipapp can help.
Suppose we want to package the “Get Time” App, we can run the command below.
python -m zipapp get_time_app -m "print_time:main"
In the command, we just need to let zipapp knows the name of the app get_time_app, the name of the Python file that will be used as the entry point print_time and the main method main.
The one with .pyz extension is the app that we just created. We can distribute it as a single file rather than a folder.
To use the packaged app, simply use python to call it.
python get_time_app.pyz
With Python CLI, we can encrypt a string or a file. Let’s start with an interesting one. Rot 13 is an encryption method that simply moves any English letters by 13 positions to the right. For example, an “a” (position: 1) will become an “n” (position: 14).
We can use encodings.rot_13 to encrypt a string as follows.
echo "I am Chris" | python -m encodings.rot_13
Of course, don’t use this for any real confidential stuff. Because there are 26 letters in English, so we can decipher the string very easily by running this algorithm again :)
echo 'V nz Puevf' | python -m encodings.rot_13
Now, let’s have a look at a more useful one, base64. We can encode a string with base64 format as follows.
echo "I am Chris" | python -m base64
Then, we can add a flag -d to decode it.
echo "SSBhbSBDaHJpcwo=" | python -m base64 -d
This will be pretty useful if we have an image file to be encoded on the fly. We can encode a file as follows.
python -m base64 get_time_app/print_time.py
It’s pretty interesting, the decoded Python script file can be executed on the fly.
echo "ZnJvbSBkYXRldGltZSBpbXBvcnQgZGF0ZXRpbWUKCgpkZWYgbWFpbigpOgogICAgY3VycmVudF90aW1lID0gZGF0ZXRpbWUubm93KCkKICAgIHByaW50KGYnQ3VycmVudCB0aW1lIGlzIHtjdXJyZW50X3RpbWV9LicpCgoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIG1haW4oKQo=" | python -m base64 -d | python
If we want to get the current system information, Python provides an easy way to do so. We can run the command below.
python -m sysconfig
All the system configuration is displayed such as the paths and environment variables. There is much more stuff displayed, the screenshot only shows a portion of it.
If we just want to display the paths and the current working directory, we can also run this command.
python -m site
We can also use Python to compress files without the need to download tar/zip/gzip. For example, if we want to compress the app we’ve just written in section 4, we can run the following command to add the folder to a zip file. In the command, the option -c stands for “create”.
python -m zipfile -c get_time_app.zip get_time_app
Of course, we can extract it as well. Let’s extract the folder and put it into a new directory so that it can be separated from the original one. In the command below, the option -e stands for “extract”.
python -m zipfile -e get_time_app.zip get_time_app_extracted
Then, we can verify it.
ls get_time_app_extractedcat get_time_app_extracted/get_time_app/print_time.py
I use zip for demonstration, while Python also supports tar and gzip.
In this article, I have introduced a way to use Python built-in libraries without writing any code. It really provides lots of conveniences if we do remember to use them. Hope you enjoyed reading this article and the content would help!
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) | [
{
"code": null,
"e": 425,
"s": 172,
"text": "One of the reasons why Python become popular is that we can write relatively less code to achieve complex features. The Python developers’ community welcomes libraries that encapsulate complicated implementations with simple interfaces exposed for use."
},
{
"code": null,
"e": 526,
"s": 425,
"text": "However, that’s even not the simplest. Can you believe that we can even use Python without any code?"
},
{
"code": null,
"e": 632,
"s": 526,
"text": "In this article, I’ll introduce 8 Python built-in features that we can leverage without writing any code."
},
{
"code": null,
"e": 888,
"s": 632,
"text": "Let’s start with Python CLI (Command-Line Interface) before everything. Although we don’t have to write code to use the features that will be introduced later on, we still need to let Python know what we want to execute. To do this, we can use Python CLI."
},
{
"code": null,
"e": 998,
"s": 888,
"text": "As long as we have Python installed on our machine, we can display all the supported arguments in Python CLI."
},
{
"code": null,
"e": 1014,
"s": 998,
"text": "$ python --help"
},
{
"code": null,
"e": 1268,
"s": 1014,
"text": "The screenshot shows only part of the help output because it is too long. The one I want to emphasise is the -m option. It will run a library module as a script. Therefore, if the module is implemented to support CLI, we will be able to use it directly."
},
{
"code": null,
"e": 1291,
"s": 1268,
"text": "Now we should begin :)"
},
{
"code": null,
"e": 1612,
"s": 1291,
"text": "Sometimes, we would like to test the outbound network traffic to an IP:Port. Usually, telnet is a not bad choice, especially on the Windows platform. However, it is often not installed by default. We have to download and install it before use, which could be a waste if we just want a simple test and then dispose of it."
},
{
"code": null,
"e": 1767,
"s": 1612,
"text": "However, if you have Python installed, you don’t have to download telnet because Python already has it. Let’s try an IP of Google Search for its 443 port."
},
{
"code": null,
"e": 1809,
"s": 1767,
"text": "python -m telnetlib -d 142.250.70.174 443"
},
{
"code": null,
"e": 2000,
"s": 1809,
"text": "As the screenshot is shown, the traffic is OK and we even received an empty string from Google. If we try to telnet a random port that we are not supposed to access, an error will be thrown."
},
{
"code": null,
"e": 2042,
"s": 2000,
"text": "python -m telnetlib -d 142.250.70.174 999"
},
{
"code": null,
"e": 2209,
"s": 2042,
"text": "If you don’t know this before, it could be surprised I guess. Yes, we can spin up a web server using Python without writing any code. Just run the command as follows."
},
{
"code": null,
"e": 2231,
"s": 2209,
"text": "python -m http.server"
},
{
"code": null,
"e": 2385,
"s": 2231,
"text": "After we run it, it shows that the server is listening to the localhost on port 8000. Then, we can try to access http://localhost:8000/ from our browser."
},
{
"code": null,
"e": 2561,
"s": 2385,
"text": "The web server will render our local file system using whichever path we started the server as root. In other words, we won’t be able to access any directories above the root."
},
{
"code": null,
"e": 2734,
"s": 2561,
"text": "Are you asking what is this used for? For example, if we have many text/PDF/image files in the directory or any sub-directories, we can very easily and quickly access them."
},
{
"code": null,
"e": 2809,
"s": 2734,
"text": "If you want to know more interesting usage, please check out this article."
},
{
"code": null,
"e": 2832,
"s": 2809,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2961,
"s": 2832,
"text": "If you follow the article above and turn this into a “low-code” solution, you may be able to add more customised features to it."
},
{
"code": null,
"e": 3245,
"s": 2961,
"text": "If you have a long JSON string without formatting, it could be difficult to read. Usually, I would prefer to use text editors such as Sublime or VS code with JSON plugins to make the string pretty. However, if we don’t have these tools handy, Python will be able to help temporarily."
},
{
"code": null,
"e": 3330,
"s": 3245,
"text": "Suppose we have such a JSON string. I’ll use a short one for demonstrating purposes."
},
{
"code": null,
"e": 3398,
"s": 3330,
"text": "echo '{\"name\": {\"first_name\":\"Chris\", \"last_name\":\"Tao\"} \"age\":33}'"
},
{
"code": null,
"e": 3561,
"s": 3398,
"text": "Our operating systems do not recognise it, so the String will be displayed as-is. However, if we add the Python json.tool as the magic, it will be well formatted."
},
{
"code": null,
"e": 3651,
"s": 3561,
"text": "echo '{\"name\": {\"first_name\":\"Chris\", \"last_name\":\"Tao\"} \"age\":33}' | python -m json.tool"
},
{
"code": null,
"e": 3818,
"s": 3651,
"text": "Oops! The JSON string is not valid, and the json.tool helped us to identify the issue. We missed a comma after the name object. Let me add the comma to make it valid."
},
{
"code": null,
"e": 3909,
"s": 3818,
"text": "echo '{\"name\": {\"first_name\":\"Chris\", \"last_name\":\"Tao\"}, \"age\":33}' | python -m json.tool"
},
{
"code": null,
"e": 3971,
"s": 3909,
"text": "Now, it is output with perfect indentation! Easy to read now."
},
{
"code": null,
"e": 4326,
"s": 3971,
"text": "Yes, we can use Python to “create” a text editor. Of course, it is not very powerful, but it will be convenient if you don’t have a better one installed. Also, it won’t be more powerful than Vim and Nanos, but it is totally UI-based rather than a command-line text editor. This editor is created by the idlelib with Tkinter, so it is even cross-platform."
},
{
"code": null,
"e": 4522,
"s": 4326,
"text": "Suppose we are going to write a simple Python app to display the current time. We want to quickly write the code but don’t want to download and install a code editor. Now, let’s run this command."
},
{
"code": null,
"e": 4585,
"s": 4522,
"text": "mkdir get_time_apppython -m idlelib get_time_app/print_time.py"
},
{
"code": null,
"e": 4765,
"s": 4585,
"text": "idlelib cannot create the directory if it doesn’t exist, so we need to create one if we need it. After we run this command, the print_time.py will NOT be created until we save it."
},
{
"code": null,
"e": 4863,
"s": 4765,
"text": "The editor should pop up now. We can write some code in it. The code can even be syntax-coloured."
},
{
"code": null,
"e": 5019,
"s": 4863,
"text": "Now, we can press ctrl+s to save it and then close it. Let’s go back to the command line and display the content of the file, the code is definitely there."
},
{
"code": null,
"e": 5050,
"s": 5019,
"text": "cat get_time_app/print_time.py"
},
{
"code": null,
"e": 5228,
"s": 5050,
"text": "If we just want to create a simple application like the one we’ve just written above, we don’t need any 3rd party libraries such as PyInstaller. Python built-in Zipapp can help."
},
{
"code": null,
"e": 5305,
"s": 5228,
"text": "Suppose we want to package the “Get Time” App, we can run the command below."
},
{
"code": null,
"e": 5356,
"s": 5305,
"text": "python -m zipapp get_time_app -m \"print_time:main\""
},
{
"code": null,
"e": 5541,
"s": 5356,
"text": "In the command, we just need to let zipapp knows the name of the app get_time_app, the name of the Python file that will be used as the entry point print_time and the main method main."
},
{
"code": null,
"e": 5662,
"s": 5541,
"text": "The one with .pyz extension is the app that we just created. We can distribute it as a single file rather than a folder."
},
{
"code": null,
"e": 5717,
"s": 5662,
"text": "To use the packaged app, simply use python to call it."
},
{
"code": null,
"e": 5741,
"s": 5717,
"text": "python get_time_app.pyz"
},
{
"code": null,
"e": 5998,
"s": 5741,
"text": "With Python CLI, we can encrypt a string or a file. Let’s start with an interesting one. Rot 13 is an encryption method that simply moves any English letters by 13 positions to the right. For example, an “a” (position: 1) will become an “n” (position: 14)."
},
{
"code": null,
"e": 6058,
"s": 5998,
"text": "We can use encodings.rot_13 to encrypt a string as follows."
},
{
"code": null,
"e": 6105,
"s": 6058,
"text": "echo \"I am Chris\" | python -m encodings.rot_13"
},
{
"code": null,
"e": 6282,
"s": 6105,
"text": "Of course, don’t use this for any real confidential stuff. Because there are 26 letters in English, so we can decipher the string very easily by running this algorithm again :)"
},
{
"code": null,
"e": 6329,
"s": 6282,
"text": "echo 'V nz Puevf' | python -m encodings.rot_13"
},
{
"code": null,
"e": 6436,
"s": 6329,
"text": "Now, let’s have a look at a more useful one, base64. We can encode a string with base64 format as follows."
},
{
"code": null,
"e": 6473,
"s": 6436,
"text": "echo \"I am Chris\" | python -m base64"
},
{
"code": null,
"e": 6514,
"s": 6473,
"text": "Then, we can add a flag -d to decode it."
},
{
"code": null,
"e": 6560,
"s": 6514,
"text": "echo \"SSBhbSBDaHJpcwo=\" | python -m base64 -d"
},
{
"code": null,
"e": 6671,
"s": 6560,
"text": "This will be pretty useful if we have an image file to be encoded on the fly. We can encode a file as follows."
},
{
"code": null,
"e": 6715,
"s": 6671,
"text": "python -m base64 get_time_app/print_time.py"
},
{
"code": null,
"e": 6799,
"s": 6715,
"text": "It’s pretty interesting, the decoded Python script file can be executed on the fly."
},
{
"code": null,
"e": 7058,
"s": 6799,
"text": "echo \"ZnJvbSBkYXRldGltZSBpbXBvcnQgZGF0ZXRpbWUKCgpkZWYgbWFpbigpOgogICAgY3VycmVudF90aW1lID0gZGF0ZXRpbWUubm93KCkKICAgIHByaW50KGYnQ3VycmVudCB0aW1lIGlzIHtjdXJyZW50X3RpbWV9LicpCgoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIG1haW4oKQo=\" | python -m base64 -d | python"
},
{
"code": null,
"e": 7176,
"s": 7058,
"text": "If we want to get the current system information, Python provides an easy way to do so. We can run the command below."
},
{
"code": null,
"e": 7196,
"s": 7176,
"text": "python -m sysconfig"
},
{
"code": null,
"e": 7362,
"s": 7196,
"text": "All the system configuration is displayed such as the paths and environment variables. There is much more stuff displayed, the screenshot only shows a portion of it."
},
{
"code": null,
"e": 7464,
"s": 7362,
"text": "If we just want to display the paths and the current working directory, we can also run this command."
},
{
"code": null,
"e": 7479,
"s": 7464,
"text": "python -m site"
},
{
"code": null,
"e": 7757,
"s": 7479,
"text": "We can also use Python to compress files without the need to download tar/zip/gzip. For example, if we want to compress the app we’ve just written in section 4, we can run the following command to add the folder to a zip file. In the command, the option -c stands for “create”."
},
{
"code": null,
"e": 7808,
"s": 7757,
"text": "python -m zipfile -c get_time_app.zip get_time_app"
},
{
"code": null,
"e": 8012,
"s": 7808,
"text": "Of course, we can extract it as well. Let’s extract the folder and put it into a new directory so that it can be separated from the original one. In the command below, the option -e stands for “extract”."
},
{
"code": null,
"e": 8073,
"s": 8012,
"text": "python -m zipfile -e get_time_app.zip get_time_app_extracted"
},
{
"code": null,
"e": 8097,
"s": 8073,
"text": "Then, we can verify it."
},
{
"code": null,
"e": 8176,
"s": 8097,
"text": "ls get_time_app_extractedcat get_time_app_extracted/get_time_app/print_time.py"
},
{
"code": null,
"e": 8246,
"s": 8176,
"text": "I use zip for demonstration, while Python also supports tar and gzip."
},
{
"code": null,
"e": 8483,
"s": 8246,
"text": "In this article, I have introduced a way to use Python built-in libraries without writing any code. It really provides lots of conveniences if we do remember to use them. Hope you enjoyed reading this article and the content would help!"
},
{
"code": null,
"e": 8494,
"s": 8483,
"text": "medium.com"
}
] |
TypeScript - Functions | Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
A function definition specifies what and how a specific task would be done.
A function must be called so as to execute it.
Functions may also return value along with control, back to the caller.
Parameters are a mechanism to pass values to functions.
Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. The syntax to declare a function with optional parameter is as given below −
function function_name (param1[:type], param2[:type], param3[:type])
function disp_details(id:number,name:string,mail_id?:string) {
console.log("ID:", id);
console.log("Name",name);
if(mail_id!=undefined)
console.log("Email Id",mail_id);
}
disp_details(123,"John");
disp_details(111,"mary","[email protected]");
The above example declares a parameterized function. Here, the third parameter, i.e., mail_id is an optional parameter.
The above example declares a parameterized function. Here, the third parameter, i.e., mail_id is an optional parameter.
If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined.
If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined.
The function prints the value of mail_id only if the argument is passed a value.
The function prints the value of mail_id only if the argument is passed a value.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
function disp_details(id, name, mail_id) {
console.log("ID:", id);
console.log("Name", name);
if (mail_id != undefined)
console.log("Email Id", mail_id);
}
disp_details(123, "John");
disp_details(111, "mary", "[email protected]");
The above code will produce the following output −
ID:123
Name John
ID: 111
Name mary
Email Id [email protected]
Rest parameters are similar to variable arguments in Java. Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type.
To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter.
function addNumbers(...nums:number[]) {
var i;
var sum:number = 0;
for(i = 0;i<nums.length;i++) {
sum = sum + nums[i];
}
console.log("sum of the numbers",sum)
}
addNumbers(1,2,3)
addNumbers(10,10,10,10,10)
The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter.
The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter.
The function is invoked twice, by passing three and six values, respectively.
The function is invoked twice, by passing three and six values, respectively.
The for loop iterates through the argument list, passed to the function and calculates their sum.
The for loop iterates through the argument list, passed to the function and calculates their sum.
On compiling, it will generate following JavaScript code −
function addNumbers() {
var nums = [];
for (var _i = 0; _i < arguments.length; _i++) {
nums[_i - 0] = arguments[_i];
}
var i;
var sum = 0;
for (i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
console.log("sum of the numbers", sum);
}
addNumbers(1, 2, 3);
addNumbers(10, 10, 10, 10, 10);
The output of the above code is as follows −
sum of numbers 6
sum of numbers 50
Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.
function function_name(param1[:type],param2[:type] = default_value) {
}
Note − A parameter cannot be declared optional and default at the same time.
function calculate_discount(price:number,rate:number = 0.50) {
var discount = price * rate;
console.log("Discount Amount: ",discount);
}
calculate_discount(1000)
calculate_discount(1000,0.30)
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
function calculate_discount(price, rate) {
if (rate === void 0) { rate = 0.50; }
var discount = price * rate;
console.log("Discount Amount: ", discount);
}
calculate_discount(1000);
calculate_discount(1000, 0.30);
Its output is as follows −
Discount amount : 500
Discount amount : 300
The example declares the function, calculate_discount. The function has two parameters - price and rate.
The example declares the function, calculate_discount. The function has two parameters - price and rate.
The value of the parameter rate is set to 0.50 by default.
The value of the parameter rate is set to 0.50 by default.
The program invokes the function, passing to it only the value of the parameter price. Here, the value of rate is 0.50 (default)
The program invokes the function, passing to it only the value of the parameter price. Here, the value of rate is 0.50 (default)
The same function is invoked, but with two arguments. The default value of rate is overwritten and is set to the value explicitly passed.
The same function is invoked, but with two arguments. The default value of rate is overwritten and is set to the value explicitly passed.
Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation.
Variables can be assigned an anonymous function. Such an expression is called a function expression.
var res = function( [arguments] ) { ... }
var msg = function() {
return "hello world";
}
console.log(msg())
On compiling, it will generate the same code in JavaScript.
It will produce the following output −
hello world
var res = function(a:number,b:number) {
return a*b;
};
console.log(res(12,2))
The anonymous function returns the product of the values passed to it.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var res = function (a, b) {
return a * b;
};
console.log(res(12, 2));
The output of the above code is as follows −
24
Function expression and function declaration are not synonymous. Unlike a function expression, a function declaration is bound by the function name.
The fundamental difference between the two is that, function declarations are parsed before their execution. On the other hand, function expressions are parsed only when the script engine encounters it during execution.
When the JavaScript parser sees a function in the main code flow, it assumes Function Declaration. When a function comes as a part of a statement, it is a Function Expression.
TypeScript also supports defining a function with the built-in JavaScript constructor called Function ().
var res = new Function( [arguments] ) { ... }.
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log(x);
The new Function() is a call to the constructor which in turn creates and returns a function reference.
On compiling, it will generate the same code in JavaScript.
The output of the above example code is as follows −
12
Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.
function factorial(number) {
if (number <= 0) { // termination case
return 1;
} else {
return (number * factorial(number - 1)); // function invokes itself
}
};
console.log(factorial(6)); // outputs 720
On compiling, it will generate the same code in JavaScript.
Here is its output −
720
(function () {
var x = "Hello!!";
console.log(x)
})() // the function invokes itself using a pair of parentheses ()
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Hello!!
Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.
There are 3 parts to a Lambda function −
Parameters − A function may optionally have parameters
Parameters − A function may optionally have parameters
The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator
The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator
Statements − represent the function’s instruction set
Statements − represent the function’s instruction set
Tip − By convention, the use of single letter parameter is encouraged for a compact and precise function declaration.
It is an anonymous function expression that points to a single line of code. Its syntax is as follows −
( [param1, parma2,...param n] )=>statement;
var foo = (x:number)=>10 + x
console.log(foo(100)) //outputs 110
The program declares a lambda expression function. The function returns the sum of 10 and the argument passed.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var foo = function (x) { return 10 + x; };
console.log(foo(100)); //outputs 110
Here is the output of the above code −
110
Lambda statement is an anonymous function declaration that points to a block of code. This syntax is used when the function body spans multiple lines. Its syntax is as follows −
( [param1, parma2,...param n] )=> {
//code block
}
var foo = (x:number)=> {
x = 10 + x
console.log(x)
}
foo(100)
The function’s reference is returned and stored in the variable foo.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var foo = function (x) {
x = 10 + x;
console.log(x);
};
foo(100);
The output of the above program is as follows −
110
It is not mandatory to specify the data type of a parameter. In such a case the data type of the parameter is any. Let us take a look at the following code snippet −
var func = (x)=> {
if(typeof x=="number") {
console.log(x+" is numeric")
} else if(typeof x=="string") {
console.log(x+" is a string")
}
}
func(12)
func("Tom")
On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var func = function (x) {
if (typeof x == "number") {
console.log(x + " is numeric");
} else if (typeof x == "string") {
console.log(x + " is a string");
}
};
func(12);
func("Tom");
Its output is as follows −
12 is numeric
Tom is a string
var display = x=> {
console.log("The function got "+x)
}
display(12)
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var display = function (x) {
console.log("The function got " + x);
};
display(12);
Its output is as follows −
The function got 12
The following example shows these two Syntactic variations.
var disp =()=> {
console.log("Function invoked");
}
disp();
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var disp = function () {
console.log("Function invoked");
};
disp();
Its output is as follows −
Function invoked
Functions have the capability to operate differently on the basis of the input provided to them. In other words, a program can have multiple methods with the same name with different implementation. This mechanism is termed as Function Overloading. TypeScript provides support for function overloading.
To overload a function in TypeScript, you need to follow the steps given below −
Step 1 − Declare multiple functions with the same name but different function signature. Function signature includes the following.
The data type of the parameter
The data type of the parameter
function disp(string):void;
function disp(number):void;
The number of parameters
The number of parameters
function disp(n1:number):void;
function disp(x:number,y:number):void;
The sequence of parameters
The sequence of parameters
function disp(n1:number,s1:string):void;
function disp(s:string,n:number):void;
Note − The function signature doesn’t include the function’s return type.
Step 2 − The declaration must be followed by the function definition. The parameter types should be set to any if the parameter types differ during overload. Additionally, for case b explained above, you may consider marking one or more parameters as optional during the function definition.
Step 3 − Finally, you must invoke the function to make it functional.
Let us now take a look at the following example code −
function disp(s1:string):void;
function disp(n1:number,s1:string):void;
function disp(x:any,y?:any):void {
console.log(x);
console.log(y);
}
disp("abc")
disp(1,"xyz");
The first two lines depict the function overload declaration. The function has two overloads −
Function that accepts a single string parameter.
Function that accepts two values of type number and string respectively.
The first two lines depict the function overload declaration. The function has two overloads −
Function that accepts a single string parameter.
Function that accepts a single string parameter.
Function that accepts two values of type number and string respectively.
Function that accepts two values of type number and string respectively.
The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here.
The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here.
The overloaded function is invoked by the last two statements.
The overloaded function is invoked by the last two statements.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
function disp(x, y) {
console.log(x);
console.log(y);
}
disp("abc");
disp(1, "xyz");
The above code will produce the following output −
abc
1
xyz
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2408,
"s": 2048,
"text": "Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code."
},
{
"code": null,
"e": 2568,
"s": 2408,
"text": "A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function."
},
{
"code": null,
"e": 2644,
"s": 2568,
"text": "A function definition specifies what and how a specific task would be done."
},
{
"code": null,
"e": 2691,
"s": 2644,
"text": "A function must be called so as to execute it."
},
{
"code": null,
"e": 2763,
"s": 2691,
"text": "Functions may also return value along with control, back to the caller."
},
{
"code": null,
"e": 2819,
"s": 2763,
"text": "Parameters are a mechanism to pass values to functions."
},
{
"code": null,
"e": 3153,
"s": 2819,
"text": "Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. The syntax to declare a function with optional parameter is as given below −"
},
{
"code": null,
"e": 3223,
"s": 3153,
"text": "function function_name (param1[:type], param2[:type], param3[:type])\n"
},
{
"code": null,
"e": 3484,
"s": 3223,
"text": "function disp_details(id:number,name:string,mail_id?:string) { \n console.log(\"ID:\", id); \n console.log(\"Name\",name); \n \n if(mail_id!=undefined) \n console.log(\"Email Id\",mail_id); \n}\ndisp_details(123,\"John\");\ndisp_details(111,\"mary\",\"[email protected]\");\n"
},
{
"code": null,
"e": 3604,
"s": 3484,
"text": "The above example declares a parameterized function. Here, the third parameter, i.e., mail_id is an optional parameter."
},
{
"code": null,
"e": 3724,
"s": 3604,
"text": "The above example declares a parameterized function. Here, the third parameter, i.e., mail_id is an optional parameter."
},
{
"code": null,
"e": 3840,
"s": 3724,
"text": "If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined."
},
{
"code": null,
"e": 3956,
"s": 3840,
"text": "If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined."
},
{
"code": null,
"e": 4037,
"s": 3956,
"text": "The function prints the value of mail_id only if the argument is passed a value."
},
{
"code": null,
"e": 4118,
"s": 4037,
"text": "The function prints the value of mail_id only if the argument is passed a value."
},
{
"code": null,
"e": 4177,
"s": 4118,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 4454,
"s": 4177,
"text": "//Generated by typescript 1.8.10\nfunction disp_details(id, name, mail_id) {\n console.log(\"ID:\", id);\n console.log(\"Name\", name);\n\t\n if (mail_id != undefined)\n console.log(\"Email Id\", mail_id);\n}\ndisp_details(123, \"John\");\ndisp_details(111, \"mary\", \"[email protected]\");\n"
},
{
"code": null,
"e": 4505,
"s": 4454,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 4568,
"s": 4505,
"text": "ID:123 \nName John \nID: 111 \nName mary \nEmail Id [email protected]\n"
},
{
"code": null,
"e": 4862,
"s": 4568,
"text": "Rest parameters are similar to variable arguments in Java. Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type."
},
{
"code": null,
"e": 5003,
"s": 4862,
"text": "To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter."
},
{
"code": null,
"e": 5247,
"s": 5003,
"text": "function addNumbers(...nums:number[]) { \n var i; \n var sum:number = 0; \n \n for(i = 0;i<nums.length;i++) { \n sum = sum + nums[i]; \n } \n console.log(\"sum of the numbers\",sum) \n} \naddNumbers(1,2,3) \naddNumbers(10,10,10,10,10)\n"
},
{
"code": null,
"e": 5435,
"s": 5247,
"text": "The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter."
},
{
"code": null,
"e": 5623,
"s": 5435,
"text": "The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter."
},
{
"code": null,
"e": 5701,
"s": 5623,
"text": "The function is invoked twice, by passing three and six values, respectively."
},
{
"code": null,
"e": 5779,
"s": 5701,
"text": "The function is invoked twice, by passing three and six values, respectively."
},
{
"code": null,
"e": 5877,
"s": 5779,
"text": "The for loop iterates through the argument list, passed to the function and calculates their sum."
},
{
"code": null,
"e": 5975,
"s": 5877,
"text": "The for loop iterates through the argument list, passed to the function and calculates their sum."
},
{
"code": null,
"e": 6034,
"s": 5975,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 6364,
"s": 6034,
"text": "function addNumbers() {\n var nums = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n nums[_i - 0] = arguments[_i];\n }\n\tvar i;\n var sum = 0;\n\t\n for (i = 0; i < nums.length; i++) {\n sum = sum + nums[i];\n }\n console.log(\"sum of the numbers\", sum);\n}\naddNumbers(1, 2, 3);\naddNumbers(10, 10, 10, 10, 10);\n"
},
{
"code": null,
"e": 6409,
"s": 6364,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 6446,
"s": 6409,
"text": "sum of numbers 6 \nsum of numbers 50\n"
},
{
"code": null,
"e": 6569,
"s": 6446,
"text": "Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values."
},
{
"code": null,
"e": 6643,
"s": 6569,
"text": "function function_name(param1[:type],param2[:type] = default_value) { \n}\n"
},
{
"code": null,
"e": 6720,
"s": 6643,
"text": "Note − A parameter cannot be declared optional and default at the same time."
},
{
"code": null,
"e": 6924,
"s": 6720,
"text": "function calculate_discount(price:number,rate:number = 0.50) { \n var discount = price * rate; \n console.log(\"Discount Amount: \",discount); \n} \ncalculate_discount(1000) \ncalculate_discount(1000,0.30)\n"
},
{
"code": null,
"e": 6983,
"s": 6924,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 7240,
"s": 6983,
"text": "//Generated by typescript 1.8.10\nfunction calculate_discount(price, rate) {\n if (rate === void 0) { rate = 0.50; }\n var discount = price * rate;\n console.log(\"Discount Amount: \", discount);\n}\ncalculate_discount(1000);\ncalculate_discount(1000, 0.30);\n"
},
{
"code": null,
"e": 7267,
"s": 7240,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7313,
"s": 7267,
"text": "Discount amount : 500 \nDiscount amount : 300\n"
},
{
"code": null,
"e": 7418,
"s": 7313,
"text": "The example declares the function, calculate_discount. The function has two parameters - price and rate."
},
{
"code": null,
"e": 7523,
"s": 7418,
"text": "The example declares the function, calculate_discount. The function has two parameters - price and rate."
},
{
"code": null,
"e": 7582,
"s": 7523,
"text": "The value of the parameter rate is set to 0.50 by default."
},
{
"code": null,
"e": 7641,
"s": 7582,
"text": "The value of the parameter rate is set to 0.50 by default."
},
{
"code": null,
"e": 7770,
"s": 7641,
"text": "The program invokes the function, passing to it only the value of the parameter price. Here, the value of rate is 0.50 (default)"
},
{
"code": null,
"e": 7899,
"s": 7770,
"text": "The program invokes the function, passing to it only the value of the parameter price. Here, the value of rate is 0.50 (default)"
},
{
"code": null,
"e": 8037,
"s": 7899,
"text": "The same function is invoked, but with two arguments. The default value of rate is overwritten and is set to the value explicitly passed."
},
{
"code": null,
"e": 8175,
"s": 8037,
"text": "The same function is invoked, but with two arguments. The default value of rate is overwritten and is set to the value explicitly passed."
},
{
"code": null,
"e": 8490,
"s": 8175,
"text": "Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation."
},
{
"code": null,
"e": 8591,
"s": 8490,
"text": "Variables can be assigned an anonymous function. Such an expression is called a function expression."
},
{
"code": null,
"e": 8634,
"s": 8591,
"text": "var res = function( [arguments] ) { ... }\n"
},
{
"code": null,
"e": 8708,
"s": 8634,
"text": "var msg = function() { \n return \"hello world\"; \n} \nconsole.log(msg())\n"
},
{
"code": null,
"e": 8768,
"s": 8708,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 8807,
"s": 8768,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 8820,
"s": 8807,
"text": "hello world\n"
},
{
"code": null,
"e": 8907,
"s": 8820,
"text": "var res = function(a:number,b:number) { \n return a*b; \n}; \nconsole.log(res(12,2)) \n"
},
{
"code": null,
"e": 8978,
"s": 8907,
"text": "The anonymous function returns the product of the values passed to it."
},
{
"code": null,
"e": 9037,
"s": 8978,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 9144,
"s": 9037,
"text": "//Generated by typescript 1.8.10\nvar res = function (a, b) {\n return a * b;\n};\nconsole.log(res(12, 2));\n"
},
{
"code": null,
"e": 9189,
"s": 9144,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 9193,
"s": 9189,
"text": "24\n"
},
{
"code": null,
"e": 9342,
"s": 9193,
"text": "Function expression and function declaration are not synonymous. Unlike a function expression, a function declaration is bound by the function name."
},
{
"code": null,
"e": 9562,
"s": 9342,
"text": "The fundamental difference between the two is that, function declarations are parsed before their execution. On the other hand, function expressions are parsed only when the script engine encounters it during execution."
},
{
"code": null,
"e": 9738,
"s": 9562,
"text": "When the JavaScript parser sees a function in the main code flow, it assumes Function Declaration. When a function comes as a part of a statement, it is a Function Expression."
},
{
"code": null,
"e": 9844,
"s": 9738,
"text": "TypeScript also supports defining a function with the built-in JavaScript constructor called Function ()."
},
{
"code": null,
"e": 9892,
"s": 9844,
"text": "var res = new Function( [arguments] ) { ... }.\n"
},
{
"code": null,
"e": 9994,
"s": 9892,
"text": "var myFunction = new Function(\"a\", \"b\", \"return a * b\"); \nvar x = myFunction(4, 3); \nconsole.log(x);\n"
},
{
"code": null,
"e": 10098,
"s": 9994,
"text": "The new Function() is a call to the constructor which in turn creates and returns a function reference."
},
{
"code": null,
"e": 10158,
"s": 10098,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 10211,
"s": 10158,
"text": "The output of the above example code is as follows −"
},
{
"code": null,
"e": 10216,
"s": 10211,
"text": "12 \n"
},
{
"code": null,
"e": 10473,
"s": 10216,
"text": "Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop."
},
{
"code": null,
"e": 10723,
"s": 10473,
"text": "function factorial(number) {\n if (number <= 0) { // termination case\n return 1; \n } else { \n return (number * factorial(number - 1)); // function invokes itself\n } \n}; \nconsole.log(factorial(6)); // outputs 720 \n"
},
{
"code": null,
"e": 10783,
"s": 10723,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 10804,
"s": 10783,
"text": "Here is its output −"
},
{
"code": null,
"e": 10809,
"s": 10804,
"text": "720\n"
},
{
"code": null,
"e": 10946,
"s": 10809,
"text": "(function () { \n var x = \"Hello!!\"; \n console.log(x) \n})() // the function invokes itself using a pair of parentheses ()\n"
},
{
"code": null,
"e": 11006,
"s": 10946,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 11033,
"s": 11006,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 11042,
"s": 11033,
"text": "Hello!!\n"
},
{
"code": null,
"e": 11222,
"s": 11042,
"text": "Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions."
},
{
"code": null,
"e": 11263,
"s": 11222,
"text": "There are 3 parts to a Lambda function −"
},
{
"code": null,
"e": 11318,
"s": 11263,
"text": "Parameters − A function may optionally have parameters"
},
{
"code": null,
"e": 11373,
"s": 11318,
"text": "Parameters − A function may optionally have parameters"
},
{
"code": null,
"e": 11461,
"s": 11373,
"text": "The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator"
},
{
"code": null,
"e": 11549,
"s": 11461,
"text": "The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator"
},
{
"code": null,
"e": 11603,
"s": 11549,
"text": "Statements − represent the function’s instruction set"
},
{
"code": null,
"e": 11657,
"s": 11603,
"text": "Statements − represent the function’s instruction set"
},
{
"code": null,
"e": 11775,
"s": 11657,
"text": "Tip − By convention, the use of single letter parameter is encouraged for a compact and precise function declaration."
},
{
"code": null,
"e": 11879,
"s": 11775,
"text": "It is an anonymous function expression that points to a single line of code. Its syntax is as follows −"
},
{
"code": null,
"e": 11924,
"s": 11879,
"text": "( [param1, parma2,...param n] )=>statement;\n"
},
{
"code": null,
"e": 11997,
"s": 11924,
"text": "var foo = (x:number)=>10 + x \nconsole.log(foo(100)) //outputs 110 \n"
},
{
"code": null,
"e": 12108,
"s": 11997,
"text": "The program declares a lambda expression function. The function returns the sum of 10 and the argument passed."
},
{
"code": null,
"e": 12166,
"s": 12108,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 12285,
"s": 12166,
"text": "//Generated by typescript 1.8.10\nvar foo = function (x) { return 10 + x; };\nconsole.log(foo(100)); //outputs 110\n"
},
{
"code": null,
"e": 12324,
"s": 12285,
"text": "Here is the output of the above code −"
},
{
"code": null,
"e": 12329,
"s": 12324,
"text": "110\n"
},
{
"code": null,
"e": 12507,
"s": 12329,
"text": "Lambda statement is an anonymous function declaration that points to a block of code. This syntax is used when the function body spans multiple lines. Its syntax is as follows −"
},
{
"code": null,
"e": 12564,
"s": 12507,
"text": "( [param1, parma2,...param n] )=> {\n \n //code block\n}\n"
},
{
"code": null,
"e": 12641,
"s": 12564,
"text": "var foo = (x:number)=> { \n x = 10 + x \n console.log(x) \n} \nfoo(100)\n"
},
{
"code": null,
"e": 12710,
"s": 12641,
"text": "The function’s reference is returned and stored in the variable foo."
},
{
"code": null,
"e": 12769,
"s": 12710,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 12875,
"s": 12769,
"text": "//Generated by typescript 1.8.10\nvar foo = function (x) {\n x = 10 + x;\n console.log(x);\n};\nfoo(100);\n"
},
{
"code": null,
"e": 12923,
"s": 12875,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 12928,
"s": 12923,
"text": "110\n"
},
{
"code": null,
"e": 13094,
"s": 12928,
"text": "It is not mandatory to specify the data type of a parameter. In such a case the data type of the parameter is any. Let us take a look at the following code snippet −"
},
{
"code": null,
"e": 13285,
"s": 13094,
"text": "var func = (x)=> { \n if(typeof x==\"number\") { \n console.log(x+\" is numeric\") \n } else if(typeof x==\"string\") { \n console.log(x+\" is a string\") \n } \n} \nfunc(12) \nfunc(\"Tom\")\n"
},
{
"code": null,
"e": 13348,
"s": 13285,
"text": "On compiling, it will generate the following JavaScript code −"
},
{
"code": null,
"e": 13585,
"s": 13348,
"text": "//Generated by typescript 1.8.10\nvar func = function (x) {\n if (typeof x == \"number\") {\n console.log(x + \" is numeric\");\n } else if (typeof x == \"string\") {\n console.log(x + \" is a string\");\n }\n};\nfunc(12);\nfunc(\"Tom\");\n"
},
{
"code": null,
"e": 13612,
"s": 13585,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 13644,
"s": 13612,
"text": "12 is numeric \nTom is a string\n"
},
{
"code": null,
"e": 13720,
"s": 13644,
"text": "var display = x=> { \n console.log(\"The function got \"+x) \n} \ndisplay(12)\n"
},
{
"code": null,
"e": 13779,
"s": 13720,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 13899,
"s": 13779,
"text": "//Generated by typescript 1.8.10\nvar display = function (x) {\n console.log(\"The function got \" + x);\n};\ndisplay(12);\n"
},
{
"code": null,
"e": 13926,
"s": 13899,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 13947,
"s": 13926,
"text": "The function got 12\n"
},
{
"code": null,
"e": 14007,
"s": 13947,
"text": "The following example shows these two Syntactic variations."
},
{
"code": null,
"e": 14074,
"s": 14007,
"text": "var disp =()=> { \n console.log(\"Function invoked\"); \n} \ndisp();\n"
},
{
"code": null,
"e": 14133,
"s": 14074,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 14239,
"s": 14133,
"text": "//Generated by typescript 1.8.10\nvar disp = function () {\n console.log(\"Function invoked\");\n};\ndisp();\n"
},
{
"code": null,
"e": 14266,
"s": 14239,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 14284,
"s": 14266,
"text": "Function invoked\n"
},
{
"code": null,
"e": 14587,
"s": 14284,
"text": "Functions have the capability to operate differently on the basis of the input provided to them. In other words, a program can have multiple methods with the same name with different implementation. This mechanism is termed as Function Overloading. TypeScript provides support for function overloading."
},
{
"code": null,
"e": 14668,
"s": 14587,
"text": "To overload a function in TypeScript, you need to follow the steps given below −"
},
{
"code": null,
"e": 14800,
"s": 14668,
"text": "Step 1 − Declare multiple functions with the same name but different function signature. Function signature includes the following."
},
{
"code": null,
"e": 14831,
"s": 14800,
"text": "The data type of the parameter"
},
{
"code": null,
"e": 14862,
"s": 14831,
"text": "The data type of the parameter"
},
{
"code": null,
"e": 14920,
"s": 14862,
"text": "function disp(string):void; \nfunction disp(number):void;\n"
},
{
"code": null,
"e": 14945,
"s": 14920,
"text": "The number of parameters"
},
{
"code": null,
"e": 14970,
"s": 14945,
"text": "The number of parameters"
},
{
"code": null,
"e": 15042,
"s": 14970,
"text": "function disp(n1:number):void; \nfunction disp(x:number,y:number):void;\n"
},
{
"code": null,
"e": 15069,
"s": 15042,
"text": "The sequence of parameters"
},
{
"code": null,
"e": 15096,
"s": 15069,
"text": "The sequence of parameters"
},
{
"code": null,
"e": 15178,
"s": 15096,
"text": "function disp(n1:number,s1:string):void; \nfunction disp(s:string,n:number):void;\n"
},
{
"code": null,
"e": 15252,
"s": 15178,
"text": "Note − The function signature doesn’t include the function’s return type."
},
{
"code": null,
"e": 15544,
"s": 15252,
"text": "Step 2 − The declaration must be followed by the function definition. The parameter types should be set to any if the parameter types differ during overload. Additionally, for case b explained above, you may consider marking one or more parameters as optional during the function definition."
},
{
"code": null,
"e": 15614,
"s": 15544,
"text": "Step 3 − Finally, you must invoke the function to make it functional."
},
{
"code": null,
"e": 15669,
"s": 15614,
"text": "Let us now take a look at the following example code −"
},
{
"code": null,
"e": 15852,
"s": 15669,
"text": "function disp(s1:string):void; \nfunction disp(n1:number,s1:string):void; \n\nfunction disp(x:any,y?:any):void { \n console.log(x); \n console.log(y); \n} \ndisp(\"abc\") \ndisp(1,\"xyz\");\n"
},
{
"code": null,
"e": 16072,
"s": 15852,
"text": "The first two lines depict the function overload declaration. The function has two overloads −\n\nFunction that accepts a single string parameter.\nFunction that accepts two values of type number and string respectively.\n\n"
},
{
"code": null,
"e": 16167,
"s": 16072,
"text": "The first two lines depict the function overload declaration. The function has two overloads −"
},
{
"code": null,
"e": 16216,
"s": 16167,
"text": "Function that accepts a single string parameter."
},
{
"code": null,
"e": 16265,
"s": 16216,
"text": "Function that accepts a single string parameter."
},
{
"code": null,
"e": 16338,
"s": 16265,
"text": "Function that accepts two values of type number and string respectively."
},
{
"code": null,
"e": 16411,
"s": 16338,
"text": "Function that accepts two values of type number and string respectively."
},
{
"code": null,
"e": 16545,
"s": 16411,
"text": "The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here."
},
{
"code": null,
"e": 16679,
"s": 16545,
"text": "The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here."
},
{
"code": null,
"e": 16742,
"s": 16679,
"text": "The overloaded function is invoked by the last two statements."
},
{
"code": null,
"e": 16805,
"s": 16742,
"text": "The overloaded function is invoked by the last two statements."
},
{
"code": null,
"e": 16864,
"s": 16805,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 16989,
"s": 16864,
"text": "//Generated by typescript 1.8.10\nfunction disp(x, y) {\n console.log(x);\n console.log(y);\n}\ndisp(\"abc\");\ndisp(1, \"xyz\");\n"
},
{
"code": null,
"e": 17040,
"s": 16989,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 17054,
"s": 17040,
"text": "abc \n1 \nxyz \n"
},
{
"code": null,
"e": 17087,
"s": 17054,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 17101,
"s": 17087,
"text": " Antonio Papa"
},
{
"code": null,
"e": 17134,
"s": 17101,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 17148,
"s": 17134,
"text": " Haider Malik"
},
{
"code": null,
"e": 17183,
"s": 17148,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 17203,
"s": 17183,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 17236,
"s": 17203,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 17250,
"s": 17236,
"text": " Sean Bradley"
},
{
"code": null,
"e": 17285,
"s": 17250,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 17301,
"s": 17285,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 17334,
"s": 17301,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 17354,
"s": 17334,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 17361,
"s": 17354,
"text": " Print"
},
{
"code": null,
"e": 17372,
"s": 17361,
"text": " Add Notes"
}
] |
Prime numbers in a range - JavaScript | We are required to write a JavaScript function that takes in two numbers, say, a and b and returns the total number of prime numbers between a and b (including a and b, if they are prime).
For example −
If a = 2, and b = 21, the prime numbers between them are 2, 3, 5, 7, 11, 13, 17, 19
And their count is 8. Our function should return 8.
Let’s write the code for this function −
Following is the code −
const isPrime = num => {
let count = 2;
while(count < (num / 2)+1){
if(num % count !== 0){
count++;
continue;
};
return false;
};
return true;
};
const primeBetween = (a, b) => {
let count = 0;
for(let i = Math.min(a, b); i <= Math.max(a, b); i++){
if(isPrime(i)){
count++;
};
};
return count;
};
console.log(primeBetween(2, 21));
Following is the output in the console −
8 | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in two numbers, say, a and b and returns the total number of prime numbers between a and b (including a and b, if they are prime)."
},
{
"code": null,
"e": 1265,
"s": 1251,
"text": "For example −"
},
{
"code": null,
"e": 1349,
"s": 1265,
"text": "If a = 2, and b = 21, the prime numbers between them are 2, 3, 5, 7, 11, 13, 17, 19"
},
{
"code": null,
"e": 1401,
"s": 1349,
"text": "And their count is 8. Our function should return 8."
},
{
"code": null,
"e": 1442,
"s": 1401,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 1466,
"s": 1442,
"text": "Following is the code −"
},
{
"code": null,
"e": 1878,
"s": 1466,
"text": "const isPrime = num => {\n let count = 2;\n while(count < (num / 2)+1){\n if(num % count !== 0){\n count++;\n continue;\n };\n return false;\n };\n return true;\n};\nconst primeBetween = (a, b) => {\n let count = 0;\n for(let i = Math.min(a, b); i <= Math.max(a, b); i++){\n if(isPrime(i)){\n count++;\n };\n };\n return count;\n};\nconsole.log(primeBetween(2, 21));"
},
{
"code": null,
"e": 1919,
"s": 1878,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1921,
"s": 1919,
"text": "8"
}
] |
How to get YouTube video ID with PHP Regex ? - GeeksforGeeks | 21 Oct, 2021
YouTube ID is a string of 11 characters, which consists of both upper and lower case alphabets and numeric values. It is used to define a YouTube video uniquely. A link to any YouTube video consists of its YouTube ID in a query format whose variable is generally written as ‘v’ or ‘vi’ or can be represented as ‘youtu.be/’ . Examples of YouTube ID from the link given below:
https://youtu.be/hjGD08xfg9c
https://www.youtube.com/watch?v=hjGD08xfg9c
https://www.youtube.com/watch?vi=hjGD08xfg9c
https://www.youtube.com/?v=hjGD08xfg9c
https://www.youtube.com/?vi=hjGD08xfg9c
In all these urls’s the string ‘hjGD08xfg9c’ is the YouTube ID. Now using this knowledge, a regular expression can be built for fetching the YouTube ID from a given link in PHP.Regex: Now we know that there are five basic formats in which we can get a YouTube ID i.e. by v= or vi= or v/ or vi/ or youtu.be/. So as the query starts from ‘?’ or ‘yout.be/’, start regex by ‘?’ or look for ‘yout.be/’. It will ignore the URL part before ‘?’ or ‘yout.be/’. After that search for ‘v=’ or ‘vi=’ and store the next 11 characters and print it.According to this logic the regex will be
preg_match_all("#(?<=v=|v\/|vi=|vi\/|youtu.be\/)[a-zA-Z0-9_-]{11}#", $url, $match);
Example: This example will show the YouTube ID in which input will be the link to YouTube.
php
<?php$url = 'https://youtu.be/hjGD08xfg9c
Array
(
[0] => hjGD08xfg9c
[1] => hjGD08xfg9c
[2] => hjGD08xfg9c
[3] => hjGD08xfg9c
[4] => hjGD08xfg9c
)
Alternative: Instead of using regular expression we can access the variable or the query by using two functions that are parse_str() and parse_url(). The parse_str() takes parse_url() and an output variable as parameters and puts all the query values of the url in the output variable. The parse_url() takes the url in string format and an integer value and returns the list of different properties within the url depending on the value of integer passed. Example:
php
<?php // Store the URL into variable$url = 'https://www.youtube.com/watch?v=hjGD08xfg9c';$url1='https://www.youtube.com/?vi=hjGD08xfg9c'; // Use parse_str() function to parse the query stringparse_str( parse_url( $url, PHP_URL_QUERY ), $youtube_id_v );parse_str( parse_url( $url1, PHP_URL_QUERY ), $youtube_id_vi ); // Display the outputecho $youtube_id_v['v'] . "\n";echo $youtube_id_vi['vi']; ?>
hjGD08xfg9c
hjGD08xfg9c
adnanirshad158
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP? | [
{
"code": null,
"e": 24966,
"s": 24938,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 25343,
"s": 24966,
"text": "YouTube ID is a string of 11 characters, which consists of both upper and lower case alphabets and numeric values. It is used to define a YouTube video uniquely. A link to any YouTube video consists of its YouTube ID in a query format whose variable is generally written as ‘v’ or ‘vi’ or can be represented as ‘youtu.be/’ . Examples of YouTube ID from the link given below: "
},
{
"code": null,
"e": 25372,
"s": 25343,
"text": "https://youtu.be/hjGD08xfg9c"
},
{
"code": null,
"e": 25416,
"s": 25372,
"text": "https://www.youtube.com/watch?v=hjGD08xfg9c"
},
{
"code": null,
"e": 25461,
"s": 25416,
"text": "https://www.youtube.com/watch?vi=hjGD08xfg9c"
},
{
"code": null,
"e": 25500,
"s": 25461,
"text": "https://www.youtube.com/?v=hjGD08xfg9c"
},
{
"code": null,
"e": 25540,
"s": 25500,
"text": "https://www.youtube.com/?vi=hjGD08xfg9c"
},
{
"code": null,
"e": 26118,
"s": 25540,
"text": "In all these urls’s the string ‘hjGD08xfg9c’ is the YouTube ID. Now using this knowledge, a regular expression can be built for fetching the YouTube ID from a given link in PHP.Regex: Now we know that there are five basic formats in which we can get a YouTube ID i.e. by v= or vi= or v/ or vi/ or youtu.be/. So as the query starts from ‘?’ or ‘yout.be/’, start regex by ‘?’ or look for ‘yout.be/’. It will ignore the URL part before ‘?’ or ‘yout.be/’. After that search for ‘v=’ or ‘vi=’ and store the next 11 characters and print it.According to this logic the regex will be "
},
{
"code": null,
"e": 26202,
"s": 26118,
"text": "preg_match_all(\"#(?<=v=|v\\/|vi=|vi\\/|youtu.be\\/)[a-zA-Z0-9_-]{11}#\", $url, $match);"
},
{
"code": null,
"e": 26295,
"s": 26202,
"text": "Example: This example will show the YouTube ID in which input will be the link to YouTube. "
},
{
"code": null,
"e": 26299,
"s": 26295,
"text": "php"
},
{
"code": "<?php$url = 'https://youtu.be/hjGD08xfg9c",
"e": 26341,
"s": 26299,
"text": null
},
{
"code": null,
"e": 26466,
"s": 26341,
"text": "Array\n(\n [0] => hjGD08xfg9c\n [1] => hjGD08xfg9c\n [2] => hjGD08xfg9c\n [3] => hjGD08xfg9c\n [4] => hjGD08xfg9c\n)"
},
{
"code": null,
"e": 26935,
"s": 26468,
"text": "Alternative: Instead of using regular expression we can access the variable or the query by using two functions that are parse_str() and parse_url(). The parse_str() takes parse_url() and an output variable as parameters and puts all the query values of the url in the output variable. The parse_url() takes the url in string format and an integer value and returns the list of different properties within the url depending on the value of integer passed. Example: "
},
{
"code": null,
"e": 26939,
"s": 26935,
"text": "php"
},
{
"code": "<?php // Store the URL into variable$url = 'https://www.youtube.com/watch?v=hjGD08xfg9c';$url1='https://www.youtube.com/?vi=hjGD08xfg9c'; // Use parse_str() function to parse the query stringparse_str( parse_url( $url, PHP_URL_QUERY ), $youtube_id_v );parse_str( parse_url( $url1, PHP_URL_QUERY ), $youtube_id_vi ); // Display the outputecho $youtube_id_v['v'] . \"\\n\";echo $youtube_id_vi['vi']; ?>",
"e": 27337,
"s": 26939,
"text": null
},
{
"code": null,
"e": 27361,
"s": 27337,
"text": "hjGD08xfg9c\nhjGD08xfg9c"
},
{
"code": null,
"e": 27378,
"s": 27363,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27385,
"s": 27378,
"text": "Picked"
},
{
"code": null,
"e": 27389,
"s": 27385,
"text": "PHP"
},
{
"code": null,
"e": 27402,
"s": 27389,
"text": "PHP Programs"
},
{
"code": null,
"e": 27419,
"s": 27402,
"text": "Web Technologies"
},
{
"code": null,
"e": 27446,
"s": 27419,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27450,
"s": 27446,
"text": "PHP"
},
{
"code": null,
"e": 27548,
"s": 27450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27598,
"s": 27548,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27638,
"s": 27598,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27699,
"s": 27638,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 27749,
"s": 27699,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 27776,
"s": 27749,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 27826,
"s": 27776,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27866,
"s": 27826,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27918,
"s": 27866,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 27979,
"s": 27918,
"text": "How to Upload Image into Database and Display it using PHP ?"
}
] |
Design and Analysis Insertion Sort | Insertion sort is a very simple method to sort numbers in an ascending or descending order. This method follows the incremental method. It can be compared with the technique how cards are sorted at the time of playing a game.
The numbers, which are needed to be sorted, are known as keys. Here is the algorithm of the insertion sort method.
Algorithm: Insertion-Sort(A)
for j = 2 to A.length
key = A[j]
i = j – 1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
Run time of this algorithm is very much dependent on the given input.
If the given numbers are sorted, this algorithm runs in O(n) time. If the given numbers are in reverse order, the algorithm runs in O(n2) time.
Unsorted list:
1st iteration:
Key = a[2] = 13
a[1] = 2 < 13
Swap, no swap
2nd iteration:
Key = a[3] = 5
a[2] = 13 > 5
Swap 5 and 13
Next, a[1] = 2 < 13
Swap, no swap
3rd iteration:
Key = a[4] = 18
a[3] = 13 < 18,
a[2] = 5 < 18,
a[1] = 2 < 18
Swap, no swap
4th iteration:
Key = a[5] = 14
a[4] = 18 > 14
Swap 18 and 14
Next, a[3] = 13 < 14,
a[2] = 5 < 14,
a[1] = 2 < 14
So, no swap
Finally,
the sorted list is
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2825,
"s": 2599,
"text": "Insertion sort is a very simple method to sort numbers in an ascending or descending order. This method follows the incremental method. It can be compared with the technique how cards are sorted at the time of playing a game."
},
{
"code": null,
"e": 2940,
"s": 2825,
"text": "The numbers, which are needed to be sorted, are known as keys. Here is the algorithm of the insertion sort method."
},
{
"code": null,
"e": 3112,
"s": 2940,
"text": "Algorithm: Insertion-Sort(A) \nfor j = 2 to A.length \n key = A[j] \n i = j – 1 \n while i > 0 and A[i] > key \n A[i + 1] = A[i] \n i = i -1 \n A[i + 1] = key \n"
},
{
"code": null,
"e": 3182,
"s": 3112,
"text": "Run time of this algorithm is very much dependent on the given input."
},
{
"code": null,
"e": 3326,
"s": 3182,
"text": "If the given numbers are sorted, this algorithm runs in O(n) time. If the given numbers are in reverse order, the algorithm runs in O(n2) time."
},
{
"code": null,
"e": 3341,
"s": 3326,
"text": "Unsorted list:"
},
{
"code": null,
"e": 3356,
"s": 3341,
"text": "1st iteration:"
},
{
"code": null,
"e": 3372,
"s": 3356,
"text": "Key = a[2] = 13"
},
{
"code": null,
"e": 3386,
"s": 3372,
"text": "a[1] = 2 < 13"
},
{
"code": null,
"e": 3400,
"s": 3386,
"text": "Swap, no swap"
},
{
"code": null,
"e": 3415,
"s": 3400,
"text": "2nd iteration:"
},
{
"code": null,
"e": 3430,
"s": 3415,
"text": "Key = a[3] = 5"
},
{
"code": null,
"e": 3444,
"s": 3430,
"text": "a[2] = 13 > 5"
},
{
"code": null,
"e": 3458,
"s": 3444,
"text": "Swap 5 and 13"
},
{
"code": null,
"e": 3478,
"s": 3458,
"text": "Next, a[1] = 2 < 13"
},
{
"code": null,
"e": 3492,
"s": 3478,
"text": "Swap, no swap"
},
{
"code": null,
"e": 3507,
"s": 3492,
"text": "3rd iteration:"
},
{
"code": null,
"e": 3523,
"s": 3507,
"text": "Key = a[4] = 18"
},
{
"code": null,
"e": 3539,
"s": 3523,
"text": "a[3] = 13 < 18,"
},
{
"code": null,
"e": 3554,
"s": 3539,
"text": "a[2] = 5 < 18,"
},
{
"code": null,
"e": 3568,
"s": 3554,
"text": "a[1] = 2 < 18"
},
{
"code": null,
"e": 3582,
"s": 3568,
"text": "Swap, no swap"
},
{
"code": null,
"e": 3597,
"s": 3582,
"text": "4th iteration:"
},
{
"code": null,
"e": 3613,
"s": 3597,
"text": "Key = a[5] = 14"
},
{
"code": null,
"e": 3628,
"s": 3613,
"text": "a[4] = 18 > 14"
},
{
"code": null,
"e": 3643,
"s": 3628,
"text": "Swap 18 and 14"
},
{
"code": null,
"e": 3665,
"s": 3643,
"text": "Next, a[3] = 13 < 14,"
},
{
"code": null,
"e": 3680,
"s": 3665,
"text": "a[2] = 5 < 14,"
},
{
"code": null,
"e": 3694,
"s": 3680,
"text": "a[1] = 2 < 14"
},
{
"code": null,
"e": 3706,
"s": 3694,
"text": "So, no swap"
},
{
"code": null,
"e": 3715,
"s": 3706,
"text": "Finally,"
},
{
"code": null,
"e": 3734,
"s": 3715,
"text": "the sorted list is"
},
{
"code": null,
"e": 3769,
"s": 3734,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3788,
"s": 3769,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3821,
"s": 3788,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3840,
"s": 3821,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3873,
"s": 3840,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3892,
"s": 3873,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3927,
"s": 3892,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3940,
"s": 3927,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 3972,
"s": 3940,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3985,
"s": 3972,
"text": " Zach Miller"
},
{
"code": null,
"e": 4018,
"s": 3985,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4032,
"s": 4018,
"text": " Sasha Miller"
},
{
"code": null,
"e": 4039,
"s": 4032,
"text": " Print"
},
{
"code": null,
"e": 4050,
"s": 4039,
"text": " Add Notes"
}
] |
Elegant CICD with Databricks notebooks | by Rik Jongerius | Towards Data Science | With Luuk van der Velden
Notebooks are the primary runtime on Databricks from data science exploration to ETL and ML in production. This emphasis on notebooks calls for a change in our understanding of production quality code. We have to do away with our hesitancy about messy notebooks and ask ourselves: How do we move notebooks into our production pipelines? How do we perform unit and integration tests on notebooks? Can we treat notebooks as artifacts of a DevOps pipeline?
When choosing Databricks as the compute platform your best option is to also run notebooks in your production environment. This decision is dictated by the overwhelming support for the notebooks runtime versus classic python scripting. We argue that, one should fully embrace the notebooks approach and choose the best methods to test and deploy notebooks in a production environment. In this blog, we use Azure DevOps pipelines for notebook (unit, integration) testing using transient Databricks clusters and notebook artifact registration.
Notebooks can live in isolation, but we prefer them as part of a Git repository, which has the following structure. It contains a notebooks directory to check in Databricks notebooks as Source files, a Python package (‘my_model’) containing functionality to be imported in a notebook, a tests directory with unit tests for the Python package, an Azure DevOps pipeline and a cluster-config.json to configure our transient Databricks clusters. Additionally we use Poetry for Python dependency management and packaging based on the pyproject.toml specification.
notebooks/- run_model.py # Databricks notebook checked in as .py filemy_model/- preprocessing.py # Python module imported in notebooktests/azure-pipelines.ymlcluster-config.ymlpyproject.toml...
Notebooks can be committed into a Git repository either by linking a Git repository to the notebook in the Databricks Workspace or by manually exporting the notebook as a Source File. In both cases, the notebooks are available in the repository as a Python file with Databricks markup commands. The notebook entry point of our repository is shown below. Notice that it installs and imports the Python package ‘my_model’ build from the containing repository. The package versioning will be worked out in detail later. Any notebook logic is captured in the main function. After executing the main function dbutils.notebook.exit() is called, which signals successful completion and allows a result value to be returned to the caller.
# Databricks notebook sourcedbutils.widgets.text("package_version", defaultValue='')package_version = dbutils.widgets.get("package_version") # COMMAND ---------- devops_pat = dbutils.secrets.get("devops_scope", "devops-artifact-read")%pip install my_model==$package_version --index=https://build:[email protected]/organization/project/_packaging/feed/pypi/simple/ # COMMAND ---------- from my_model.preprocessing import do_nothing # COMMAND ---------- # define the main model functiondef main(spark): do_nothing(spark) # COMMAND ---------- # run the modelfrom loguru import logger with logger.catch(reraise=True): main(spark) # COMMAND ---------- dbutils.notebook.exit("OK")
When developing notebooks and their supporting Python package, a developer commits on a development branch and creates a Pull Request for colleagues to review. Figure 1 shows the steps of the pipeline that support our Pull Requests. The Pull Request automatically triggers an Azure DevOps Pipeline that has to succeed on the most recent commit. First we run the unit tests of the Python package and on success build it and publish the dev build package to Azure Artifacts. The version string of this dev build package is passed to the notebook input widget “package_version” for notebook integration testing on our staging environment. The pipeline validates whether the notebook runs successfully (whether dbutils.notebook.exit is called) and provides feedback on the Pull Request.
The goal is to execute this notebook on Databricks from an Azure DevOps pipeline. For flexibility, we choose Databricks Pools. The advantage of these pools is that they can reduce the startup and auto-scale times of clusters when many different jobs need to run on just-in-time clusters. For the execution of the notebook (and access to optional data sources) we use an Azure App Registration. This Azure App Registration will have permissions to manage Databricks clusters and execute notebooks. The basic steps of the pipeline include Databricks cluster configuration and creation, execution of the notebook and finally deletion of the cluster. We will discuss each step in detail (Figure 2).
In order to use Azure DevOps Pipelines to test and deploy Databricks notebooks, we use the Azure DevOps tasks developed by Data Thirst Ltd to create clusters and the tasks from Microsoft DevLabs to execute notebooks. As their set of tasks does not yet support all needed operations, we also use their PowerShell tools they developed for Databricks. Both the tasks and PowerShell tools are wrappers around the Databricks API.
As preparation we create a Databricks pool that is available for integration tests. We use an Azure App Registration that acts as a principal to execute notebooks on the instance pool. The App Registration is registered as a Databricks Service Principal with the “Can Attach To” permission on the Databricks pool to create cluster.
The first step of the CI/CD pipeline is to fetch all required secrets. For simplicity, we store the app registration client id, secret, tenant-id and the Databricks pool ID in a Key Vault. The secrets are collected using the AzureKeyVault task.
# azure-pipelines.yml excerptjobs:- job: integration_test displayName: Test on databricks pool: vmImage: "windows-latest" steps: - task: AzureKeyVault@1 inputs: azureSubscription: "Azure DevOps Service Connection" keyVaultName: "keyvault-test-environment" secretsFilter: "appreg-client-id,appreg-client-secret,tenant-id,databricks-pool-id"
To interact with Databricks we need to connect to the workspace from Azure DevOps. We use two Azure Devops Tasks from Data Thirst to generate an access token for Databricks and to connect to the workspace. The token is stored in the BearerToken variable and generated for the app registration we have granted permissions in Databricks. The workspace URL can be found in the Azure Portal on the Databricks resource.
# azure-pipelines.yml excerpt- task: databricksDeployCreateBearer@0 inputs: applicationId: $(appreg-client-id) spSecret: $(appreg-client-secret) resourceGroup: "DatabricksResourceGroup" workspace: "DatabricksWorkspace" subscriptionId: "AzureSubscriptionId" tenantId: $(tenant-id) region: "westeurope"- task: configuredatabricks@0 inputs: url: "https://adb-000000000000.0.azuredatabricks.net" token: $(BearerToken)
Please note, there is a potential security issue by using the databricksDeployCreateBearer task, which we have resolved in our live pipelines. The current version of the task creates bearer tokens without an expiration date and unfortunately, there is no way to set an expiration date using the task. As an alternative, it is possible to use the Powershell Databricks tools from Data Thirst as well. By consecutively calling Connect-Databricks and New-DatabricksBearerToken it is possible to create a token with a limited lifetime.
After setting up the connection to Databricks, we create a dedicated cluster in the Databricks for the purpose of the integration tests executed by this pipeline. The cluster configuration consists of just 1 worker, which is sufficient for the integration test. As we store test data needed for the notebooks on an ADLS gen2 storage account, we setup ADLS pass-through to allow the app registration to authenticate with the storage account. For best practices we do not insert the app registration client secret directly in the cluster config, as this will be visible in Databricks. Instead, we use a Databricks Secret Scope and its template markup in the cluster config, which is filled at runtime.
// cluster-config.json{ "num_workers": 1, "cluster_name": "", "spark_version": "", "spark_conf": { "fs.azure.account.auth.type": "OAuth", "fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider", "fs.azure.account.oauth2.client.id": "", "fs.azure.account.oauth2.client.secret": "{{secrets/zpz_scope/appreg-client-secret}}", "fs.azure.account.oauth2.client.endpoint": "", "spark.hadoop.fs.permissions.umask-mode": "002" }, "ssh_public_keys": [], "custom_tags": {}, "spark_env_vars": { "PYSPARK_PYTHON": "/databricks/python3/bin/python3", "NSK_ENV": "" }, "autotermination_minutes": 10, "cluster_source": "API", "init_scripts": [], "instance_pool_id": ""}
We commit the above template of the cluster configuration file and use the linux `jq` command to fill out details such as the pool id and app registration client id from the Azure Key Vault at runtime. The cluster name is based on the current devops Build ID and together with other parameters the cluster-config.json is rendered and written to disk.
# azure-pipelines.yml excerpt- bash: | jq -c ".cluster_name = \"${CLUSTER_NAME}\""` `"| .spark_conf.\"fs.azure.account.oauth2.client.id\" = \"$(ar20zpz001-client-id)\""` `"| .spark_conf.\"fs.azure.account.oauth2.client.endpoint\" = \"https://login.microsoftonline.com/$(tenant-id)/oauth2/token\""` `"| .spark_version = \"${RUNTIME}\""` `"| .instance_pool_id = \"${INSTANCE_POOL_ID}\""` `"| .spark_env_vars.NSK_ENV = \"${NSK_ENV}\"" cluster-config.json > tmp.$$.json mv tmp.$$.json cluster-config.json echo "Generated cluster-config.json:" cat cluster-config.json displayName: "Generate cluster-config.json" env: CLUSTER_NAME: "integration-build-$(Build.BuildId)" RUNTIME: "7.5.x-scala2.12" INSTANCE_POOL_ID: $(main-pool-id) NSK_ENV: "test"
The databricksClusterTask from Data Thirst uses the rendered cluster-config.json to create and deploy a cluster on our staging environment with resources taken from the Databricks pool.
- task: databricksClusterTask@0 name: createCluster inputs: authMethod: "bearer" bearerToken: $(appreg-access-token) region: "westeurope" sourcePath: "cluster-config.json"
Finally, we can upload the notebook to test and execute it. The databricksDeployScripts task uploads the notebook to Databricks, which is executed using the executenotebook task from Microsoft DevLabs. The notebook is stored in a path containing the devops Build ID to identify (and delete) it later if needed. If the notebook uses widgets, the executionParams input is used to pass a JSON string with input parameters. In our case, the Python package dev version string is passed as “package_version” for controlled integration testing. Finally, we wait for the execution of the notebook to finish. The executenotebook task finishes successfully if the Databricks builtin dbutils.notebook.exit(“returnValue”) is called during the notebook run.
# azure-pipelines.yml excerpt- task: databricksDeployScripts@0 inputs: authMethod: "bearer" bearerToken: $(appreg-access-token) region: "westeurope" localPath: "notebooks/" databricksPath: "/test/package_name/$(Build.BuildId)" clean: false - task: executenotebook@0 inputs: notebookPath: "/test/package_name/$(Build.BuildId)/$(notebook_name)" executionParams: '{"package_version":"0.0.0-dev"}' existingClusterId: $(createCluster.DatabricksClusterId)- task: waitexecution@0 name: waitForNotebook
Finally, we delete the cluster. Unfortunately, no Azure DevOps task from Data Thirst exists to delete clusters, so we installed their Powershell Databricks tools and use the Remove-DatabricksCluster command to delete the cluster.
# azure-pipelines.yml excerpt- task: PowerShell@2 condition: always() inputs: targetType: "inline" script: | Install-Module -Name azure.databricks.cicd.tools -force -Scope CurrentUser- task: PowerShell@2 condition: always() inputs: targetType: "inline" script: | Remove-DatabricksCluster -BearerToken $(BearerToken) -Region 'westeurope' -ClusterId $(createCluster.DatabricksClusterId) displayName: "Delete Databricks integration cluster"
Notebooks that have been tested successfully are ready to be merged with the main branch. After merging we want to bring the notebooks to production. We use Azure devops artifacts to register the project notebook directory as a universal package in an Azure devops artifact feed. We tag the main branch with a release version, which triggers a pipeline run including artifact registration. The release version is set as the default “package_version” in the notebook input widget with sed before registering the notebook artifact, see below (example below for release 1.0.0). Note that, the accompanying Python package is also registered as an artifact with the same name and version, but in a different artifact devops artifact feed. This ensures that by default the notebook will run with the Python package version it was tested against. Our notebook artifacts are thus reproducible and allow for a controlled release process.
# Databricks notebook sourcedbutils.widgets.text("package_version", defaultValue='1.0.0')package_version = dbutils.widgets.get("package_version")
How you generate release versions is up to you. Initially you can add a git tag to the main branch to trigger a build including artifact registration, such as shown below. For full CICD you can generate a version on-the-fly when merging a pull request.
# azure-pipelines.yml excerpt variables: packageName: 'my_model' ${{ if startsWith(variables['Build.SourceBranch'], 'refs/tags/') }}: packageVersion: $(Build.SourceBranchName) ${{ if not(startsWith(variables['Build.SourceBranch'], 'refs/tags/')) }}: packageVersion: 0.0.0-dev.$(Build.BuildId)- job: publish_notebook_artifact pool: vmImage: "ubuntu-latest" dependsOn: [integration_test] condition: and(succeeded(), or(eq(variables['Build.Reason'], 'Manual'), startsWith(variables['Build.SourceBranch'], 'refs/tags/'))) steps: - bash: | set -e if [ -z "$PACKAGEVERSION" ] then echo "Require PACKAGEVERSION parameter" exit 1 fi sed -i "s/defaultValue=.*/defaultValue='$PACKAGEVERSION')/" \ notebooks/run_model.py displayName: Update default value for version - task: UniversalPackages@0 displayName: Publish notebook artifact $(packageVersion) inputs: command: publish publishDirectory: "notebooks/" vstsFeedPublish: "DNAKAA/databricks-notebooks" vstsFeedPackagePublish: "my_model" packagePublishDescription: "notebooks of my_model" versionOption: custom versionPublish: "$(packageVersion)"
We have shown how to run notebook integration tests on transient Databricks clusters accompanied by Python package unit tests. This results in reproducible notebook artifacts allowing for a controlled release process for notebooks. Databricks notebooks are first class citizens and require engineers to emancipate notebooks into their test and release processes. We look forward to learn more about merging the realities of data scientists with those of the data engineer with the goal increase productivity, regular releases. Our goal is to ease the move from exploration, proof-of-concept to production. In our next blog we will go in depth how to use notebook artifacts in production pipelines with an emphasis on Azure DataFactory pipelines.
Originally published at https://codebeez.nl. | [
{
"code": null,
"e": 196,
"s": 171,
"text": "With Luuk van der Velden"
},
{
"code": null,
"e": 650,
"s": 196,
"text": "Notebooks are the primary runtime on Databricks from data science exploration to ETL and ML in production. This emphasis on notebooks calls for a change in our understanding of production quality code. We have to do away with our hesitancy about messy notebooks and ask ourselves: How do we move notebooks into our production pipelines? How do we perform unit and integration tests on notebooks? Can we treat notebooks as artifacts of a DevOps pipeline?"
},
{
"code": null,
"e": 1192,
"s": 650,
"text": "When choosing Databricks as the compute platform your best option is to also run notebooks in your production environment. This decision is dictated by the overwhelming support for the notebooks runtime versus classic python scripting. We argue that, one should fully embrace the notebooks approach and choose the best methods to test and deploy notebooks in a production environment. In this blog, we use Azure DevOps pipelines for notebook (unit, integration) testing using transient Databricks clusters and notebook artifact registration."
},
{
"code": null,
"e": 1751,
"s": 1192,
"text": "Notebooks can live in isolation, but we prefer them as part of a Git repository, which has the following structure. It contains a notebooks directory to check in Databricks notebooks as Source files, a Python package (‘my_model’) containing functionality to be imported in a notebook, a tests directory with unit tests for the Python package, an Azure DevOps pipeline and a cluster-config.json to configure our transient Databricks clusters. Additionally we use Poetry for Python dependency management and packaging based on the pyproject.toml specification."
},
{
"code": null,
"e": 1961,
"s": 1751,
"text": "notebooks/- run_model.py # Databricks notebook checked in as .py filemy_model/- preprocessing.py # Python module imported in notebooktests/azure-pipelines.ymlcluster-config.ymlpyproject.toml..."
},
{
"code": null,
"e": 2692,
"s": 1961,
"text": "Notebooks can be committed into a Git repository either by linking a Git repository to the notebook in the Databricks Workspace or by manually exporting the notebook as a Source File. In both cases, the notebooks are available in the repository as a Python file with Databricks markup commands. The notebook entry point of our repository is shown below. Notice that it installs and imports the Python package ‘my_model’ build from the containing repository. The package versioning will be worked out in detail later. Any notebook logic is captured in the main function. After executing the main function dbutils.notebook.exit() is called, which signals successful completion and allows a result value to be returned to the caller."
},
{
"code": null,
"e": 3382,
"s": 2692,
"text": "# Databricks notebook sourcedbutils.widgets.text(\"package_version\", defaultValue='')package_version = dbutils.widgets.get(\"package_version\") # COMMAND ---------- devops_pat = dbutils.secrets.get(\"devops_scope\", \"devops-artifact-read\")%pip install my_model==$package_version --index=https://build:[email protected]/organization/project/_packaging/feed/pypi/simple/ # COMMAND ---------- from my_model.preprocessing import do_nothing # COMMAND ---------- # define the main model functiondef main(spark): do_nothing(spark) # COMMAND ---------- # run the modelfrom loguru import logger with logger.catch(reraise=True): main(spark) # COMMAND ---------- dbutils.notebook.exit(\"OK\")"
},
{
"code": null,
"e": 4165,
"s": 3382,
"text": "When developing notebooks and their supporting Python package, a developer commits on a development branch and creates a Pull Request for colleagues to review. Figure 1 shows the steps of the pipeline that support our Pull Requests. The Pull Request automatically triggers an Azure DevOps Pipeline that has to succeed on the most recent commit. First we run the unit tests of the Python package and on success build it and publish the dev build package to Azure Artifacts. The version string of this dev build package is passed to the notebook input widget “package_version” for notebook integration testing on our staging environment. The pipeline validates whether the notebook runs successfully (whether dbutils.notebook.exit is called) and provides feedback on the Pull Request."
},
{
"code": null,
"e": 4860,
"s": 4165,
"text": "The goal is to execute this notebook on Databricks from an Azure DevOps pipeline. For flexibility, we choose Databricks Pools. The advantage of these pools is that they can reduce the startup and auto-scale times of clusters when many different jobs need to run on just-in-time clusters. For the execution of the notebook (and access to optional data sources) we use an Azure App Registration. This Azure App Registration will have permissions to manage Databricks clusters and execute notebooks. The basic steps of the pipeline include Databricks cluster configuration and creation, execution of the notebook and finally deletion of the cluster. We will discuss each step in detail (Figure 2)."
},
{
"code": null,
"e": 5285,
"s": 4860,
"text": "In order to use Azure DevOps Pipelines to test and deploy Databricks notebooks, we use the Azure DevOps tasks developed by Data Thirst Ltd to create clusters and the tasks from Microsoft DevLabs to execute notebooks. As their set of tasks does not yet support all needed operations, we also use their PowerShell tools they developed for Databricks. Both the tasks and PowerShell tools are wrappers around the Databricks API."
},
{
"code": null,
"e": 5617,
"s": 5285,
"text": "As preparation we create a Databricks pool that is available for integration tests. We use an Azure App Registration that acts as a principal to execute notebooks on the instance pool. The App Registration is registered as a Databricks Service Principal with the “Can Attach To” permission on the Databricks pool to create cluster."
},
{
"code": null,
"e": 5862,
"s": 5617,
"text": "The first step of the CI/CD pipeline is to fetch all required secrets. For simplicity, we store the app registration client id, secret, tenant-id and the Databricks pool ID in a Key Vault. The secrets are collected using the AzureKeyVault task."
},
{
"code": null,
"e": 6227,
"s": 5862,
"text": "# azure-pipelines.yml excerptjobs:- job: integration_test displayName: Test on databricks pool: vmImage: \"windows-latest\" steps: - task: AzureKeyVault@1 inputs: azureSubscription: \"Azure DevOps Service Connection\" keyVaultName: \"keyvault-test-environment\" secretsFilter: \"appreg-client-id,appreg-client-secret,tenant-id,databricks-pool-id\""
},
{
"code": null,
"e": 6642,
"s": 6227,
"text": "To interact with Databricks we need to connect to the workspace from Azure DevOps. We use two Azure Devops Tasks from Data Thirst to generate an access token for Databricks and to connect to the workspace. The token is stored in the BearerToken variable and generated for the app registration we have granted permissions in Databricks. The workspace URL can be found in the Azure Portal on the Databricks resource."
},
{
"code": null,
"e": 7085,
"s": 6642,
"text": "# azure-pipelines.yml excerpt- task: databricksDeployCreateBearer@0 inputs: applicationId: $(appreg-client-id) spSecret: $(appreg-client-secret) resourceGroup: \"DatabricksResourceGroup\" workspace: \"DatabricksWorkspace\" subscriptionId: \"AzureSubscriptionId\" tenantId: $(tenant-id) region: \"westeurope\"- task: configuredatabricks@0 inputs: url: \"https://adb-000000000000.0.azuredatabricks.net\" token: $(BearerToken)"
},
{
"code": null,
"e": 7617,
"s": 7085,
"text": "Please note, there is a potential security issue by using the databricksDeployCreateBearer task, which we have resolved in our live pipelines. The current version of the task creates bearer tokens without an expiration date and unfortunately, there is no way to set an expiration date using the task. As an alternative, it is possible to use the Powershell Databricks tools from Data Thirst as well. By consecutively calling Connect-Databricks and New-DatabricksBearerToken it is possible to create a token with a limited lifetime."
},
{
"code": null,
"e": 8317,
"s": 7617,
"text": "After setting up the connection to Databricks, we create a dedicated cluster in the Databricks for the purpose of the integration tests executed by this pipeline. The cluster configuration consists of just 1 worker, which is sufficient for the integration test. As we store test data needed for the notebooks on an ADLS gen2 storage account, we setup ADLS pass-through to allow the app registration to authenticate with the storage account. For best practices we do not insert the app registration client secret directly in the cluster config, as this will be visible in Databricks. Instead, we use a Databricks Secret Scope and its template markup in the cluster config, which is filled at runtime."
},
{
"code": null,
"e": 9113,
"s": 8317,
"text": "// cluster-config.json{ \"num_workers\": 1, \"cluster_name\": \"\", \"spark_version\": \"\", \"spark_conf\": { \"fs.azure.account.auth.type\": \"OAuth\", \"fs.azure.account.oauth.provider.type\": \"org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider\", \"fs.azure.account.oauth2.client.id\": \"\", \"fs.azure.account.oauth2.client.secret\": \"{{secrets/zpz_scope/appreg-client-secret}}\", \"fs.azure.account.oauth2.client.endpoint\": \"\", \"spark.hadoop.fs.permissions.umask-mode\": \"002\" }, \"ssh_public_keys\": [], \"custom_tags\": {}, \"spark_env_vars\": { \"PYSPARK_PYTHON\": \"/databricks/python3/bin/python3\", \"NSK_ENV\": \"\" }, \"autotermination_minutes\": 10, \"cluster_source\": \"API\", \"init_scripts\": [], \"instance_pool_id\": \"\"}"
},
{
"code": null,
"e": 9464,
"s": 9113,
"text": "We commit the above template of the cluster configuration file and use the linux `jq` command to fill out details such as the pool id and app registration client id from the Azure Key Vault at runtime. The cluster name is based on the current devops Build ID and together with other parameters the cluster-config.json is rendered and written to disk."
},
{
"code": null,
"e": 10280,
"s": 9464,
"text": "# azure-pipelines.yml excerpt- bash: | jq -c \".cluster_name = \\\"${CLUSTER_NAME}\\\"\"` `\"| .spark_conf.\\\"fs.azure.account.oauth2.client.id\\\" = \\\"$(ar20zpz001-client-id)\\\"\"` `\"| .spark_conf.\\\"fs.azure.account.oauth2.client.endpoint\\\" = \\\"https://login.microsoftonline.com/$(tenant-id)/oauth2/token\\\"\"` `\"| .spark_version = \\\"${RUNTIME}\\\"\"` `\"| .instance_pool_id = \\\"${INSTANCE_POOL_ID}\\\"\"` `\"| .spark_env_vars.NSK_ENV = \\\"${NSK_ENV}\\\"\" cluster-config.json > tmp.$$.json mv tmp.$$.json cluster-config.json echo \"Generated cluster-config.json:\" cat cluster-config.json displayName: \"Generate cluster-config.json\" env: CLUSTER_NAME: \"integration-build-$(Build.BuildId)\" RUNTIME: \"7.5.x-scala2.12\" INSTANCE_POOL_ID: $(main-pool-id) NSK_ENV: \"test\""
},
{
"code": null,
"e": 10466,
"s": 10280,
"text": "The databricksClusterTask from Data Thirst uses the rendered cluster-config.json to create and deploy a cluster on our staging environment with resources taken from the Databricks pool."
},
{
"code": null,
"e": 10652,
"s": 10466,
"text": "- task: databricksClusterTask@0 name: createCluster inputs: authMethod: \"bearer\" bearerToken: $(appreg-access-token) region: \"westeurope\" sourcePath: \"cluster-config.json\""
},
{
"code": null,
"e": 11397,
"s": 10652,
"text": "Finally, we can upload the notebook to test and execute it. The databricksDeployScripts task uploads the notebook to Databricks, which is executed using the executenotebook task from Microsoft DevLabs. The notebook is stored in a path containing the devops Build ID to identify (and delete) it later if needed. If the notebook uses widgets, the executionParams input is used to pass a JSON string with input parameters. In our case, the Python package dev version string is passed as “package_version” for controlled integration testing. Finally, we wait for the execution of the notebook to finish. The executenotebook task finishes successfully if the Databricks builtin dbutils.notebook.exit(“returnValue”) is called during the notebook run."
},
{
"code": null,
"e": 11928,
"s": 11397,
"text": "# azure-pipelines.yml excerpt- task: databricksDeployScripts@0 inputs: authMethod: \"bearer\" bearerToken: $(appreg-access-token) region: \"westeurope\" localPath: \"notebooks/\" databricksPath: \"/test/package_name/$(Build.BuildId)\" clean: false - task: executenotebook@0 inputs: notebookPath: \"/test/package_name/$(Build.BuildId)/$(notebook_name)\" executionParams: '{\"package_version\":\"0.0.0-dev\"}' existingClusterId: $(createCluster.DatabricksClusterId)- task: waitexecution@0 name: waitForNotebook"
},
{
"code": null,
"e": 12158,
"s": 11928,
"text": "Finally, we delete the cluster. Unfortunately, no Azure DevOps task from Data Thirst exists to delete clusters, so we installed their Powershell Databricks tools and use the Remove-DatabricksCluster command to delete the cluster."
},
{
"code": null,
"e": 12623,
"s": 12158,
"text": "# azure-pipelines.yml excerpt- task: PowerShell@2 condition: always() inputs: targetType: \"inline\" script: | Install-Module -Name azure.databricks.cicd.tools -force -Scope CurrentUser- task: PowerShell@2 condition: always() inputs: targetType: \"inline\" script: | Remove-DatabricksCluster -BearerToken $(BearerToken) -Region 'westeurope' -ClusterId $(createCluster.DatabricksClusterId) displayName: \"Delete Databricks integration cluster\""
},
{
"code": null,
"e": 13552,
"s": 12623,
"text": "Notebooks that have been tested successfully are ready to be merged with the main branch. After merging we want to bring the notebooks to production. We use Azure devops artifacts to register the project notebook directory as a universal package in an Azure devops artifact feed. We tag the main branch with a release version, which triggers a pipeline run including artifact registration. The release version is set as the default “package_version” in the notebook input widget with sed before registering the notebook artifact, see below (example below for release 1.0.0). Note that, the accompanying Python package is also registered as an artifact with the same name and version, but in a different artifact devops artifact feed. This ensures that by default the notebook will run with the Python package version it was tested against. Our notebook artifacts are thus reproducible and allow for a controlled release process."
},
{
"code": null,
"e": 13698,
"s": 13552,
"text": "# Databricks notebook sourcedbutils.widgets.text(\"package_version\", defaultValue='1.0.0')package_version = dbutils.widgets.get(\"package_version\")"
},
{
"code": null,
"e": 13951,
"s": 13698,
"text": "How you generate release versions is up to you. Initially you can add a git tag to the main branch to trigger a build including artifact registration, such as shown below. For full CICD you can generate a version on-the-fly when merging a pull request."
},
{
"code": null,
"e": 15148,
"s": 13951,
"text": "# azure-pipelines.yml excerpt variables: packageName: 'my_model' ${{ if startsWith(variables['Build.SourceBranch'], 'refs/tags/') }}: packageVersion: $(Build.SourceBranchName) ${{ if not(startsWith(variables['Build.SourceBranch'], 'refs/tags/')) }}: packageVersion: 0.0.0-dev.$(Build.BuildId)- job: publish_notebook_artifact pool: vmImage: \"ubuntu-latest\" dependsOn: [integration_test] condition: and(succeeded(), or(eq(variables['Build.Reason'], 'Manual'), startsWith(variables['Build.SourceBranch'], 'refs/tags/'))) steps: - bash: | set -e if [ -z \"$PACKAGEVERSION\" ] then echo \"Require PACKAGEVERSION parameter\" exit 1 fi sed -i \"s/defaultValue=.*/defaultValue='$PACKAGEVERSION')/\" \\ notebooks/run_model.py displayName: Update default value for version - task: UniversalPackages@0 displayName: Publish notebook artifact $(packageVersion) inputs: command: publish publishDirectory: \"notebooks/\" vstsFeedPublish: \"DNAKAA/databricks-notebooks\" vstsFeedPackagePublish: \"my_model\" packagePublishDescription: \"notebooks of my_model\" versionOption: custom versionPublish: \"$(packageVersion)\""
},
{
"code": null,
"e": 15894,
"s": 15148,
"text": "We have shown how to run notebook integration tests on transient Databricks clusters accompanied by Python package unit tests. This results in reproducible notebook artifacts allowing for a controlled release process for notebooks. Databricks notebooks are first class citizens and require engineers to emancipate notebooks into their test and release processes. We look forward to learn more about merging the realities of data scientists with those of the data engineer with the goal increase productivity, regular releases. Our goal is to ease the move from exploration, proof-of-concept to production. In our next blog we will go in depth how to use notebook artifacts in production pipelines with an emphasis on Azure DataFactory pipelines."
}
] |
Bootstrap 4 - Alerts | The alert component specifies the predefined message for an user actions. It is used to send the information such as warning, error or confirmation messages to the end users.
You can create an alert box, by adding a class of .alert and along with contextual classes such as .alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light or .alert-dark.
The following example demonstrates usage of above contextual classes −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Alerts</h2>
<div class = "alert alert-primary" role = "alert">
primary alert - Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-secondary" role = "alert">
secondary alert — Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-success" role = "alert">
success alert — Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-danger" role = "alert">
danger alert — Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-warning" role = "alert">
warning alert — Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-info" role = "alert">
info alert — Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-light" role = "alert">
light alert — Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-dark" role = "alert">
dark alert — Welcome to Tutorialspoint!!!
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
To get links in alerts, use the .alert-link utility class in the <a> tag as shown in the below example −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Links in Alerts</h2>
<div class = "alert alert-primary" role = "alert">
primary alert - Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-secondary" role = "alert">
secondary alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-success" role = "alert">
success alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-danger" role = "alert">
danger alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-warning" role = "alert">
warning alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-info" role = "alert">
info alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-light" role = "alert">
light alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
<div class = "alert alert-dark" role = "alert">
<div class = "alert alert-dark" role = "alert">
dark alert — Welcome to
<a href = "https://www.tutorialspoint.com/" target = "_blank"
rel = "nofollow" class = "alert-link">Tutorialspoint!!!</a>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
To build a dismissal alert, use the .alert-dismissable class to alert container. Add the data-dismiss="alert" attribute on the button element to close a button, which automatically dismisses the alert message box.
The following example demonstrates dismissal of alert box −
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Dismissal Alerts</h2>
<div class = "alert alert-success alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Success!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-primary alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Primary!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-secondary alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Secondary!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-danger alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Danger!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-warning alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Warning!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-info alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Info!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-light alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Light!</strong> Welcome to Tutorialspoint!!!
</div>
<div class = "alert alert-dark alert-dismissible">
<button type = "button" class = "close" data-dismiss = "alert">×</button>
<strong>Dark!</strong> Welcome to Tutorialspoint!!!
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1991,
"s": 1816,
"text": "The alert component specifies the predefined message for an user actions. It is used to send the information such as warning, error or confirmation messages to the end users."
},
{
"code": null,
"e": 2213,
"s": 1991,
"text": "You can create an alert box, by adding a class of .alert and along with contextual classes such as .alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light or .alert-dark."
},
{
"code": null,
"e": 2284,
"s": 2213,
"text": "The following example demonstrates usage of above contextual classes −"
},
{
"code": null,
"e": 4845,
"s": 2284,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Alerts</h2>\n <div class = \"alert alert-primary\" role = \"alert\">\n primary alert - Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-secondary\" role = \"alert\">\n secondary alert — Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-success\" role = \"alert\">\n success alert — Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-danger\" role = \"alert\">\n danger alert — Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-warning\" role = \"alert\">\n warning alert — Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-info\" role = \"alert\">\n info alert — Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-light\" role = \"alert\">\n light alert — Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-dark\" role = \"alert\">\n dark alert — Welcome to Tutorialspoint!!!\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4884,
"s": 4845,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4989,
"s": 4884,
"text": "To get links in alerts, use the .alert-link utility class in the <a> tag as shown in the below example −"
},
{
"code": null,
"e": 8684,
"s": 4989,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Links in Alerts</h2>\n <div class = \"alert alert-primary\" role = \"alert\">\n primary alert - Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n \n <div class = \"alert alert-secondary\" role = \"alert\">\n secondary alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n \n <div class = \"alert alert-success\" role = \"alert\">\n success alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n \n <div class = \"alert alert-danger\" role = \"alert\">\n danger alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n \n <div class = \"alert alert-warning\" role = \"alert\">\n warning alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n \n <div class = \"alert alert-info\" role = \"alert\">\n info alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n \n <div class = \"alert alert-light\" role = \"alert\">\n light alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a> \n </div>\n \n <div class = \"alert alert-dark\" role = \"alert\">\n <div class = \"alert alert-dark\" role = \"alert\">\n dark alert — Welcome to \n <a href = \"https://www.tutorialspoint.com/\" target = \"_blank\" \n rel = \"nofollow\" class = \"alert-link\">Tutorialspoint!!!</a>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8723,
"s": 8684,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 8937,
"s": 8723,
"text": "To build a dismissal alert, use the .alert-dismissable class to alert container. Add the data-dismiss=\"alert\" attribute on the button element to close a button, which automatically dismisses the alert message box."
},
{
"code": null,
"e": 8997,
"s": 8937,
"text": "The following example demonstrates dismissal of alert box −"
},
{
"code": null,
"e": 12355,
"s": 8997,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n <body>\n <div class = \"container\">\n <h2>Dismissal Alerts</h2>\n <div class = \"alert alert-success alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Success!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-primary alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Primary!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-secondary alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Secondary!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-danger alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Danger!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-warning alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Warning!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-info alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Info!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-light alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Light!</strong> Welcome to Tutorialspoint!!!\n </div>\n \n <div class = \"alert alert-dark alert-dismissible\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\">×</button>\n <strong>Dark!</strong> Welcome to Tutorialspoint!!!\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 12394,
"s": 12355,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 12427,
"s": 12394,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12441,
"s": 12427,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12476,
"s": 12441,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12493,
"s": 12476,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12530,
"s": 12493,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 12558,
"s": 12530,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12591,
"s": 12558,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12603,
"s": 12591,
"text": " Azaz Patel"
},
{
"code": null,
"e": 12638,
"s": 12603,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12655,
"s": 12638,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 12688,
"s": 12655,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 12708,
"s": 12688,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 12715,
"s": 12708,
"text": " Print"
},
{
"code": null,
"e": 12726,
"s": 12715,
"text": " Add Notes"
}
] |
Redux - Testing | Testing Redux code is easy as we mostly write functions, and most of them are pure. So we can test it without even mocking them. Here, we are using JEST as a testing engine. It works in the node environment and does not access DOM.
We can install JEST with the code given below −
npm install --save-dev jest
With babel, you need to install babel-jest as follows −
npm install --save-dev babel-jest
And configure it to use babel-preset-env features in the .babelrc file as follows −
{
"presets": ["@babel/preset-env"]
}
And add the following script in your package.json:
{
//Some other code
"scripts": {
//code
"test": "jest",
"test:watch": "npm test -- --watch"
},
//code
}
Finally, run npm test or npm run test. Let us check how we can write test cases for action creators and reducers.
Let us assume you have action creator as shown below −
export function itemsRequestSuccess(bool) {
return {
type: ITEMS_REQUEST_SUCCESS,
isLoading: bool,
}
}
This action creator can be tested as given below −
import * as action from '../actions/actions';
import * as types from '../../constants/ActionTypes';
describe('actions', () => {
it('should create an action to check if item is loading', () => {
const isLoading = true,
const expectedAction = {
type: types.ITEMS_REQUEST_SUCCESS, isLoading
}
expect(actions.itemsRequestSuccess(isLoading)).toEqual(expectedAction)
})
})
We have learnt that reducer should return a new state when action is applied. So reducer is tested on this behaviour.
Consider a reducer as given below −
const initialState = {
isLoading: false
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'ITEMS_REQUEST':
return Object.assign({}, state, {
isLoading: action.payload.isLoading
})
default:
return state;
}
}
export default reducer;
To test above reducer, we need to pass state and action to the reducer, and return a new state as shown below −
import reducer from '../../reducer/reducer'
import * as types from '../../constants/ActionTypes'
describe('reducer initial state', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual([
{
isLoading: false,
}
])
})
it('should handle ITEMS_REQUEST', () => {
expect(
reducer(
{
isLoading: false,
},
{
type: types.ITEMS_REQUEST,
payload: { isLoading: true }
}
)
).toEqual({
isLoading: true
})
})
})
If you are not familiar with writing test case, you can check the basics of JEST.
56 Lectures
12.5 hours
Eduonix Learning Solutions
63 Lectures
9.5 hours
TELCOMA Global
129 Lectures
19.5 hours
Ghulam Abbas
31 Lectures
3 hours
Saumitra Vishal
55 Lectures
4 hours
Saumitra Vishal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2047,
"s": 1815,
"text": "Testing Redux code is easy as we mostly write functions, and most of them are pure. So we can test it without even mocking them. Here, we are using JEST as a testing engine. It works in the node environment and does not access DOM."
},
{
"code": null,
"e": 2095,
"s": 2047,
"text": "We can install JEST with the code given below −"
},
{
"code": null,
"e": 2124,
"s": 2095,
"text": "npm install --save-dev jest\n"
},
{
"code": null,
"e": 2180,
"s": 2124,
"text": "With babel, you need to install babel-jest as follows −"
},
{
"code": null,
"e": 2215,
"s": 2180,
"text": "npm install --save-dev babel-jest\n"
},
{
"code": null,
"e": 2299,
"s": 2215,
"text": "And configure it to use babel-preset-env features in the .babelrc file as follows −"
},
{
"code": null,
"e": 2532,
"s": 2299,
"text": "{ \n \"presets\": [\"@babel/preset-env\"] \n}\nAnd add the following script in your package.json:\n{ \n //Some other code \n \"scripts\": {\n //code\n \"test\": \"jest\", \n \"test:watch\": \"npm test -- --watch\" \n }, \n //code \n}"
},
{
"code": null,
"e": 2646,
"s": 2532,
"text": "Finally, run npm test or npm run test. Let us check how we can write test cases for action creators and reducers."
},
{
"code": null,
"e": 2701,
"s": 2646,
"text": "Let us assume you have action creator as shown below −"
},
{
"code": null,
"e": 2822,
"s": 2701,
"text": "export function itemsRequestSuccess(bool) {\n return {\n type: ITEMS_REQUEST_SUCCESS,\n isLoading: bool,\n }\n}"
},
{
"code": null,
"e": 2873,
"s": 2822,
"text": "This action creator can be tested as given below −"
},
{
"code": null,
"e": 3286,
"s": 2873,
"text": "import * as action from '../actions/actions';\nimport * as types from '../../constants/ActionTypes';\n\ndescribe('actions', () => {\n it('should create an action to check if item is loading', () => { \n const isLoading = true, \n const expectedAction = { \n type: types.ITEMS_REQUEST_SUCCESS, isLoading \n } \n expect(actions.itemsRequestSuccess(isLoading)).toEqual(expectedAction) \n })\n})"
},
{
"code": null,
"e": 3404,
"s": 3286,
"text": "We have learnt that reducer should return a new state when action is applied. So reducer is tested on this behaviour."
},
{
"code": null,
"e": 3440,
"s": 3404,
"text": "Consider a reducer as given below −"
},
{
"code": null,
"e": 3764,
"s": 3440,
"text": "const initialState = {\n isLoading: false\n};\nconst reducer = (state = initialState, action) => {\n switch (action.type) {\n case 'ITEMS_REQUEST':\n return Object.assign({}, state, {\n isLoading: action.payload.isLoading\n })\n default:\n return state;\n }\n}\nexport default reducer;"
},
{
"code": null,
"e": 3876,
"s": 3764,
"text": "To test above reducer, we need to pass state and action to the reducer, and return a new state as shown below −"
},
{
"code": null,
"e": 4505,
"s": 3876,
"text": "import reducer from '../../reducer/reducer' \nimport * as types from '../../constants/ActionTypes'\n\ndescribe('reducer initial state', () => {\n it('should return the initial state', () => {\n expect(reducer(undefined, {})).toEqual([\n {\n isLoading: false,\n }\n ])\n })\n it('should handle ITEMS_REQUEST', () => {\n expect(\n reducer(\n {\n isLoading: false,\n },\n {\n type: types.ITEMS_REQUEST,\n payload: { isLoading: true }\n }\n )\n ).toEqual({\n isLoading: true\n })\n })\n})"
},
{
"code": null,
"e": 4587,
"s": 4505,
"text": "If you are not familiar with writing test case, you can check the basics of JEST."
},
{
"code": null,
"e": 4623,
"s": 4587,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4651,
"s": 4623,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4686,
"s": 4651,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4702,
"s": 4686,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4739,
"s": 4702,
"text": "\n 129 Lectures \n 19.5 hours \n"
},
{
"code": null,
"e": 4753,
"s": 4739,
"text": " Ghulam Abbas"
},
{
"code": null,
"e": 4786,
"s": 4753,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4803,
"s": 4786,
"text": " Saumitra Vishal"
},
{
"code": null,
"e": 4836,
"s": 4803,
"text": "\n 55 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4853,
"s": 4836,
"text": " Saumitra Vishal"
},
{
"code": null,
"e": 4860,
"s": 4853,
"text": " Print"
},
{
"code": null,
"e": 4871,
"s": 4860,
"text": " Add Notes"
}
] |
Patchwork - Awesome ggplot2 extension for DataViz | Towards Data Science | For Data Visualization in R, ggplot2 has been the go-to package to generate awesome, publishing quality plots. Its layered approach enables us to start with a simple visual foundation and keep adding embellishments with each layer. Even the most basic plots with default settings, looks and feels way better than base R graphics. So much so, that if you plan or need to share the output of your analytic work to internal stakeholders or external clients, it is imperative that you have ggplot in your skillset. Yes, there is a learning curve (which self-respecting skill does not !) but once mastered, ggplot2 provides superb possibilities for customization and to convey your insight in a striking manner.
But this post is not about ggplot per se ! Rather it is about the awesome layout functionality now available, beyond the standard grid options available through the facet_wrap() and facet_grid() methods of ggplot2.
Flexibile layouting options are especially useful and sorely missed, when you would like to group a set of related plots together into a single graphic, but find that some plots would look better wider than the others and messes with your grid constraints of rows and columns and row/column widths. Or worse, there is a rash of legends floating all over the place.
Enter patchwork !
patchwork builds on the power of + which now not only enables us to add a layer to the base plot in ggplot2, but also enables us to control the placement and size of the subplots. All of this with just 3 “operators” :+ , () and /. Lets check it out !
Ensure you have already installed ggplot2 package. If you have not used ggplot before, head to this comprehensive tutorial here by Selva Prabhakaran.
library(ggplot2)install.packages('patchwork') # first time installationlibrary('patchwork') # load the library in to your R environment
We will use the Texas Housing txhousing dataset from ggplot2 to demo the capabilities of patchwork. Lets quickly check the dimensions and first few rows of the dataset.
data = ggplot2::txhousingdim(data)
head(data)
It has 9 columns and 8602 observations and contains info on city wise housing sales and inventory data for the US state of Texas for 2000–2015 for various months. You can use the help(txhousing) command on your R console to check for the detailed description of the columns. For the purpose of our demo let us consider the data only for the city of Dallas.
dallas = data[data$city == "Dallas",] # take a subset of data only for Dallas
We will now create some ggplots that will then be used in patchwork
avg.monthly.sales = dallas %>% group_by(year) %>% summarise(mean = mean(sales))mytheme = theme(panel.background = element_rect(fill = "powderblue")) # set a ggplot theme for repeated use laterp1 = ggplot(avg.monthly.sales, aes(year,mean)) + geom_col(fill = "gold", color = "navyblue") + ylab("Mean Monthly Sales (Nos)") + mytheme + labs(title = "Dallas - 2000 to 2015")p1
avg.monthly.vol = dallas %>% group_by(year) %>% summarise(mean = mean(volume))p2 = ggplot(avg.monthly.vol, aes(year,mean)) + geom_col(fill = "gold", color = "navyblue") + ylab("Mean Monthly volumes in USD") + mytheme + labs(title = "Dallas - 2000 to 2015")p2
dal_2014 = dallas %>% filter(year ==2014)p3 = ggplot(dal_2014, aes(month,listings)) + geom_line(color = "navyblue") + mytheme + scale_x_continuous(breaks = c(seq(1,12,1))) + labs(title = "Dallas 2014: Property Listing Count")p3
avg.monthly.inventory = dallas %>% group_by(year) %>% summarise(mean = mean(inventory))p4 = ggplot(avg.monthly.inventory, aes(year,mean)) + geom_col(fill = "gold", color = "navyblue") + ylab("Mean Inventory (No of months)") + mytheme + labs(title = "Dallas - 2000 to 2015")p4
Now, assume that we want to display 2 or more of these plots as a single graphic. Extensions like gridExtra do a competent job, but the options are restricted to square or rectangular grids with one subplot per cell. Here is where patchwork hits it right out of the park with virtually no layouting code required. Watch !!
p1 + p2
Thats it ! As simple as addition..Now for some division as well.
(p1 + p2) /p3
And stack it some more..!
p1/(p3+p4)/p2
Awesome right? The package also has option to consolidate all the identical legends of the subplots in the patchwork into a single legend and more features. I will post a separate article covering this.
For another handy tool for Exploratory Data Analysis (EDA) in R, click here to see my article on SmartEDA.
Thank you for reading and please leave your comments and feedback. | [
{
"code": null,
"e": 879,
"s": 172,
"text": "For Data Visualization in R, ggplot2 has been the go-to package to generate awesome, publishing quality plots. Its layered approach enables us to start with a simple visual foundation and keep adding embellishments with each layer. Even the most basic plots with default settings, looks and feels way better than base R graphics. So much so, that if you plan or need to share the output of your analytic work to internal stakeholders or external clients, it is imperative that you have ggplot in your skillset. Yes, there is a learning curve (which self-respecting skill does not !) but once mastered, ggplot2 provides superb possibilities for customization and to convey your insight in a striking manner."
},
{
"code": null,
"e": 1094,
"s": 879,
"text": "But this post is not about ggplot per se ! Rather it is about the awesome layout functionality now available, beyond the standard grid options available through the facet_wrap() and facet_grid() methods of ggplot2."
},
{
"code": null,
"e": 1459,
"s": 1094,
"text": "Flexibile layouting options are especially useful and sorely missed, when you would like to group a set of related plots together into a single graphic, but find that some plots would look better wider than the others and messes with your grid constraints of rows and columns and row/column widths. Or worse, there is a rash of legends floating all over the place."
},
{
"code": null,
"e": 1477,
"s": 1459,
"text": "Enter patchwork !"
},
{
"code": null,
"e": 1728,
"s": 1477,
"text": "patchwork builds on the power of + which now not only enables us to add a layer to the base plot in ggplot2, but also enables us to control the placement and size of the subplots. All of this with just 3 “operators” :+ , () and /. Lets check it out !"
},
{
"code": null,
"e": 1878,
"s": 1728,
"text": "Ensure you have already installed ggplot2 package. If you have not used ggplot before, head to this comprehensive tutorial here by Selva Prabhakaran."
},
{
"code": null,
"e": 2014,
"s": 1878,
"text": "library(ggplot2)install.packages('patchwork') # first time installationlibrary('patchwork') # load the library in to your R environment"
},
{
"code": null,
"e": 2183,
"s": 2014,
"text": "We will use the Texas Housing txhousing dataset from ggplot2 to demo the capabilities of patchwork. Lets quickly check the dimensions and first few rows of the dataset."
},
{
"code": null,
"e": 2218,
"s": 2183,
"text": "data = ggplot2::txhousingdim(data)"
},
{
"code": null,
"e": 2229,
"s": 2218,
"text": "head(data)"
},
{
"code": null,
"e": 2586,
"s": 2229,
"text": "It has 9 columns and 8602 observations and contains info on city wise housing sales and inventory data for the US state of Texas for 2000–2015 for various months. You can use the help(txhousing) command on your R console to check for the detailed description of the columns. For the purpose of our demo let us consider the data only for the city of Dallas."
},
{
"code": null,
"e": 2664,
"s": 2586,
"text": "dallas = data[data$city == \"Dallas\",] # take a subset of data only for Dallas"
},
{
"code": null,
"e": 2732,
"s": 2664,
"text": "We will now create some ggplots that will then be used in patchwork"
},
{
"code": null,
"e": 3108,
"s": 2732,
"text": "avg.monthly.sales = dallas %>% group_by(year) %>% summarise(mean = mean(sales))mytheme = theme(panel.background = element_rect(fill = \"powderblue\")) # set a ggplot theme for repeated use laterp1 = ggplot(avg.monthly.sales, aes(year,mean)) + geom_col(fill = \"gold\", color = \"navyblue\") + ylab(\"Mean Monthly Sales (Nos)\") + mytheme + labs(title = \"Dallas - 2000 to 2015\")p1"
},
{
"code": null,
"e": 3371,
"s": 3108,
"text": "avg.monthly.vol = dallas %>% group_by(year) %>% summarise(mean = mean(volume))p2 = ggplot(avg.monthly.vol, aes(year,mean)) + geom_col(fill = \"gold\", color = \"navyblue\") + ylab(\"Mean Monthly volumes in USD\") + mytheme + labs(title = \"Dallas - 2000 to 2015\")p2"
},
{
"code": null,
"e": 3603,
"s": 3371,
"text": "dal_2014 = dallas %>% filter(year ==2014)p3 = ggplot(dal_2014, aes(month,listings)) + geom_line(color = \"navyblue\") + mytheme + scale_x_continuous(breaks = c(seq(1,12,1))) + labs(title = \"Dallas 2014: Property Listing Count\")p3"
},
{
"code": null,
"e": 3883,
"s": 3603,
"text": "avg.monthly.inventory = dallas %>% group_by(year) %>% summarise(mean = mean(inventory))p4 = ggplot(avg.monthly.inventory, aes(year,mean)) + geom_col(fill = \"gold\", color = \"navyblue\") + ylab(\"Mean Inventory (No of months)\") + mytheme + labs(title = \"Dallas - 2000 to 2015\")p4"
},
{
"code": null,
"e": 4206,
"s": 3883,
"text": "Now, assume that we want to display 2 or more of these plots as a single graphic. Extensions like gridExtra do a competent job, but the options are restricted to square or rectangular grids with one subplot per cell. Here is where patchwork hits it right out of the park with virtually no layouting code required. Watch !!"
},
{
"code": null,
"e": 4214,
"s": 4206,
"text": "p1 + p2"
},
{
"code": null,
"e": 4279,
"s": 4214,
"text": "Thats it ! As simple as addition..Now for some division as well."
},
{
"code": null,
"e": 4293,
"s": 4279,
"text": "(p1 + p2) /p3"
},
{
"code": null,
"e": 4319,
"s": 4293,
"text": "And stack it some more..!"
},
{
"code": null,
"e": 4333,
"s": 4319,
"text": "p1/(p3+p4)/p2"
},
{
"code": null,
"e": 4536,
"s": 4333,
"text": "Awesome right? The package also has option to consolidate all the identical legends of the subplots in the patchwork into a single legend and more features. I will post a separate article covering this."
},
{
"code": null,
"e": 4643,
"s": 4536,
"text": "For another handy tool for Exploratory Data Analysis (EDA) in R, click here to see my article on SmartEDA."
}
] |
Check if a large number is divisibility by 15 in C++ | Here we will see how to check a number is divisible by 15 or not. In this case the number is very large number. So we put the number as string.
To check whether a number is divisible by 15, if the number is divisible by 5, and divisible by 3. So to check divisibility by 5, we have to see the last number is 0 or 5. To check divisibility by 3, we will see the sum of digits are divisible by 3 or not.
Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isDiv15(string num){
int n = num.length();
if(num[n - 1] != '5' && num[n - 1] != '0')
return false;
long sum = accumulate(begin(num), end(num), 0) - '0' * n;
if(sum % 3 == 0)
return true;
return false;
}
int main() {
string num = "154484585745184258458158245285260";
if(isDiv15(num)){
cout << "Divisible";
} else {
cout << "Not Divisible";
}
}
Divisible | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Here we will see how to check a number is divisible by 15 or not. In this case the number is very large number. So we put the number as string."
},
{
"code": null,
"e": 1463,
"s": 1206,
"text": "To check whether a number is divisible by 15, if the number is divisible by 5, and divisible by 3. So to check divisibility by 5, we have to see the last number is 0 or 5. To check divisibility by 3, we will see the sum of digits are divisible by 3 or not."
},
{
"code": null,
"e": 1474,
"s": 1463,
"text": " Live Demo"
},
{
"code": null,
"e": 1926,
"s": 1474,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isDiv15(string num){\n int n = num.length();\n if(num[n - 1] != '5' && num[n - 1] != '0')\n return false;\n long sum = accumulate(begin(num), end(num), 0) - '0' * n;\n if(sum % 3 == 0)\n return true;\n return false;\n}\nint main() {\n string num = \"154484585745184258458158245285260\";\n if(isDiv15(num)){\n cout << \"Divisible\";\n } else {\n cout << \"Not Divisible\";\n }\n}"
},
{
"code": null,
"e": 1936,
"s": 1926,
"text": "Divisible"
}
] |
How to animate RecyclerView items when they appear on screen? | This example demonstrates how to animate RecyclerView items when they appear on the screen .
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutAnimation="@anim/layout_animation_up_to_down"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:src="@android:drawable/ic_media_next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to res/anim/down_to_up.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500">
<translate
android:fromYDelta="50%p"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toYDelta="0" />
<alpha
android:fromAlpha="0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toAlpha="1" />
</set>
Step 4 − Add the following code to res/anim/left_to_right.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500">
<translate
android:fromXDelta="-100%p"
android:interpolator="@android:anim/decelerate_interpolator"
android:toXDelta="0" />
<alpha
android:fromAlpha="0.5"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toAlpha="1" />
</set>
Step 5 − Add the following code to res/anim/right_to_left.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500">
<translate
android:fromXDelta="100%p"
android:interpolator="@android:anim/decelerate_interpolator"
android:toXDelta="0" />
<alpha
android:fromAlpha="0.5"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toAlpha="1" />
</set>
Step 6 − Add the following code to res/anim/up_to_down.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500">
<translate
android:fromYDelta="-25%"
android:interpolator="@android:anim/decelerate_interpolator"
android:toYDelta="0" />
<alpha
android:fromAlpha="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:toAlpha="1" />
<scale
android:fromXScale="125%"
android:fromYScale="125%"
android:interpolator="@android:anim/decelerate_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="100%"
android:toYScale="100%" />
</set>
Step 7 − Add the following code to res/anim/layout_animation_down_to_up.xml.
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/down_to_up"
android:animationOrder="normal"
android:delay="15%" />
Step 8 − Add the following code to res/anim/layout_animation_left_to_right.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/left_to_right"
android:animationOrder="normal"
android:delay="15%" />
Step 9 − Add the following code to res/anim/layout_animation_right_to_left.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/right_to_left"
android:animationOrder="normal"
android:delay="15%" />
Step 10 − Add the following code to res/anim/layout_animation_up_to_down.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/up_to_down"
android:animationOrder="normal"
android:delay="15%" />
Step 11 − Add the following code to src/MainActivity.java
package com.journaldev.androidrecyclerviewlayoutanimation;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.GridLayoutAnimationController;
import android.view.animation.LayoutAnimationController;
import android.widget.Spinner;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
FloatingActionButton fab;
RecyclerView recyclerView;
RecyclerViewAdapter recyclerViewAdapter;
ArrayList<String>> arrayList = new ArrayList<>();
int[] animationList = {R.anim.layout_animation_up_to_down,
R.anim.layout_animation_right_to_left,
R.anim.layout_animation_down_to_up,
R.anim.layout_animation_left_to_right};
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab = findViewById(R.id.fab);
recyclerView = findViewById(R.id.recyclerView);
populateData();
initAdapter();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i < animationList.length - 1) {
i++;
} else {
i = 0;
}
runAnimationAgain();
}
});
}
private void populateData() {
for (int i = 0; i < 12; i++) {
arrayList.add("Item " + i);
}
}
private void initAdapter() {
recyclerViewAdapter = new RecyclerViewAdapter(arrayList);
recyclerView.setAdapter(recyclerViewAdapter);
}
private void runAnimationAgain() {
final LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(this, animationList[i]);
recyclerView.setLayoutAnimation(controller);
recyclerViewAdapter.notifyDataSetChanged();
recyclerView.scheduleLayoutAnimation();
}
}
Step 12 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.journaldev.androidrecyclerviewlayoutanimation">
<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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrates how to animate RecyclerView items when they appear on the screen ."
},
{
"code": null,
"e": 1284,
"s": 1155,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1349,
"s": 1284,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2633,
"s": 1349,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <android.support.v7.widget.RecyclerView\n android:id=\"@+id/recyclerView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layoutAnimation=\"@anim/layout_animation_up_to_down\"\n app:layoutManager=\"android.support.v7.widget.LinearLayoutManager\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n <android.support.design.widget.FloatingActionButton\n android:id=\"@+id/fab\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"8dp\"\n android:src=\"@android:drawable/ic_media_next\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2693,
"s": 2633,
"text": "Step 3 − Add the following code to res/anim/down_to_up.xml."
},
{
"code": null,
"e": 3129,
"s": 2693,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:duration=\"500\">\n <translate\n android:fromYDelta=\"50%p\"\n android:interpolator=\"@android:anim/accelerate_decelerate_interpolator\"\n android:toYDelta=\"0\" />\n <alpha\n android:fromAlpha=\"0\"\n android:interpolator=\"@android:anim/accelerate_decelerate_interpolator\"\n android:toAlpha=\"1\" />\n</set>"
},
{
"code": null,
"e": 3192,
"s": 3129,
"text": "Step 4 − Add the following code to res/anim/left_to_right.xml."
},
{
"code": null,
"e": 3621,
"s": 3192,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:duration=\"500\">\n <translate\n android:fromXDelta=\"-100%p\"\n android:interpolator=\"@android:anim/decelerate_interpolator\"\n android:toXDelta=\"0\" />\n <alpha\n android:fromAlpha=\"0.5\"\n android:interpolator=\"@android:anim/accelerate_decelerate_interpolator\"\n android:toAlpha=\"1\" />\n</set>"
},
{
"code": null,
"e": 3684,
"s": 3621,
"text": "Step 5 − Add the following code to res/anim/right_to_left.xml."
},
{
"code": null,
"e": 4112,
"s": 3684,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:duration=\"500\">\n <translate\n android:fromXDelta=\"100%p\"\n android:interpolator=\"@android:anim/decelerate_interpolator\"\n android:toXDelta=\"0\" />\n <alpha\n android:fromAlpha=\"0.5\"\n android:interpolator=\"@android:anim/accelerate_decelerate_interpolator\"\n android:toAlpha=\"1\" />\n</set>"
},
{
"code": null,
"e": 4172,
"s": 4112,
"text": "Step 6 − Add the following code to res/anim/up_to_down.xml."
},
{
"code": null,
"e": 4844,
"s": 4172,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:duration=\"500\">\n <translate\n android:fromYDelta=\"-25%\"\n android:interpolator=\"@android:anim/decelerate_interpolator\"\n android:toYDelta=\"0\" />\n <alpha\n android:fromAlpha=\"0\"\n android:interpolator=\"@android:anim/decelerate_interpolator\"\n android:toAlpha=\"1\" />\n <scale\n android:fromXScale=\"125%\"\n android:fromYScale=\"125%\"\n android:interpolator=\"@android:anim/decelerate_interpolator\"\n android:pivotX=\"50%\"\n android:pivotY=\"50%\"\n android:toXScale=\"100%\"\n android:toYScale=\"100%\" />\n</set>"
},
{
"code": null,
"e": 4921,
"s": 4844,
"text": "Step 7 − Add the following code to res/anim/layout_animation_down_to_up.xml."
},
{
"code": null,
"e": 5137,
"s": 4921,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layoutAnimation xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:animation=\"@anim/down_to_up\"\n android:animationOrder=\"normal\"\n android:delay=\"15%\" />"
},
{
"code": null,
"e": 5216,
"s": 5137,
"text": "Step 8 − Add the following code to res/anim/layout_animation_left_to_right.xml"
},
{
"code": null,
"e": 5435,
"s": 5216,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layoutAnimation xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:animation=\"@anim/left_to_right\"\n android:animationOrder=\"normal\"\n android:delay=\"15%\" />"
},
{
"code": null,
"e": 5514,
"s": 5435,
"text": "Step 9 − Add the following code to res/anim/layout_animation_right_to_left.xml"
},
{
"code": null,
"e": 5733,
"s": 5514,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layoutAnimation xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:animation=\"@anim/right_to_left\"\n android:animationOrder=\"normal\"\n android:delay=\"15%\" />"
},
{
"code": null,
"e": 5810,
"s": 5733,
"text": "Step 10 − Add the following code to res/anim/layout_animation_up_to_down.xml"
},
{
"code": null,
"e": 6026,
"s": 5810,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layoutAnimation xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:animation=\"@anim/up_to_down\"\n android:animationOrder=\"normal\"\n android:delay=\"15%\" />"
},
{
"code": null,
"e": 6084,
"s": 6026,
"text": "Step 11 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 8235,
"s": 6084,
"text": "package com.journaldev.androidrecyclerviewlayoutanimation;\nimport android.support.design.widget.FloatingActionButton;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.GridLayoutAnimationController;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.Spinner;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n FloatingActionButton fab;\n RecyclerView recyclerView;\n RecyclerViewAdapter recyclerViewAdapter;\n ArrayList<String>> arrayList = new ArrayList<>();\n int[] animationList = {R.anim.layout_animation_up_to_down,\n R.anim.layout_animation_right_to_left,\n R.anim.layout_animation_down_to_up,\n R.anim.layout_animation_left_to_right};\n int i = 0;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n fab = findViewById(R.id.fab);\n recyclerView = findViewById(R.id.recyclerView);\n populateData();\n initAdapter();\n fab.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (i < animationList.length - 1) {\n i++;\n } else {\n i = 0;\n }\n runAnimationAgain();\n }\n });\n }\n private void populateData() {\n for (int i = 0; i < 12; i++) {\n arrayList.add(\"Item \" + i);\n }\n }\n private void initAdapter() {\n recyclerViewAdapter = new RecyclerViewAdapter(arrayList);\n recyclerView.setAdapter(recyclerViewAdapter);\n }\n private void runAnimationAgain() {\n final LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(this, animationList[i]);\n recyclerView.setLayoutAnimation(controller);\n recyclerViewAdapter.notifyDataSetChanged();\n recyclerView.scheduleLayoutAnimation();\n }\n}"
},
{
"code": null,
"e": 8301,
"s": 8235,
"text": "Step 12 − Add the following code to Manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 9009,
"s": 8301,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.journaldev.androidrecyclerviewlayoutanimation\">\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": 9360,
"s": 9009,
"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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 9401,
"s": 9360,
"text": "Click here to download the project code."
}
] |
Evaluating Performance of Models. Log reg/classification evaluation... | by Michelle Venables | Towards Data Science | After completing some data science projects in logistic regression and binary classification I have decided to write more about the evaluation of our models and steps to take to make sure they are running efficiently and accurately. You may have “good” data and understand how to build a model, but if you are able to interpret the efficiency of your model you’ll be able to interpret your results and provide the ultimate business decisions!
With regression, we predict continuous variables so it makes sense to discuss error as a distance of how far off our estimates are. With classification problems, we are dealing with binary variables so our model is either right or wrong. As a result, we examine a few specific measurements when evaluating performance of a classification algorithm.
Precision — measures how precise the predictions are.Recall — indicates what percentage of the classes we’re interested in were actually captured by the model.Accuracy is probably the most intuitive metric. We use it to measure the total number of predictions a model gets right, including both True Positives and True Negatives.F1 score is a measurement that considers both precision and recall to compute the score. It can be interpreted as a weighted average of the precision and recall values and cannot be high without both precision and recall also being high. When a model’s F1 score is high, you know that your model is doing well all around.
Precision — measures how precise the predictions are.
Recall — indicates what percentage of the classes we’re interested in were actually captured by the model.
Accuracy is probably the most intuitive metric. We use it to measure the total number of predictions a model gets right, including both True Positives and True Negatives.
F1 score is a measurement that considers both precision and recall to compute the score. It can be interpreted as a weighted average of the precision and recall values and cannot be high without both precision and recall also being high. When a model’s F1 score is high, you know that your model is doing well all around.
Example: Predict if an employee is Employed or Not Employed (Active). In this project we ideally what to predict if a candidate is a good fit for the company.
Precision: “Out of all the times the model said someone was employed, how many times did the employee in question actually have a job at “Dental Magic?”
Recall: “Out of all the employees we saw that actually were employed, what percentage of them did our model correctly identify as having active employment?”
Precision and recall have an inverse relationship. As one goes up the other will go down.
This is a classic data science question. What is better more false positives or false negatives? The answer is “IT DEPENDS ON THE PROBLEM” and can test your critical thinking abilities. So let’s examine a new example.
Detecting credit card fraud, a false positive would be when our model flags a transaction as fraudulent and it isn’t. This results in a slightly annoyed customer. A false negative might be a fraudulent transaction that a company mistakenly lets through as normal consumer behavior. In this case, the credit card company could be on the hook for reimbursing the customer for thousands of dollars because they missed the signs that the transaction was fraudulent! Although being wrong is never ideal, it makes sense that credit card companies tend to build their models to be a bit too sensitive, because having a high recall saves them more money than having a high precision score.
Let’s analyze our HR example. Our model wants to predict whether a person will fit within the company “employed vs non-employed”. In this situation we ideally want both to be low: false negatives and false positives. As an HR employee we’d like our false positives to be higher than false negatives and here’s why. With a higher false positive our model predicts our candidate is a good fit when they are actually not... This is just the first round of interviewing scans of candidates, we would rather look through more resumes than miss out on one potentially good candidate for the role. The ultimate hiring decision comes down a persons final decision.
When evaluating models we want to visualize an ROC Curve. Illustrating the true positive rate against the false positive rate of our classifier. True positive rate is another name for recall which is a ratio of the true positive predictions compared to all values that are actually positive.
TPR = TP/(TP+FN)
False positive rates is the ratio of false positive predictions compared to all values that are actually negative.
FPR = FP/(FP+TN)
If TPR is our y-axis and FPR is our x-axis, we want our ROC curve to hug the left side of our chart meaning higher the TPR the lower the FPR.
The logistic regression model produces probabilities that each observation’s specific class. Imagine it looking like the image below:
If we alter cutoff point it will sacrifice precision, increasing the FPR in order to increase the TPR or vice versa. Shifting the decision boundary to the left from 0.5 will result in capturing more of the positive class (1) cases. It will also pick up some false positives (red cases at the far right of the negative (0) case distribution).
Models with poor ROC might have large overlaps in the probability estimates for the two classes. This will indicate that our model had difficulty separating the two classes from each other.
Let’s see an example:
#Import roc_curve, aucfrom sklearn.metrics import roc_curve, auc#Calculate the probability scores of each point in the training sety_train_score = model_log.decision_function(X_train)# Calculate the fpr, tpr, and thresholds for the training settrain_fpr, train_tpr, thresholds = roc_curve(y_train, y_train_score)#Calculate the probability scores of each point in the test sety_test_score = model_log.decision_function(X_test)#Calculate the fpr, tpr, and thresholds for the test settest_fpr, test_tpr, test_thresholds = roc_curve(y_test, y_test_score)
Using Matplotlib we want to visualize our ROC Curve:
plt.plot(test_fpr, test_tpr, color='darkorange', lw=lw, label='ROC curve')
As shown to the left you can see that our classification models TPR vs FPR. Think about the scenario of this model: predicting employees fit within the company. If you tune the current model to have an 76% True Positive Rate, (you’ve still missed 29% of those who would be a good fit), what is the False positive rate?
When TPR = 75% then the FPR is 22%. The true positive rate determines the percentage of employees that are active who are who are correctly identified as a good fit. At the same time, this has a FPR of nearly .25 meaning that roughly one in four times we incorrectly warn an employee of being a good fit when they are actually not performing well.
Test AUC: 0.8041
The overall accuracy of a classifier can be quantified by the AUC, the Area Under the Curve. Perfect classifiers would have an AUC score of 1.0 while an AUC of 0.5 is worthless. Here we have and AUC of .80 which seems to be accurate.
An Introduction to Statistical Learning. Gareth James Trevor Hastie Robert Tibshirani Daniela Witten
Michelle Venables — Github | [
{
"code": null,
"e": 615,
"s": 172,
"text": "After completing some data science projects in logistic regression and binary classification I have decided to write more about the evaluation of our models and steps to take to make sure they are running efficiently and accurately. You may have “good” data and understand how to build a model, but if you are able to interpret the efficiency of your model you’ll be able to interpret your results and provide the ultimate business decisions!"
},
{
"code": null,
"e": 964,
"s": 615,
"text": "With regression, we predict continuous variables so it makes sense to discuss error as a distance of how far off our estimates are. With classification problems, we are dealing with binary variables so our model is either right or wrong. As a result, we examine a few specific measurements when evaluating performance of a classification algorithm."
},
{
"code": null,
"e": 1615,
"s": 964,
"text": "Precision — measures how precise the predictions are.Recall — indicates what percentage of the classes we’re interested in were actually captured by the model.Accuracy is probably the most intuitive metric. We use it to measure the total number of predictions a model gets right, including both True Positives and True Negatives.F1 score is a measurement that considers both precision and recall to compute the score. It can be interpreted as a weighted average of the precision and recall values and cannot be high without both precision and recall also being high. When a model’s F1 score is high, you know that your model is doing well all around."
},
{
"code": null,
"e": 1669,
"s": 1615,
"text": "Precision — measures how precise the predictions are."
},
{
"code": null,
"e": 1776,
"s": 1669,
"text": "Recall — indicates what percentage of the classes we’re interested in were actually captured by the model."
},
{
"code": null,
"e": 1947,
"s": 1776,
"text": "Accuracy is probably the most intuitive metric. We use it to measure the total number of predictions a model gets right, including both True Positives and True Negatives."
},
{
"code": null,
"e": 2269,
"s": 1947,
"text": "F1 score is a measurement that considers both precision and recall to compute the score. It can be interpreted as a weighted average of the precision and recall values and cannot be high without both precision and recall also being high. When a model’s F1 score is high, you know that your model is doing well all around."
},
{
"code": null,
"e": 2428,
"s": 2269,
"text": "Example: Predict if an employee is Employed or Not Employed (Active). In this project we ideally what to predict if a candidate is a good fit for the company."
},
{
"code": null,
"e": 2581,
"s": 2428,
"text": "Precision: “Out of all the times the model said someone was employed, how many times did the employee in question actually have a job at “Dental Magic?”"
},
{
"code": null,
"e": 2738,
"s": 2581,
"text": "Recall: “Out of all the employees we saw that actually were employed, what percentage of them did our model correctly identify as having active employment?”"
},
{
"code": null,
"e": 2828,
"s": 2738,
"text": "Precision and recall have an inverse relationship. As one goes up the other will go down."
},
{
"code": null,
"e": 3046,
"s": 2828,
"text": "This is a classic data science question. What is better more false positives or false negatives? The answer is “IT DEPENDS ON THE PROBLEM” and can test your critical thinking abilities. So let’s examine a new example."
},
{
"code": null,
"e": 3728,
"s": 3046,
"text": "Detecting credit card fraud, a false positive would be when our model flags a transaction as fraudulent and it isn’t. This results in a slightly annoyed customer. A false negative might be a fraudulent transaction that a company mistakenly lets through as normal consumer behavior. In this case, the credit card company could be on the hook for reimbursing the customer for thousands of dollars because they missed the signs that the transaction was fraudulent! Although being wrong is never ideal, it makes sense that credit card companies tend to build their models to be a bit too sensitive, because having a high recall saves them more money than having a high precision score."
},
{
"code": null,
"e": 4385,
"s": 3728,
"text": "Let’s analyze our HR example. Our model wants to predict whether a person will fit within the company “employed vs non-employed”. In this situation we ideally want both to be low: false negatives and false positives. As an HR employee we’d like our false positives to be higher than false negatives and here’s why. With a higher false positive our model predicts our candidate is a good fit when they are actually not... This is just the first round of interviewing scans of candidates, we would rather look through more resumes than miss out on one potentially good candidate for the role. The ultimate hiring decision comes down a persons final decision."
},
{
"code": null,
"e": 4677,
"s": 4385,
"text": "When evaluating models we want to visualize an ROC Curve. Illustrating the true positive rate against the false positive rate of our classifier. True positive rate is another name for recall which is a ratio of the true positive predictions compared to all values that are actually positive."
},
{
"code": null,
"e": 4694,
"s": 4677,
"text": "TPR = TP/(TP+FN)"
},
{
"code": null,
"e": 4809,
"s": 4694,
"text": "False positive rates is the ratio of false positive predictions compared to all values that are actually negative."
},
{
"code": null,
"e": 4826,
"s": 4809,
"text": "FPR = FP/(FP+TN)"
},
{
"code": null,
"e": 4968,
"s": 4826,
"text": "If TPR is our y-axis and FPR is our x-axis, we want our ROC curve to hug the left side of our chart meaning higher the TPR the lower the FPR."
},
{
"code": null,
"e": 5102,
"s": 4968,
"text": "The logistic regression model produces probabilities that each observation’s specific class. Imagine it looking like the image below:"
},
{
"code": null,
"e": 5444,
"s": 5102,
"text": "If we alter cutoff point it will sacrifice precision, increasing the FPR in order to increase the TPR or vice versa. Shifting the decision boundary to the left from 0.5 will result in capturing more of the positive class (1) cases. It will also pick up some false positives (red cases at the far right of the negative (0) case distribution)."
},
{
"code": null,
"e": 5634,
"s": 5444,
"text": "Models with poor ROC might have large overlaps in the probability estimates for the two classes. This will indicate that our model had difficulty separating the two classes from each other."
},
{
"code": null,
"e": 5656,
"s": 5634,
"text": "Let’s see an example:"
},
{
"code": null,
"e": 6207,
"s": 5656,
"text": "#Import roc_curve, aucfrom sklearn.metrics import roc_curve, auc#Calculate the probability scores of each point in the training sety_train_score = model_log.decision_function(X_train)# Calculate the fpr, tpr, and thresholds for the training settrain_fpr, train_tpr, thresholds = roc_curve(y_train, y_train_score)#Calculate the probability scores of each point in the test sety_test_score = model_log.decision_function(X_test)#Calculate the fpr, tpr, and thresholds for the test settest_fpr, test_tpr, test_thresholds = roc_curve(y_test, y_test_score)"
},
{
"code": null,
"e": 6260,
"s": 6207,
"text": "Using Matplotlib we want to visualize our ROC Curve:"
},
{
"code": null,
"e": 6335,
"s": 6260,
"text": "plt.plot(test_fpr, test_tpr, color='darkorange', lw=lw, label='ROC curve')"
},
{
"code": null,
"e": 6654,
"s": 6335,
"text": "As shown to the left you can see that our classification models TPR vs FPR. Think about the scenario of this model: predicting employees fit within the company. If you tune the current model to have an 76% True Positive Rate, (you’ve still missed 29% of those who would be a good fit), what is the False positive rate?"
},
{
"code": null,
"e": 7002,
"s": 6654,
"text": "When TPR = 75% then the FPR is 22%. The true positive rate determines the percentage of employees that are active who are who are correctly identified as a good fit. At the same time, this has a FPR of nearly .25 meaning that roughly one in four times we incorrectly warn an employee of being a good fit when they are actually not performing well."
},
{
"code": null,
"e": 7019,
"s": 7002,
"text": "Test AUC: 0.8041"
},
{
"code": null,
"e": 7253,
"s": 7019,
"text": "The overall accuracy of a classifier can be quantified by the AUC, the Area Under the Curve. Perfect classifiers would have an AUC score of 1.0 while an AUC of 0.5 is worthless. Here we have and AUC of .80 which seems to be accurate."
},
{
"code": null,
"e": 7354,
"s": 7253,
"text": "An Introduction to Statistical Learning. Gareth James Trevor Hastie Robert Tibshirani Daniela Witten"
}
] |
Deep dive into ROC-AUC. deep dive into ROC-AUC | by Songhao Wu | Towards Data Science | I believe most people have heard of the ROC curve or Area under the Curve before if you are interested in data science. However, what exactly is the ROC curve, and why area under the ROC curve is a good metric to evaluate the classification model? I have briefly walked through in my previous article on top metrics for classification but I will go through in more detail in this article.
The full name for ROC is Receiver Operating Characteristic. It was first created for the usage of radar signal detection during World War II. The US has used it to improve the accuracy of detecting Japanese Aircraft from Radar. That is why it is called receiver operating characteristic.
AUC or the area under the curve is just the area under the ROC curve. Before we go into what is ROC curve, we need to understand quickly is Confusion Matrix.
As you can see from the picture above, the confusion matrix is the combination of your prediction(1 or 0) vs actual value(1 or 0). Based on your prediction value and whether you have correctly classified it is divided into 4 sections. For example, true positive is the number of cases that you correctly classify the case to be positive while false positive means the number of cases that you wrongly classify the case to be positive.
The confusion matrix contains only absolute numbers. However, based on these numbers, we can develop many new percentage-based metrics. True Positive Rate and False Positive Rate are two of them.
True Positive Rate(TPR): Among the truly positive cases, how much percentage of them are captured in the model correctly
True Positive Rate(TPR): Among the truly positive cases, how much percentage of them are captured in the model correctly
TPR=TP/(TP+FN)
False Positive Rate(NPR): Among the truly negative cases, how much percentage of them are actually false positive.
False Positive Rate(NPR): Among the truly negative cases, how much percentage of them are actually false positive.
NPR=FP/(FP+TN)
Ok let us go into ROC curve now!
As you can see from the graph, the ROC curve is simply TPR plotted against NPR. Ok end of the story...
Just Joking!
There are a lot more information you can read from the chart. The first thing I want to ask here is : There is only one set of TPR,FPR for the model result and how do you form so many points to plot the graph?
This goes back to how the classification model works. When you build a classification model like a decision tree and you want to classify maybe whether the stock will increase or decrease tomorrow based on the input. The classification model will first calculate the probability of increase or decrease based on the historical value you provided. After that, based on the threshold, it will decide whether the result is increasing or decreasing.
Yes, the keyword here is the threshold. Different threshold creates different TPR and FPR. They represent different points and form up the ROC curve. You can choose the output to be ‘Increase’ if more than a 50% chance of increase based on historical data but you can also increase the threshold and only show ‘Increase’ if more than a 90% chance. If you choose 90% confidence instead of 50%, you will be more confident that the stocks you choose to show ‘Increase’ are very likely to increase but you may miss out on some potential stocks.
As we know the bigger the area under the curve(AUC), the better the classification. The ideal or perfect curve is a vertical line from (0,0) to (0,1) and then to (1,1) which means the model can 100% separate positive and negative cases. However, if you pick randomly for each case, TPR and FPR should increase at the same rate. The blue dotted line shows the curve TPR and FPR when you blindly guess positive or negative for each case and for that diagonal line, the area under the curve(AUC) is 0.5.
Look at the two dots on the ROC curve. Green dot has a very high threshold it means only if you are 99% sure then you can classify the case as positive. The red dot has a relatively lower threshold and it means you can classify the case to be positive if you are 90% confident.
Whats the movement of TPR and FPR from green dot to red dot?
Both TPR and FPR increase. When you reduce the threshold, more positive cases can be identified, thus TP increases, and TP/(TP+FN) also increases. On the other side, inevitably you will wrongly classify some negative cases to be positive due to the lowering of threshold and so FP & FP/(FP+TN) also increases.
We can see that TPR and FPR are positively correlated and you have to balance between maximizing capture of positive cases and minimizing the wrong classification of negative cases.
It is hard to define the optimal point because you should choose the most suitable threshold for the business case. However, the general rule is to maximize (TPR-FPR) which in the graph is represented by the vertical distance between the orange and blue dotted line.
We can see from the chart above that among the three points, redpoint has the biggest TPR-FPR and should be considered as the optimal point. Moving from red point to green point, the threshold gets more strict. However, a big number of positive cases are not captured from the model with a less than proportionate decrease in wrongly classified cases. Moving from the red point to the blue point, the threshold is getting more lenient and adding more wrongly classified positive points than correctly identified positive points.
A good metric of a machine learning model should display the true and consistent prediction ability of the model. It means if I change the testing dataset it should not have a very different score.
ROC curve does not only consider the classification results but also the prediction probability of all classes. For example, if the output is classified correctly based on 51% probability, then it is very likely to be wrongly classified if you use another testing dataset. In addition, the ROC curve also considers the performance across the different thresholds and so it is a comprehensive metric to assess how good the separation of the cases in different groups.
As I have shown before, for the binary classification problems, if you pick randomly you can achieve 0.5 AUC. Thus, if you are solving a binary classification problem, a reasonable ROC score should>0.5. A good classification model usually has AUC score >0.9 but it is totally application dependent.
If you just want to find AUC score, you can refer to sklearn metric package here.
If you want to plot the ROC curve for your model results you can refer to here
# Calculate FPR, TPR and AUCfrom sklearn.metrics import roc_curve, aucfpr, tpr, treshold = roc_curve(y_test, y_score_new)roc_auc = auc(fpr, tpr)#Plot ROC curveplt.plot(fpr, tpr, color='darkorange', label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc="lower right")plt.show()
Here is the code for me to plot the ROC example plot which I used in this article. You need two inputs which are the true value of y and also prediction probability. Note that the roc_curve function only needs probability for the positive cases but not the probability for both classes. If you have a multi-class classification problem, you can also use the package and there is an example of how to plot it in the link above.
If you are interested to know what are the other top metrics for the evaluation of the classification model, you can refer to the link below: | [
{
"code": null,
"e": 561,
"s": 172,
"text": "I believe most people have heard of the ROC curve or Area under the Curve before if you are interested in data science. However, what exactly is the ROC curve, and why area under the ROC curve is a good metric to evaluate the classification model? I have briefly walked through in my previous article on top metrics for classification but I will go through in more detail in this article."
},
{
"code": null,
"e": 849,
"s": 561,
"text": "The full name for ROC is Receiver Operating Characteristic. It was first created for the usage of radar signal detection during World War II. The US has used it to improve the accuracy of detecting Japanese Aircraft from Radar. That is why it is called receiver operating characteristic."
},
{
"code": null,
"e": 1007,
"s": 849,
"text": "AUC or the area under the curve is just the area under the ROC curve. Before we go into what is ROC curve, we need to understand quickly is Confusion Matrix."
},
{
"code": null,
"e": 1442,
"s": 1007,
"text": "As you can see from the picture above, the confusion matrix is the combination of your prediction(1 or 0) vs actual value(1 or 0). Based on your prediction value and whether you have correctly classified it is divided into 4 sections. For example, true positive is the number of cases that you correctly classify the case to be positive while false positive means the number of cases that you wrongly classify the case to be positive."
},
{
"code": null,
"e": 1638,
"s": 1442,
"text": "The confusion matrix contains only absolute numbers. However, based on these numbers, we can develop many new percentage-based metrics. True Positive Rate and False Positive Rate are two of them."
},
{
"code": null,
"e": 1759,
"s": 1638,
"text": "True Positive Rate(TPR): Among the truly positive cases, how much percentage of them are captured in the model correctly"
},
{
"code": null,
"e": 1880,
"s": 1759,
"text": "True Positive Rate(TPR): Among the truly positive cases, how much percentage of them are captured in the model correctly"
},
{
"code": null,
"e": 1895,
"s": 1880,
"text": "TPR=TP/(TP+FN)"
},
{
"code": null,
"e": 2010,
"s": 1895,
"text": "False Positive Rate(NPR): Among the truly negative cases, how much percentage of them are actually false positive."
},
{
"code": null,
"e": 2125,
"s": 2010,
"text": "False Positive Rate(NPR): Among the truly negative cases, how much percentage of them are actually false positive."
},
{
"code": null,
"e": 2140,
"s": 2125,
"text": "NPR=FP/(FP+TN)"
},
{
"code": null,
"e": 2173,
"s": 2140,
"text": "Ok let us go into ROC curve now!"
},
{
"code": null,
"e": 2276,
"s": 2173,
"text": "As you can see from the graph, the ROC curve is simply TPR plotted against NPR. Ok end of the story..."
},
{
"code": null,
"e": 2289,
"s": 2276,
"text": "Just Joking!"
},
{
"code": null,
"e": 2499,
"s": 2289,
"text": "There are a lot more information you can read from the chart. The first thing I want to ask here is : There is only one set of TPR,FPR for the model result and how do you form so many points to plot the graph?"
},
{
"code": null,
"e": 2945,
"s": 2499,
"text": "This goes back to how the classification model works. When you build a classification model like a decision tree and you want to classify maybe whether the stock will increase or decrease tomorrow based on the input. The classification model will first calculate the probability of increase or decrease based on the historical value you provided. After that, based on the threshold, it will decide whether the result is increasing or decreasing."
},
{
"code": null,
"e": 3486,
"s": 2945,
"text": "Yes, the keyword here is the threshold. Different threshold creates different TPR and FPR. They represent different points and form up the ROC curve. You can choose the output to be ‘Increase’ if more than a 50% chance of increase based on historical data but you can also increase the threshold and only show ‘Increase’ if more than a 90% chance. If you choose 90% confidence instead of 50%, you will be more confident that the stocks you choose to show ‘Increase’ are very likely to increase but you may miss out on some potential stocks."
},
{
"code": null,
"e": 3987,
"s": 3486,
"text": "As we know the bigger the area under the curve(AUC), the better the classification. The ideal or perfect curve is a vertical line from (0,0) to (0,1) and then to (1,1) which means the model can 100% separate positive and negative cases. However, if you pick randomly for each case, TPR and FPR should increase at the same rate. The blue dotted line shows the curve TPR and FPR when you blindly guess positive or negative for each case and for that diagonal line, the area under the curve(AUC) is 0.5."
},
{
"code": null,
"e": 4265,
"s": 3987,
"text": "Look at the two dots on the ROC curve. Green dot has a very high threshold it means only if you are 99% sure then you can classify the case as positive. The red dot has a relatively lower threshold and it means you can classify the case to be positive if you are 90% confident."
},
{
"code": null,
"e": 4326,
"s": 4265,
"text": "Whats the movement of TPR and FPR from green dot to red dot?"
},
{
"code": null,
"e": 4636,
"s": 4326,
"text": "Both TPR and FPR increase. When you reduce the threshold, more positive cases can be identified, thus TP increases, and TP/(TP+FN) also increases. On the other side, inevitably you will wrongly classify some negative cases to be positive due to the lowering of threshold and so FP & FP/(FP+TN) also increases."
},
{
"code": null,
"e": 4818,
"s": 4636,
"text": "We can see that TPR and FPR are positively correlated and you have to balance between maximizing capture of positive cases and minimizing the wrong classification of negative cases."
},
{
"code": null,
"e": 5085,
"s": 4818,
"text": "It is hard to define the optimal point because you should choose the most suitable threshold for the business case. However, the general rule is to maximize (TPR-FPR) which in the graph is represented by the vertical distance between the orange and blue dotted line."
},
{
"code": null,
"e": 5614,
"s": 5085,
"text": "We can see from the chart above that among the three points, redpoint has the biggest TPR-FPR and should be considered as the optimal point. Moving from red point to green point, the threshold gets more strict. However, a big number of positive cases are not captured from the model with a less than proportionate decrease in wrongly classified cases. Moving from the red point to the blue point, the threshold is getting more lenient and adding more wrongly classified positive points than correctly identified positive points."
},
{
"code": null,
"e": 5812,
"s": 5614,
"text": "A good metric of a machine learning model should display the true and consistent prediction ability of the model. It means if I change the testing dataset it should not have a very different score."
},
{
"code": null,
"e": 6279,
"s": 5812,
"text": "ROC curve does not only consider the classification results but also the prediction probability of all classes. For example, if the output is classified correctly based on 51% probability, then it is very likely to be wrongly classified if you use another testing dataset. In addition, the ROC curve also considers the performance across the different thresholds and so it is a comprehensive metric to assess how good the separation of the cases in different groups."
},
{
"code": null,
"e": 6578,
"s": 6279,
"text": "As I have shown before, for the binary classification problems, if you pick randomly you can achieve 0.5 AUC. Thus, if you are solving a binary classification problem, a reasonable ROC score should>0.5. A good classification model usually has AUC score >0.9 but it is totally application dependent."
},
{
"code": null,
"e": 6660,
"s": 6578,
"text": "If you just want to find AUC score, you can refer to sklearn metric package here."
},
{
"code": null,
"e": 6739,
"s": 6660,
"text": "If you want to plot the ROC curve for your model results you can refer to here"
},
{
"code": null,
"e": 7242,
"s": 6739,
"text": "# Calculate FPR, TPR and AUCfrom sklearn.metrics import roc_curve, aucfpr, tpr, treshold = roc_curve(y_test, y_score_new)roc_auc = auc(fpr, tpr)#Plot ROC curveplt.plot(fpr, tpr, color='darkorange', label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc=\"lower right\")plt.show()"
},
{
"code": null,
"e": 7669,
"s": 7242,
"text": "Here is the code for me to plot the ROC example plot which I used in this article. You need two inputs which are the true value of y and also prediction probability. Note that the roc_curve function only needs probability for the positive cases but not the probability for both classes. If you have a multi-class classification problem, you can also use the package and there is an example of how to plot it in the link above."
}
] |
Monitor System Power States in ElectronJS | 29 May, 2020
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
One such System behavior that can directly affect the execution of a native desktop application is System Power and changes in its state. For example, the developers would like to know when the system switches from charging to battery power and vice-versa so that they can automatically adjust the brightness of the system via the application to consume less battery power. Similarly, when the system is about to be suspended or shut-down, the application can be made aware and take necessary action such as exit cleanly, etc. Electron provides us with a way by which we can monitor the System Power State Changes using the built-in powerMonitor Module. This tutorial will demonstrate how to monitor these system power states using the powerMonitor Module Instance methods and events.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
System Power State Changes in ElectronJS: The powerMonitor Module is part of the Main Process. To import and use this Module in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link. The powerMonitor Module cannot be used until the ready event of the app module is emitted and the application is ready to create BrowserWindow Instances. For more Information, Refer this link.
Project Structure:
Example: We will start by building the Electron Application for Monitoring System Power State Changes by following the given steps.
Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:{
"name": "electron-power",
"version": "1.0.0",
"description": "Power State Changes in Electron ",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
npm init
To generate the package.json file. Install Electron using npm if it is not installed.
npm install electron --save
This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:
{
"name": "electron-power",
"version": "1.0.0",
"description": "Power State Changes in Electron ",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'// The powerMonitor Module cannot be used until this event is emitted.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.
main.js:
const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'// The powerMonitor Module cannot be used until this event is emitted.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.
Step 3: Create the index.html file and the index.js file within the src directory according to the project structure. We will also copy the Boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:npm start
index.html:
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>
Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:
npm start
Step 4: We are going to monitor the System Power State Changes throughout the Application without binding this module to any HTML DOM element.index.js: Add the following snippet in that file.const electron = require('electron');// Importing powerMonitor from Main Process // Using remote Moduleconst powerMonitor = electron.remote.powerMonitor; powerMonitor.on('suspend', () => { console.log('The system is going to sleep');}); powerMonitor.on('resume', () => { console.log('The system is resuming');}); powerMonitor.on('on-ac', () => { console.log('The system is on AC Power (charging)');}); powerMonitor.on('on-battery', () => { console.log('The system is on Battery Power');}); powerMonitor.on('shutdown', () => { console.log('The system is Shutting Down');}); powerMonitor.on('lock-screen', () => { console.log('The system is about to be locked');}); powerMonitor.on('unlock-screen', () => { console.log('The system is unlocked');}); const state = powerMonitor.getSystemIdleState(4);console.log('Current System State - ', state); const idle = powerMonitor.getSystemIdleTime();console.log('Current System Idle Time - ', idle);Explanation: A detailed Explanation of all the Instance events of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link.suspend: Event Emitted when the System is about to be Suspended or going into Sleep Mode.resume: Event Emitted when the System is resuming from Suspended State or Sleep Mode.on-ac: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to AC Power and the system is being operated on electricity such as when charging laptops. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output.on-battery: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to Battery Power and the system is being operated on battery. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output.shutdown: Event This Instance Event is supported in Linux and macOS only. This event is emitted when the System is about to restart or shut down. If the event handler invokes e.preventDefault() method from the global event object, Electron will make an attempt to delay the System from shutting down in order for the application to exit cleanly. When this method is called, the applications should exit immediately using the app.quit() method as used in the main.js file to stop all background processes and close any open BrowserWindow Instances. For more detailed Information on the app.quit() method and all the Instance events associated with it, Refer this link.lock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted when the system is about to lock the screen. On Windows, this functionality is triggered by Windows+L.unlock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted as soon as the Systems screen is Unlocked.A detailed Explanation of all the Instance methods of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link.powerMonitor.getSystemIdleState(idleThreshold) This method is used to calculate the System idle state and it returns the systems current State based on the idleThreshold value provided. The idleThreshold value is the amount of time (in seconds) before the system can be considered to be in Idle State. This method returns a String value representing the current State of the System. Return Values can be active, idle, locked or unknown. In the above code, we have taken 4s as the idleThreshold and we should get active as the return value.Note – The Return value locked is available on select System environments only.powerMonitor.getSystemIdleTime() This method is used to calculate the time in seconds for which the system has been in idle state. It does not take in any parameters. It returns an Integer value representing the system idle time in seconds.
const electron = require('electron');// Importing powerMonitor from Main Process // Using remote Moduleconst powerMonitor = electron.remote.powerMonitor; powerMonitor.on('suspend', () => { console.log('The system is going to sleep');}); powerMonitor.on('resume', () => { console.log('The system is resuming');}); powerMonitor.on('on-ac', () => { console.log('The system is on AC Power (charging)');}); powerMonitor.on('on-battery', () => { console.log('The system is on Battery Power');}); powerMonitor.on('shutdown', () => { console.log('The system is Shutting Down');}); powerMonitor.on('lock-screen', () => { console.log('The system is about to be locked');}); powerMonitor.on('unlock-screen', () => { console.log('The system is unlocked');}); const state = powerMonitor.getSystemIdleState(4);console.log('Current System State - ', state); const idle = powerMonitor.getSystemIdleTime();console.log('Current System Idle Time - ', idle);
Explanation: A detailed Explanation of all the Instance events of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link.
suspend: Event Emitted when the System is about to be Suspended or going into Sleep Mode.
resume: Event Emitted when the System is resuming from Suspended State or Sleep Mode.
on-ac: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to AC Power and the system is being operated on electricity such as when charging laptops. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output.
on-battery: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to Battery Power and the system is being operated on battery. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output.
shutdown: Event This Instance Event is supported in Linux and macOS only. This event is emitted when the System is about to restart or shut down. If the event handler invokes e.preventDefault() method from the global event object, Electron will make an attempt to delay the System from shutting down in order for the application to exit cleanly. When this method is called, the applications should exit immediately using the app.quit() method as used in the main.js file to stop all background processes and close any open BrowserWindow Instances. For more detailed Information on the app.quit() method and all the Instance events associated with it, Refer this link.
lock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted when the system is about to lock the screen. On Windows, this functionality is triggered by Windows+L.
unlock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted as soon as the Systems screen is Unlocked.
A detailed Explanation of all the Instance methods of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link.
powerMonitor.getSystemIdleState(idleThreshold) This method is used to calculate the System idle state and it returns the systems current State based on the idleThreshold value provided. The idleThreshold value is the amount of time (in seconds) before the system can be considered to be in Idle State. This method returns a String value representing the current State of the System. Return Values can be active, idle, locked or unknown. In the above code, we have taken 4s as the idleThreshold and we should get active as the return value.Note – The Return value locked is available on select System environments only.
powerMonitor.getSystemIdleTime() This method is used to calculate the time in seconds for which the system has been in idle state. It does not take in any parameters. It returns an Integer value representing the system idle time in seconds.
Note – The powerMonitor module does not control the System behaviour such as Preventing the System from going to sleep, etc and is not to be confused with the powerSaveBlocker module.
Output:
Since putting the system into Sleep mode and reviving it cannot be recorded, here is the following output for those Instance events. For the system to go into Sleep Mode, the system performs the lock-screen operation. Similarly, when reviving the system from sleep mode, the system needs to be unlocked for access.Output:
ElectronJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
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
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 May, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime."
},
{
"code": null,
"e": 1113,
"s": 328,
"text": "One such System behavior that can directly affect the execution of a native desktop application is System Power and changes in its state. For example, the developers would like to know when the system switches from charging to battery power and vice-versa so that they can automatically adjust the brightness of the system via the application to consume less battery power. Similarly, when the system is about to be suspended or shut-down, the application can be made aware and take necessary action such as exit cleanly, etc. Electron provides us with a way by which we can monitor the System Power State Changes using the built-in powerMonitor Module. This tutorial will demonstrate how to monitor these system power states using the powerMonitor Module Instance methods and events."
},
{
"code": null,
"e": 1283,
"s": 1113,
"text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system."
},
{
"code": null,
"e": 1723,
"s": 1283,
"text": "System Power State Changes in ElectronJS: The powerMonitor Module is part of the Main Process. To import and use this Module in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link. The powerMonitor Module cannot be used until the ready event of the app module is emitted and the application is ready to create BrowserWindow Instances. For more Information, Refer this link."
},
{
"code": null,
"e": 1742,
"s": 1723,
"text": "Project Structure:"
},
{
"code": null,
"e": 1874,
"s": 1742,
"text": "Example: We will start by building the Electron Application for Monitoring System Power State Changes by following the given steps."
},
{
"code": null,
"e": 2647,
"s": 1874,
"text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:{\n \"name\": \"electron-power\",\n \"version\": \"1.0.0\",\n \"description\": \"Power State Changes in Electron \",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n"
},
{
"code": null,
"e": 2656,
"s": 2647,
"text": "npm init"
},
{
"code": null,
"e": 2742,
"s": 2656,
"text": "To generate the package.json file. Install Electron using npm if it is not installed."
},
{
"code": null,
"e": 2770,
"s": 2742,
"text": "npm install electron --save"
},
{
"code": null,
"e": 3023,
"s": 2770,
"text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:"
},
{
"code": null,
"e": 3333,
"s": 3023,
"text": "{\n \"name\": \"electron-power\",\n \"version\": \"1.0.0\",\n \"description\": \"Power State Changes in Electron \",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n"
},
{
"code": null,
"e": 4963,
"s": 3333,
"text": "Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'// The powerMonitor Module cannot be used until this event is emitted.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here."
},
{
"code": null,
"e": 4972,
"s": 4963,
"text": "main.js:"
},
{
"code": "const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'// The powerMonitor Module cannot be used until this event is emitted.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.",
"e": 6318,
"s": 4972,
"text": null
},
{
"code": null,
"e": 7465,
"s": 6318,
"text": "Step 3: Create the index.html file and the index.js file within the src directory according to the project structure. We will also copy the Boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:npm start"
},
{
"code": null,
"e": 7477,
"s": 7465,
"text": "index.html:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>",
"e": 8180,
"s": 7477,
"text": null
},
{
"code": null,
"e": 8341,
"s": 8180,
"text": "Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:"
},
{
"code": null,
"e": 8351,
"s": 8341,
"text": "npm start"
},
{
"code": null,
"e": 12508,
"s": 8351,
"text": "Step 4: We are going to monitor the System Power State Changes throughout the Application without binding this module to any HTML DOM element.index.js: Add the following snippet in that file.const electron = require('electron');// Importing powerMonitor from Main Process // Using remote Moduleconst powerMonitor = electron.remote.powerMonitor; powerMonitor.on('suspend', () => { console.log('The system is going to sleep');}); powerMonitor.on('resume', () => { console.log('The system is resuming');}); powerMonitor.on('on-ac', () => { console.log('The system is on AC Power (charging)');}); powerMonitor.on('on-battery', () => { console.log('The system is on Battery Power');}); powerMonitor.on('shutdown', () => { console.log('The system is Shutting Down');}); powerMonitor.on('lock-screen', () => { console.log('The system is about to be locked');}); powerMonitor.on('unlock-screen', () => { console.log('The system is unlocked');}); const state = powerMonitor.getSystemIdleState(4);console.log('Current System State - ', state); const idle = powerMonitor.getSystemIdleTime();console.log('Current System Idle Time - ', idle);Explanation: A detailed Explanation of all the Instance events of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link.suspend: Event Emitted when the System is about to be Suspended or going into Sleep Mode.resume: Event Emitted when the System is resuming from Suspended State or Sleep Mode.on-ac: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to AC Power and the system is being operated on electricity such as when charging laptops. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output.on-battery: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to Battery Power and the system is being operated on battery. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output.shutdown: Event This Instance Event is supported in Linux and macOS only. This event is emitted when the System is about to restart or shut down. If the event handler invokes e.preventDefault() method from the global event object, Electron will make an attempt to delay the System from shutting down in order for the application to exit cleanly. When this method is called, the applications should exit immediately using the app.quit() method as used in the main.js file to stop all background processes and close any open BrowserWindow Instances. For more detailed Information on the app.quit() method and all the Instance events associated with it, Refer this link.lock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted when the system is about to lock the screen. On Windows, this functionality is triggered by Windows+L.unlock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted as soon as the Systems screen is Unlocked.A detailed Explanation of all the Instance methods of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link.powerMonitor.getSystemIdleState(idleThreshold) This method is used to calculate the System idle state and it returns the systems current State based on the idleThreshold value provided. The idleThreshold value is the amount of time (in seconds) before the system can be considered to be in Idle State. This method returns a String value representing the current State of the System. Return Values can be active, idle, locked or unknown. In the above code, we have taken 4s as the idleThreshold and we should get active as the return value.Note – The Return value locked is available on select System environments only.powerMonitor.getSystemIdleTime() This method is used to calculate the time in seconds for which the system has been in idle state. It does not take in any parameters. It returns an Integer value representing the system idle time in seconds."
},
{
"code": "const electron = require('electron');// Importing powerMonitor from Main Process // Using remote Moduleconst powerMonitor = electron.remote.powerMonitor; powerMonitor.on('suspend', () => { console.log('The system is going to sleep');}); powerMonitor.on('resume', () => { console.log('The system is resuming');}); powerMonitor.on('on-ac', () => { console.log('The system is on AC Power (charging)');}); powerMonitor.on('on-battery', () => { console.log('The system is on Battery Power');}); powerMonitor.on('shutdown', () => { console.log('The system is Shutting Down');}); powerMonitor.on('lock-screen', () => { console.log('The system is about to be locked');}); powerMonitor.on('unlock-screen', () => { console.log('The system is unlocked');}); const state = powerMonitor.getSystemIdleState(4);console.log('Current System State - ', state); const idle = powerMonitor.getSystemIdleTime();console.log('Current System Idle Time - ', idle);",
"e": 13477,
"s": 12508,
"text": null
},
{
"code": null,
"e": 13653,
"s": 13477,
"text": "Explanation: A detailed Explanation of all the Instance events of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link."
},
{
"code": null,
"e": 13743,
"s": 13653,
"text": "suspend: Event Emitted when the System is about to be Suspended or going into Sleep Mode."
},
{
"code": null,
"e": 13829,
"s": 13743,
"text": "resume: Event Emitted when the System is resuming from Suspended State or Sleep Mode."
},
{
"code": null,
"e": 14148,
"s": 13829,
"text": "on-ac: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to AC Power and the system is being operated on electricity such as when charging laptops. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output."
},
{
"code": null,
"e": 14443,
"s": 14148,
"text": "on-battery: Event This Instance Event is supported in Windows only. This event is emitted when the system power state changes to Battery Power and the system is being operated on battery. To switch between AC and Battery power simply plug/unplug the charger of the laptop as done in the Output."
},
{
"code": null,
"e": 15111,
"s": 14443,
"text": "shutdown: Event This Instance Event is supported in Linux and macOS only. This event is emitted when the System is about to restart or shut down. If the event handler invokes e.preventDefault() method from the global event object, Electron will make an attempt to delay the System from shutting down in order for the application to exit cleanly. When this method is called, the applications should exit immediately using the app.quit() method as used in the main.js file to stop all background processes and close any open BrowserWindow Instances. For more detailed Information on the app.quit() method and all the Instance events associated with it, Refer this link."
},
{
"code": null,
"e": 15315,
"s": 15111,
"text": "lock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted when the system is about to lock the screen. On Windows, this functionality is triggered by Windows+L."
},
{
"code": null,
"e": 15461,
"s": 15315,
"text": "unlock-screen: Event This Instance Event is supported in Windows and macOS only. This event is emitted as soon as the Systems screen is Unlocked."
},
{
"code": null,
"e": 15625,
"s": 15461,
"text": "A detailed Explanation of all the Instance methods of the powerMonitor module used in the code are explained below. For more detailed Information, Refer this link."
},
{
"code": null,
"e": 16244,
"s": 15625,
"text": "powerMonitor.getSystemIdleState(idleThreshold) This method is used to calculate the System idle state and it returns the systems current State based on the idleThreshold value provided. The idleThreshold value is the amount of time (in seconds) before the system can be considered to be in Idle State. This method returns a String value representing the current State of the System. Return Values can be active, idle, locked or unknown. In the above code, we have taken 4s as the idleThreshold and we should get active as the return value.Note – The Return value locked is available on select System environments only."
},
{
"code": null,
"e": 16485,
"s": 16244,
"text": "powerMonitor.getSystemIdleTime() This method is used to calculate the time in seconds for which the system has been in idle state. It does not take in any parameters. It returns an Integer value representing the system idle time in seconds."
},
{
"code": null,
"e": 16669,
"s": 16485,
"text": "Note – The powerMonitor module does not control the System behaviour such as Preventing the System from going to sleep, etc and is not to be confused with the powerSaveBlocker module."
},
{
"code": null,
"e": 16677,
"s": 16669,
"text": "Output:"
},
{
"code": null,
"e": 16999,
"s": 16677,
"text": "Since putting the system into Sleep mode and reviving it cannot be recorded, here is the following output for those Instance events. For the system to go into Sleep Mode, the system performs the lock-screen operation. Similarly, when reviving the system from sleep mode, the system needs to be unlocked for access.Output:"
},
{
"code": null,
"e": 17010,
"s": 16999,
"text": "ElectronJS"
},
{
"code": null,
"e": 17021,
"s": 17010,
"text": "JavaScript"
},
{
"code": null,
"e": 17038,
"s": 17021,
"text": "Web Technologies"
},
{
"code": null,
"e": 17136,
"s": 17038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17197,
"s": 17136,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 17269,
"s": 17197,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 17309,
"s": 17269,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 17350,
"s": 17309,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 17396,
"s": 17350,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 17458,
"s": 17396,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 17491,
"s": 17458,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 17552,
"s": 17491,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 17602,
"s": 17552,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Morgan Stanley Interview | Set 1 | 24 Jul, 2019
Morgan Stanley campus placement for post IT analyst.
1st round – objective written test10 questions on aptitude and analytics30 questions on programming10 questions on computer fundamentalsThey had sectional cut-off and selected 20 students
2st round – coding written test5 questions on coding basically on data structures1. Write a function to find the mirror image of binary tree2. WAP to find the character which occurred maximum times in the character array3. Given a 2d matrix find an element in a matrix which is 0 and make the entire row and column to 04. Find the minimum element in the rotated array of integers5. Find highest length substring such that there are equal number of 0’s and 1’sin array of 1’s and 0’s only
3rd round – Technical interview1. He asked to tell something about me2. Then he asked a questions on my projects and internship3. Then he asked me to write a modified bubble sort4. Asked me to design a structure for storing stock market details for every quote/ company and store it as a linked list and asked me to write a linked list function like insertion and initialization5. Then he asked me to store the live data of particular company of every 5 minutes and the history should be of 10 days, so it’s a huge amount of data so it’s very inefficient to use linked list so suggested to use hash map or circular array as it of fix size of 10 days.6. There were other simple questions on data structures and databases
4th round – Group Task/DiscussionThe group was formed by 6 people. They provided some 8-10 pictures based on business ethics and then we have to form a story using this pictures in 15 minutes and after this time they provided again 6 pictures and we have to include it in our story. And then we have to tell the story in group in 2 minutes. Then they asked some questions and asked us to rate everyone else in the group.
5th round – technical interviewMost of the questions were on databases and operating systems. Then some are probability questions1. If your friend is being pointed by a gun by his enemy, consider a barrel of 6 bullets but it has only 2 bullets which were consecutive too, then an enemy rotates the barrel and push into a gun then he fires the trigger but the shit was empty, then he gave a choice for 2 shot that do you want to rotate the barrel again(randomly) or continue in this position only, so we have to find both the probabilities and find which one is lesser so that we can save our friend2. The other question was we have to print10 – 60% of the time we execute the program20 – 10% of – –15 – 30% of –So we have to write a code so that when we execute the code for 100 times there will be 60 – 10’s, 10 – 20’s, 30 – 15’sThen asked me to draw tables for database of college for students, professors, time table and courses.
6th round – HR interviewBefore going for HR interview we have to fill the form which has some common questions and all things about you like books you read, hobbies, place where you want to work, about post grad.Normal HR round was there and asked some common questions such as about me, my past, my grades, interests, hobbies, pros – cons, achievements.Also about future plans like post grad and position after 5 years, then he given some puzzles to solve the 100 prisons and 100 prisoners question to toggle the doors
I really really thank geeksforgeeks for sharing very good questions for placement preparation.
If you like GeeksforGeeks and would like to contribute, you can write article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks!!
Morgan Stanley
Interview Experiences
Morgan Stanley
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jul, 2019"
},
{
"code": null,
"e": 105,
"s": 52,
"text": "Morgan Stanley campus placement for post IT analyst."
},
{
"code": null,
"e": 293,
"s": 105,
"text": "1st round – objective written test10 questions on aptitude and analytics30 questions on programming10 questions on computer fundamentalsThey had sectional cut-off and selected 20 students"
},
{
"code": null,
"e": 781,
"s": 293,
"text": "2st round – coding written test5 questions on coding basically on data structures1. Write a function to find the mirror image of binary tree2. WAP to find the character which occurred maximum times in the character array3. Given a 2d matrix find an element in a matrix which is 0 and make the entire row and column to 04. Find the minimum element in the rotated array of integers5. Find highest length substring such that there are equal number of 0’s and 1’sin array of 1’s and 0’s only"
},
{
"code": null,
"e": 1501,
"s": 781,
"text": "3rd round – Technical interview1. He asked to tell something about me2. Then he asked a questions on my projects and internship3. Then he asked me to write a modified bubble sort4. Asked me to design a structure for storing stock market details for every quote/ company and store it as a linked list and asked me to write a linked list function like insertion and initialization5. Then he asked me to store the live data of particular company of every 5 minutes and the history should be of 10 days, so it’s a huge amount of data so it’s very inefficient to use linked list so suggested to use hash map or circular array as it of fix size of 10 days.6. There were other simple questions on data structures and databases"
},
{
"code": null,
"e": 1922,
"s": 1501,
"text": "4th round – Group Task/DiscussionThe group was formed by 6 people. They provided some 8-10 pictures based on business ethics and then we have to form a story using this pictures in 15 minutes and after this time they provided again 6 pictures and we have to include it in our story. And then we have to tell the story in group in 2 minutes. Then they asked some questions and asked us to rate everyone else in the group."
},
{
"code": null,
"e": 2855,
"s": 1922,
"text": "5th round – technical interviewMost of the questions were on databases and operating systems. Then some are probability questions1. If your friend is being pointed by a gun by his enemy, consider a barrel of 6 bullets but it has only 2 bullets which were consecutive too, then an enemy rotates the barrel and push into a gun then he fires the trigger but the shit was empty, then he gave a choice for 2 shot that do you want to rotate the barrel again(randomly) or continue in this position only, so we have to find both the probabilities and find which one is lesser so that we can save our friend2. The other question was we have to print10 – 60% of the time we execute the program20 – 10% of – –15 – 30% of –So we have to write a code so that when we execute the code for 100 times there will be 60 – 10’s, 10 – 20’s, 30 – 15’sThen asked me to draw tables for database of college for students, professors, time table and courses."
},
{
"code": null,
"e": 3375,
"s": 2855,
"text": "6th round – HR interviewBefore going for HR interview we have to fill the form which has some common questions and all things about you like books you read, hobbies, place where you want to work, about post grad.Normal HR round was there and asked some common questions such as about me, my past, my grades, interests, hobbies, pros – cons, achievements.Also about future plans like post grad and position after 5 years, then he given some puzzles to solve the 100 prisons and 100 prisoners question to toggle the doors"
},
{
"code": null,
"e": 3470,
"s": 3375,
"text": "I really really thank geeksforgeeks for sharing very good questions for placement preparation."
},
{
"code": null,
"e": 3686,
"s": 3472,
"text": "If you like GeeksforGeeks and would like to contribute, you can write article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks!!"
},
{
"code": null,
"e": 3701,
"s": 3686,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 3723,
"s": 3701,
"text": "Interview Experiences"
},
{
"code": null,
"e": 3738,
"s": 3723,
"text": "Morgan Stanley"
}
] |
BigInteger toString() Method in Java | 04 Dec, 2018
BigInteger Class offers 2 methods for toString().
toString(int radix): The java.math.BigInteger.toString(int radix) method returns the decimal String representation of this BigInteger in given radix. Radix parameter decides on which number base (Binary, octal, hex etc) it should return the string. In case of toString() the radix is by Default 10. If the radix is outside the range of Character.MIN_RADIX to Character.MAX_RADIX inclusive, it will default to 10.Syntax:public String toString(int radix)Parameter: This method accepts a single mandatory parameter radix which is the radix of String representation.Return Value: This method returns decimal String representation of this BigInteger in the given radix.Examples:Input: BigInteger1=321456 radix =2
Output: 1001110011110110000
Explanation: BigInteger1.toString(2)=1001110011110110000.
when radix is 2 then function will first convert the BigInteger
to binary form then it will return String representation of that binary number.
Input: BigInteger1=321456 radix=16
Output: 4e7b0
Explanation: BigInteger1.toString()=4e7b0.
when radix is 16 then function will first convert the BigInteger
to hexadecimal form then it will return String representation of that hexadecimal number.
Below programs illustrate toString(int radix) method of BigInteger class:Example 1: When radix = 2. It means binary form String.// Java program to demonstrate// toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("321456"); // create radix int radix = 2; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println("Binary String of BigInteger " + b1 + " is equal to " + b1String); }}Output:Binary String of BigInteger 321456 is equal to 1001110011110110000
Example 2: When radix = 8 It means octal form String// Java program to demonstrate // toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("34567876543"); // create radix int radix = 8; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println("Octal String of BigInteger " + b1 + " is equal to " + b1String); }}Output:Octal String of BigInteger 34567876543 is equal to 401431767677
Example 3: When radix = 16 It means HexaDecimal form String// Java program to demonstrate toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("8765432123456"); // create radix int radix = 16; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println("Hexadecimal String of BigInteger " + b1 + " is equal to " + b1String); }}Output:Hexadecimal String of BigInteger 8765432123456 is equal to 7f8dc77d040
Syntax:
public String toString(int radix)
Parameter: This method accepts a single mandatory parameter radix which is the radix of String representation.
Return Value: This method returns decimal String representation of this BigInteger in the given radix.
Examples:
Input: BigInteger1=321456 radix =2
Output: 1001110011110110000
Explanation: BigInteger1.toString(2)=1001110011110110000.
when radix is 2 then function will first convert the BigInteger
to binary form then it will return String representation of that binary number.
Input: BigInteger1=321456 radix=16
Output: 4e7b0
Explanation: BigInteger1.toString()=4e7b0.
when radix is 16 then function will first convert the BigInteger
to hexadecimal form then it will return String representation of that hexadecimal number.
Below programs illustrate toString(int radix) method of BigInteger class:
Example 1: When radix = 2. It means binary form String.
// Java program to demonstrate// toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("321456"); // create radix int radix = 2; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println("Binary String of BigInteger " + b1 + " is equal to " + b1String); }}
Binary String of BigInteger 321456 is equal to 1001110011110110000
Example 2: When radix = 8 It means octal form String
// Java program to demonstrate // toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("34567876543"); // create radix int radix = 8; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println("Octal String of BigInteger " + b1 + " is equal to " + b1String); }}
Octal String of BigInteger 34567876543 is equal to 401431767677
Example 3: When radix = 16 It means HexaDecimal form String
// Java program to demonstrate toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("8765432123456"); // create radix int radix = 16; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println("Hexadecimal String of BigInteger " + b1 + " is equal to " + b1String); }}
Hexadecimal String of BigInteger 8765432123456 is equal to 7f8dc77d040
toString(): The java.math.BigInteger.toString() method returns the decimal String representation of this BigInteger. This method is useful to convert BigInteger to String. One can apply all string operation on BigInteger after applying toString() on BigInteger.Syntax:public String toString()Return Value: This method returns decimal String representation of this BigInteger.Examples:Input: BigInteger1=321456
Output: 321456
Explanation: BigInteger1.toString()=321456.
The answer is the String representation of BigInteger
Input: BigInteger1=59185482345
Output: 59185482345
Explanation: BigInteger1.toString()=59185482345.
The answer is the String representation of BigInteger
Below programs illustrate toString() method of BigInteger class:Example:// Java program to demonstrate toString() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("35152194853456789"); // apply toString() method String b1String = b1.toString(); // print String System.out.println(b1String); b2 = new BigInteger("7654323234565432345676543234567"); // apply toString() method String b2String = b2.toString(); // print String System.out.println(b2String); }}Output:35152194853456789
7654323234565432345676543234567
Syntax:
public String toString()
Return Value: This method returns decimal String representation of this BigInteger.
Examples:
Input: BigInteger1=321456
Output: 321456
Explanation: BigInteger1.toString()=321456.
The answer is the String representation of BigInteger
Input: BigInteger1=59185482345
Output: 59185482345
Explanation: BigInteger1.toString()=59185482345.
The answer is the String representation of BigInteger
Below programs illustrate toString() method of BigInteger class:
Example:
// Java program to demonstrate toString() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("35152194853456789"); // apply toString() method String b1String = b1.toString(); // print String System.out.println(b1String); b2 = new BigInteger("7654323234565432345676543234567"); // apply toString() method String b2String = b2.toString(); // print String System.out.println(b2String); }}
35152194853456789
7654323234565432345676543234567
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toString(java.math.BigInteger)
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 78,
"s": 28,
"text": "BigInteger Class offers 2 methods for toString()."
},
{
"code": null,
"e": 3396,
"s": 78,
"text": "toString(int radix): The java.math.BigInteger.toString(int radix) method returns the decimal String representation of this BigInteger in given radix. Radix parameter decides on which number base (Binary, octal, hex etc) it should return the string. In case of toString() the radix is by Default 10. If the radix is outside the range of Character.MIN_RADIX to Character.MAX_RADIX inclusive, it will default to 10.Syntax:public String toString(int radix)Parameter: This method accepts a single mandatory parameter radix which is the radix of String representation.Return Value: This method returns decimal String representation of this BigInteger in the given radix.Examples:Input: BigInteger1=321456 radix =2\nOutput: 1001110011110110000\nExplanation: BigInteger1.toString(2)=1001110011110110000. \nwhen radix is 2 then function will first convert the BigInteger \nto binary form then it will return String representation of that binary number.\n\nInput: BigInteger1=321456 radix=16\nOutput: 4e7b0\nExplanation: BigInteger1.toString()=4e7b0. \nwhen radix is 16 then function will first convert the BigInteger \nto hexadecimal form then it will return String representation of that hexadecimal number.\nBelow programs illustrate toString(int radix) method of BigInteger class:Example 1: When radix = 2. It means binary form String.// Java program to demonstrate// toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"321456\"); // create radix int radix = 2; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println(\"Binary String of BigInteger \" + b1 + \" is equal to \" + b1String); }}Output:Binary String of BigInteger 321456 is equal to 1001110011110110000\nExample 2: When radix = 8 It means octal form String// Java program to demonstrate // toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"34567876543\"); // create radix int radix = 8; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println(\"Octal String of BigInteger \" + b1 + \" is equal to \" + b1String); }}Output:Octal String of BigInteger 34567876543 is equal to 401431767677\nExample 3: When radix = 16 It means HexaDecimal form String// Java program to demonstrate toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"8765432123456\"); // create radix int radix = 16; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println(\"Hexadecimal String of BigInteger \" + b1 + \" is equal to \" + b1String); }}Output:Hexadecimal String of BigInteger 8765432123456 is equal to 7f8dc77d040\n"
},
{
"code": null,
"e": 3404,
"s": 3396,
"text": "Syntax:"
},
{
"code": null,
"e": 3438,
"s": 3404,
"text": "public String toString(int radix)"
},
{
"code": null,
"e": 3549,
"s": 3438,
"text": "Parameter: This method accepts a single mandatory parameter radix which is the radix of String representation."
},
{
"code": null,
"e": 3652,
"s": 3549,
"text": "Return Value: This method returns decimal String representation of this BigInteger in the given radix."
},
{
"code": null,
"e": 3662,
"s": 3652,
"text": "Examples:"
},
{
"code": null,
"e": 4180,
"s": 3662,
"text": "Input: BigInteger1=321456 radix =2\nOutput: 1001110011110110000\nExplanation: BigInteger1.toString(2)=1001110011110110000. \nwhen radix is 2 then function will first convert the BigInteger \nto binary form then it will return String representation of that binary number.\n\nInput: BigInteger1=321456 radix=16\nOutput: 4e7b0\nExplanation: BigInteger1.toString()=4e7b0. \nwhen radix is 16 then function will first convert the BigInteger \nto hexadecimal form then it will return String representation of that hexadecimal number.\n"
},
{
"code": null,
"e": 4254,
"s": 4180,
"text": "Below programs illustrate toString(int radix) method of BigInteger class:"
},
{
"code": null,
"e": 4310,
"s": 4254,
"text": "Example 1: When radix = 2. It means binary form String."
},
{
"code": "// Java program to demonstrate// toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"321456\"); // create radix int radix = 2; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println(\"Binary String of BigInteger \" + b1 + \" is equal to \" + b1String); }}",
"e": 4861,
"s": 4310,
"text": null
},
{
"code": null,
"e": 4929,
"s": 4861,
"text": "Binary String of BigInteger 321456 is equal to 1001110011110110000\n"
},
{
"code": null,
"e": 4982,
"s": 4929,
"text": "Example 2: When radix = 8 It means octal form String"
},
{
"code": "// Java program to demonstrate // toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"34567876543\"); // create radix int radix = 8; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println(\"Octal String of BigInteger \" + b1 + \" is equal to \" + b1String); }}",
"e": 5537,
"s": 4982,
"text": null
},
{
"code": null,
"e": 5602,
"s": 5537,
"text": "Octal String of BigInteger 34567876543 is equal to 401431767677\n"
},
{
"code": null,
"e": 5662,
"s": 5602,
"text": "Example 3: When radix = 16 It means HexaDecimal form String"
},
{
"code": "// Java program to demonstrate toString(radix) method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"8765432123456\"); // create radix int radix = 16; // apply toString(radix) method String b1String = b1.toString(radix); // print String System.out.println(\"Hexadecimal String of BigInteger \" + b1 + \" is equal to \" + b1String); }}",
"e": 6224,
"s": 5662,
"text": null
},
{
"code": null,
"e": 6296,
"s": 6224,
"text": "Hexadecimal String of BigInteger 8765432123456 is equal to 7f8dc77d040\n"
},
{
"code": null,
"e": 7732,
"s": 6296,
"text": "toString(): The java.math.BigInteger.toString() method returns the decimal String representation of this BigInteger. This method is useful to convert BigInteger to String. One can apply all string operation on BigInteger after applying toString() on BigInteger.Syntax:public String toString()Return Value: This method returns decimal String representation of this BigInteger.Examples:Input: BigInteger1=321456 \nOutput: 321456\nExplanation: BigInteger1.toString()=321456. \nThe answer is the String representation of BigInteger\n\nInput: BigInteger1=59185482345\nOutput: 59185482345\nExplanation: BigInteger1.toString()=59185482345. \nThe answer is the String representation of BigInteger\nBelow programs illustrate toString() method of BigInteger class:Example:// Java program to demonstrate toString() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"35152194853456789\"); // apply toString() method String b1String = b1.toString(); // print String System.out.println(b1String); b2 = new BigInteger(\"7654323234565432345676543234567\"); // apply toString() method String b2String = b2.toString(); // print String System.out.println(b2String); }}Output:35152194853456789\n7654323234565432345676543234567\n"
},
{
"code": null,
"e": 7740,
"s": 7732,
"text": "Syntax:"
},
{
"code": null,
"e": 7765,
"s": 7740,
"text": "public String toString()"
},
{
"code": null,
"e": 7849,
"s": 7765,
"text": "Return Value: This method returns decimal String representation of this BigInteger."
},
{
"code": null,
"e": 7859,
"s": 7849,
"text": "Examples:"
},
{
"code": null,
"e": 8157,
"s": 7859,
"text": "Input: BigInteger1=321456 \nOutput: 321456\nExplanation: BigInteger1.toString()=321456. \nThe answer is the String representation of BigInteger\n\nInput: BigInteger1=59185482345\nOutput: 59185482345\nExplanation: BigInteger1.toString()=59185482345. \nThe answer is the String representation of BigInteger\n"
},
{
"code": null,
"e": 8222,
"s": 8157,
"text": "Below programs illustrate toString() method of BigInteger class:"
},
{
"code": null,
"e": 8231,
"s": 8222,
"text": "Example:"
},
{
"code": "// Java program to demonstrate toString() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"35152194853456789\"); // apply toString() method String b1String = b1.toString(); // print String System.out.println(b1String); b2 = new BigInteger(\"7654323234565432345676543234567\"); // apply toString() method String b2String = b2.toString(); // print String System.out.println(b2String); }}",
"e": 8857,
"s": 8231,
"text": null
},
{
"code": null,
"e": 8908,
"s": 8857,
"text": "35152194853456789\n7654323234565432345676543234567\n"
},
{
"code": null,
"e": 9018,
"s": 8908,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toString(java.math.BigInteger)"
},
{
"code": null,
"e": 9034,
"s": 9018,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 9049,
"s": 9034,
"text": "Java-Functions"
},
{
"code": null,
"e": 9059,
"s": 9049,
"text": "java-math"
},
{
"code": null,
"e": 9077,
"s": 9059,
"text": "Java-math-package"
},
{
"code": null,
"e": 9082,
"s": 9077,
"text": "Java"
},
{
"code": null,
"e": 9098,
"s": 9082,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 9103,
"s": 9098,
"text": "Java"
},
{
"code": null,
"e": 9201,
"s": 9103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9252,
"s": 9201,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 9283,
"s": 9252,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 9302,
"s": 9283,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 9332,
"s": 9302,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 9350,
"s": 9332,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 9365,
"s": 9350,
"text": "Stream In Java"
},
{
"code": null,
"e": 9385,
"s": 9365,
"text": "Collections in Java"
},
{
"code": null,
"e": 9417,
"s": 9385,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9441,
"s": 9417,
"text": "Singleton Class in Java"
}
] |
Python | Sort list elements by frequency | 05 Apr, 2022
Given a list containing repeated and non-repeated elements, the task is to sort the given list on basis of the frequency of elements. Let’s discuss few methods for the same.
Python3
# Python code to demonstrate# sort list by frequency# of elements from collections import Counter ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of frequency of elementsresult = [item for items, c in Counter(ini_list).most_common() for item in [items] * c] # printing final resultprint("final list", str(result))
Output:
initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]
final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]
Python3
# Python code to demonstrate# sort list by frequency# of elements from collections import Counterfrom itertools import repeat, chain ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of frequency of elementsresult = list(chain.from_iterable(repeat(i, c) for i, c in Counter(ini_list).most_common())) # printing final resultprint("final list", str(result))
Output:
initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]
final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]
Python3
# Python code to demonstrate# sort list by frequency# of elements ini_list = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of frequency of elementsresult = sorted(ini_list, key = ini_list.count, reverse = True) # printing final resultprint("final list", str(result))
Output:
initial list [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4]
final list [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 5, 5, 5, 1, 1]
kapilsahu421
simmytarika5
Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 226,
"s": 52,
"text": "Given a list containing repeated and non-repeated elements, the task is to sort the given list on basis of the frequency of elements. Let’s discuss few methods for the same."
},
{
"code": null,
"e": 234,
"s": 226,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# sort list by frequency# of elements from collections import Counter ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_listprint (\"initial list\", str(ini_list)) # sorting on basis of frequency of elementsresult = [item for items, c in Counter(ini_list).most_common() for item in [items] * c] # printing final resultprint(\"final list\", str(result))",
"e": 704,
"s": 234,
"text": null
},
{
"code": null,
"e": 712,
"s": 704,
"text": "Output:"
},
{
"code": null,
"e": 858,
"s": 712,
"text": "initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]\nfinal list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]"
},
{
"code": null,
"e": 866,
"s": 858,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# sort list by frequency# of elements from collections import Counterfrom itertools import repeat, chain ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_listprint (\"initial list\", str(ini_list)) # sorting on basis of frequency of elementsresult = list(chain.from_iterable(repeat(i, c) for i, c in Counter(ini_list).most_common())) # printing final resultprint(\"final list\", str(result))",
"e": 1347,
"s": 866,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1347,
"text": "Output:"
},
{
"code": null,
"e": 1501,
"s": 1355,
"text": "initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]\nfinal list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]"
},
{
"code": null,
"e": 1509,
"s": 1501,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# sort list by frequency# of elements ini_list = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4] # printing initial ini_listprint (\"initial list\", str(ini_list)) # sorting on basis of frequency of elementsresult = sorted(ini_list, key = ini_list.count, reverse = True) # printing final resultprint(\"final list\", str(result))",
"e": 1917,
"s": 1509,
"text": null
},
{
"code": null,
"e": 1925,
"s": 1917,
"text": "Output:"
},
{
"code": null,
"e": 2065,
"s": 1925,
"text": "initial list [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4]\nfinal list [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 5, 5, 5, 1, 1]"
},
{
"code": null,
"e": 2078,
"s": 2065,
"text": "kapilsahu421"
},
{
"code": null,
"e": 2091,
"s": 2078,
"text": "simmytarika5"
},
{
"code": null,
"e": 2112,
"s": 2091,
"text": "Python list-programs"
},
{
"code": null,
"e": 2124,
"s": 2112,
"text": "Python-sort"
},
{
"code": null,
"e": 2131,
"s": 2124,
"text": "Python"
},
{
"code": null,
"e": 2147,
"s": 2131,
"text": "Python Programs"
},
{
"code": null,
"e": 2245,
"s": 2147,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2263,
"s": 2245,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2305,
"s": 2263,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2327,
"s": 2305,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2362,
"s": 2327,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2388,
"s": 2362,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2431,
"s": 2388,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2453,
"s": 2431,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2491,
"s": 2453,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2528,
"s": 2491,
"text": "Python Program for Fibonacci numbers"
}
] |
Rexx - Basic Syntax | In order to understand the basic syntax of Rexx, let us first look at a simple Hello World program.
/* Main program */
say "Hello World"
One can see how simple the hello world program is. It is a simple script line which is used to execute the Hello World program.
The following things need to be noted about the above program −
The say command is used to output a value to the console.
The say command is used to output a value to the console.
The /* */ is used for comments in Rexx.
The /* */ is used for comments in Rexx.
The output of the above program will be −
Hello World
In Rexx, let’s see a general form of a program. Take a look at the following example.
/* Main program */
say add(5,6)
exit
add:
parse arg a,b
return a + b
The output of the above program will be −
11
Let’s go through what we have understood from the above program −
Add is a function defined to add 2 numbers.
Add is a function defined to add 2 numbers.
In the main program, the values of 5 and 6 is used as parameters to the add function.
In the main program, the values of 5 and 6 is used as parameters to the add function.
The exit keyword is used to exit from the main program. This is used to differentiate the main program from the add function.
The exit keyword is used to exit from the main program. This is used to differentiate the main program from the add function.
The add function is differentiated with the ‘:’ symbol.
The add function is differentiated with the ‘:’ symbol.
The parse statement is used to parse the incoming arguments.
The parse statement is used to parse the incoming arguments.
Finally, the return statement is used to return the sum of the numeric values.
Finally, the return statement is used to return the sum of the numeric values.
In Rexx, the code is normally divided into subroutines and functions. Subroutines and functions are used to differentiate the code into different logical units. The key difference between subroutines and functions is that functions return a value whereas subroutines don’t.
Below is a key difference example between a subroutine and a function for an addition implementation −
/* Main program */
say add(5,6)
exit
add:
parse arg a,b
return a + b
/* Main program */
add(5,6)
exit
add:
parse arg a,b
say a + b
The output of both the programs will be the value 11.
Rexx can be used as a control language for a variety of command-based systems. The way that Rexx executes commands in these systems is as follows. When Rexx encounters a program line which is neither an instruction nor an assignment, it treats that line as a string expression which is to be evaluated and then passed to the environment.
An example is as follows −
/* Main program */
parse arg command
command "file1"
command "file2"
command "file3"
exit
Each of the three similar lines in this program is a string expression which adds the name of a file (contained in the string constants) to the name of a command (given as a parameter). The resulting string is passed to the environment to be executed as a command. When the command has finished, the variable "rc" is set to the exit code of the command.
The output of the above program is as follows −
sh: file1: command not found
3 *-* command "file1"
>>> " file1"
+++ "RC(127)"
sh: file2: command not found
4 *-* command "file2"
>>> " file2"
+++ "RC(127)"
sh: file3: command not found
5 *-* command "file3"
>>> " file3"
+++ "RC(127)"
The free syntax of REXX implies that some symbols are reserved for the language processor's use in certain contexts.
Within particular instructions, some symbols may be reserved to separate the parts of the instruction. These symbols are referred to as keywords. Examples of REXX keywords are the WHILE in a DO instruction, and the THEN (which acts as a clause terminator in this case) following an IF or WHEN clause.
Apart from these cases, only simple symbols that are the first token in a clause and that are not followed by an "=" or ":" are checked to see if they are instruction keywords. You can use the symbols freely elsewhere in clauses without their being taken to be keywords.
Comments are used to document your code. Single line comments are identified by using the /* */ at any position in the line.
An example is as follows −
/* Main program */
/* Call the add function */
add(5,6)
/* Exit the main program */
exit add:
/* Parse the arguments passed to the add function */ parse arg a,b
/* Display the added numeric values */
say a + b
Comments can also be written in between a code line as shown in the following program −
/* Main program */
/* Call the add function */
add(5,6)
/* Exit the main program */
exit
add:
parse /* Parse the arguments passed to the add function */
arg a,b
/* Display the added numeric values */
say a + b
The output of the above program will be −
11
You can also have multiple lines in a comment as shown in the following program −
/* Main program
The below program is used to add numbers
Call the add function */
add(5,6)
exit
add:
parse arg a,b
say a + b
The output of the above program will be − | [
{
"code": null,
"e": 2573,
"s": 2473,
"text": "In order to understand the basic syntax of Rexx, let us first look at a simple Hello World program."
},
{
"code": null,
"e": 2612,
"s": 2573,
"text": "/* Main program */ \nsay \"Hello World\" "
},
{
"code": null,
"e": 2740,
"s": 2612,
"text": "One can see how simple the hello world program is. It is a simple script line which is used to execute the Hello World program."
},
{
"code": null,
"e": 2804,
"s": 2740,
"text": "The following things need to be noted about the above program −"
},
{
"code": null,
"e": 2862,
"s": 2804,
"text": "The say command is used to output a value to the console."
},
{
"code": null,
"e": 2920,
"s": 2862,
"text": "The say command is used to output a value to the console."
},
{
"code": null,
"e": 2960,
"s": 2920,
"text": "The /* */ is used for comments in Rexx."
},
{
"code": null,
"e": 3000,
"s": 2960,
"text": "The /* */ is used for comments in Rexx."
},
{
"code": null,
"e": 3042,
"s": 3000,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 3055,
"s": 3042,
"text": "Hello World\n"
},
{
"code": null,
"e": 3141,
"s": 3055,
"text": "In Rexx, let’s see a general form of a program. Take a look at the following example."
},
{
"code": null,
"e": 3215,
"s": 3141,
"text": "/* Main program */ \nsay add(5,6) \nexit \nadd: \nparse arg a,b \nreturn a + b"
},
{
"code": null,
"e": 3257,
"s": 3215,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 3261,
"s": 3257,
"text": "11\n"
},
{
"code": null,
"e": 3327,
"s": 3261,
"text": "Let’s go through what we have understood from the above program −"
},
{
"code": null,
"e": 3371,
"s": 3327,
"text": "Add is a function defined to add 2 numbers."
},
{
"code": null,
"e": 3415,
"s": 3371,
"text": "Add is a function defined to add 2 numbers."
},
{
"code": null,
"e": 3501,
"s": 3415,
"text": "In the main program, the values of 5 and 6 is used as parameters to the add function."
},
{
"code": null,
"e": 3587,
"s": 3501,
"text": "In the main program, the values of 5 and 6 is used as parameters to the add function."
},
{
"code": null,
"e": 3713,
"s": 3587,
"text": "The exit keyword is used to exit from the main program. This is used to differentiate the main program from the add function."
},
{
"code": null,
"e": 3839,
"s": 3713,
"text": "The exit keyword is used to exit from the main program. This is used to differentiate the main program from the add function."
},
{
"code": null,
"e": 3895,
"s": 3839,
"text": "The add function is differentiated with the ‘:’ symbol."
},
{
"code": null,
"e": 3951,
"s": 3895,
"text": "The add function is differentiated with the ‘:’ symbol."
},
{
"code": null,
"e": 4012,
"s": 3951,
"text": "The parse statement is used to parse the incoming arguments."
},
{
"code": null,
"e": 4073,
"s": 4012,
"text": "The parse statement is used to parse the incoming arguments."
},
{
"code": null,
"e": 4152,
"s": 4073,
"text": "Finally, the return statement is used to return the sum of the numeric values."
},
{
"code": null,
"e": 4231,
"s": 4152,
"text": "Finally, the return statement is used to return the sum of the numeric values."
},
{
"code": null,
"e": 4505,
"s": 4231,
"text": "In Rexx, the code is normally divided into subroutines and functions. Subroutines and functions are used to differentiate the code into different logical units. The key difference between subroutines and functions is that functions return a value whereas subroutines don’t."
},
{
"code": null,
"e": 4608,
"s": 4505,
"text": "Below is a key difference example between a subroutine and a function for an addition implementation −"
},
{
"code": null,
"e": 4682,
"s": 4608,
"text": "/* Main program */ \nsay add(5,6) \nexit \nadd: \nparse arg a,b \nreturn a + b"
},
{
"code": null,
"e": 4749,
"s": 4682,
"text": "/* Main program */ \nadd(5,6) \nexit \nadd: \nparse arg a,b \nsay a + b"
},
{
"code": null,
"e": 4803,
"s": 4749,
"text": "The output of both the programs will be the value 11."
},
{
"code": null,
"e": 5141,
"s": 4803,
"text": "Rexx can be used as a control language for a variety of command-based systems. The way that Rexx executes commands in these systems is as follows. When Rexx encounters a program line which is neither an instruction nor an assignment, it treats that line as a string expression which is to be evaluated and then passed to the environment."
},
{
"code": null,
"e": 5168,
"s": 5141,
"text": "An example is as follows −"
},
{
"code": null,
"e": 5264,
"s": 5168,
"text": "/* Main program */ \nparse arg command \ncommand \"file1\" \ncommand \"file2\" \ncommand \"file3\" \nexit "
},
{
"code": null,
"e": 5618,
"s": 5264,
"text": "Each of the three similar lines in this program is a string expression which adds the name of a file (contained in the string constants) to the name of a command (given as a parameter). The resulting string is passed to the environment to be executed as a command. When the command has finished, the variable \"rc\" is set to the exit code of the command."
},
{
"code": null,
"e": 5666,
"s": 5618,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 5973,
"s": 5666,
"text": "sh: file1: command not found\n 3 *-* command \"file1\" \n >>> \" file1\"\n +++ \"RC(127)\"\nsh: file2: command not found\n 4 *-* command \"file2\" \n >>> \" file2\"\n +++ \"RC(127)\"\nsh: file3: command not found\n 5 *-* command \"file3\" \n >>> \" file3\"\n +++ \"RC(127)\"\n"
},
{
"code": null,
"e": 6090,
"s": 5973,
"text": "The free syntax of REXX implies that some symbols are reserved for the language processor's use in certain contexts."
},
{
"code": null,
"e": 6391,
"s": 6090,
"text": "Within particular instructions, some symbols may be reserved to separate the parts of the instruction. These symbols are referred to as keywords. Examples of REXX keywords are the WHILE in a DO instruction, and the THEN (which acts as a clause terminator in this case) following an IF or WHEN clause."
},
{
"code": null,
"e": 6662,
"s": 6391,
"text": "Apart from these cases, only simple symbols that are the first token in a clause and that are not followed by an \"=\" or \":\" are checked to see if they are instruction keywords. You can use the symbols freely elsewhere in clauses without their being taken to be keywords."
},
{
"code": null,
"e": 6787,
"s": 6662,
"text": "Comments are used to document your code. Single line comments are identified by using the /* */ at any position in the line."
},
{
"code": null,
"e": 6814,
"s": 6787,
"text": "An example is as follows −"
},
{
"code": null,
"e": 7026,
"s": 6814,
"text": "/* Main program */\n/* Call the add function */\nadd(5,6)\n\n/* Exit the main program */\nexit add:\n\n/* Parse the arguments passed to the add function */ parse arg a,b\n/* Display the added numeric values */\nsay a + b"
},
{
"code": null,
"e": 7114,
"s": 7026,
"text": "Comments can also be written in between a code line as shown in the following program −"
},
{
"code": null,
"e": 7338,
"s": 7114,
"text": "/* Main program */ \n/* Call the add function */ \nadd(5,6) \n\n/* Exit the main program */ \nexit \nadd: \nparse /* Parse the arguments passed to the add function */ \narg a,b \n\n/* Display the added numeric values */ \nsay a + b"
},
{
"code": null,
"e": 7380,
"s": 7338,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 7384,
"s": 7380,
"text": "11\n"
},
{
"code": null,
"e": 7466,
"s": 7384,
"text": "You can also have multiple lines in a comment as shown in the following program −"
},
{
"code": null,
"e": 7598,
"s": 7466,
"text": "/* Main program \nThe below program is used to add numbers \nCall the add function */ \nadd(5,6) \nexit \nadd: \nparse arg a,b \nsay a + b"
}
] |
Sum of the digits of square of the given number which has only 1’s as its digits | 19 Mar, 2022
Given a number represented as string str consisting of the digit 1 only i.e. 1, 11, 111, .... The task is to find the sum of digits of the square of the given number.
Examples:
Input: str = 11 Output: 4 112 = 121 1 + 2 + 1 = 4
Input: str = 1111 Output: 16
Naive approach: Find the square of the given number and then find the sum of its digits.
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; // Function to return the sum// of the digits of num ^ 2int squareDigitSum(string number){ int summ = 0; int num = stoi(number); // Store the square of num int squareNum = num * num; // Find the sum of its digits while(squareNum > 0) { summ = summ + (squareNum % 10); squareNum = squareNum / 10; } return summ;} // Driver codeint main(){ string N = "1111"; cout << squareDigitSum(N); return 0;} // This code is contributed by Princi Singh
// Java implementation of the approach// Java implementation of the approachclass GFG{ // Function to return the sum// of the digits of num ^ 2static int squareDigitSum(String number){ int summ = 0; int num = Integer.parseInt(number); // Store the square of num int squareNum = num * num; // Find the sum of its digits while(squareNum > 0) { summ = summ + (squareNum % 10); squareNum = squareNum / 10; } return summ;} // Driver codepublic static void main (String[] args){ String N = "1111"; System.out.println(squareDigitSum(N));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the sum# of the digits of num ^ 2def squareDigitSum(num): summ = 0 num = int(num) # Store the square of num squareNum = num * num # Find the sum of its digits while squareNum > 0: summ = summ + (squareNum % 10) squareNum = squareNum//10 return summ # Driver codeif __name__ == "__main__": N = "1111" print(squareDigitSum(N))
// C# implementation of the approachusing System; class GFG{ // Function to return the sum // of the digits of num ^ 2 static int squareDigitSum(String number) { int summ = 0; int num = int.Parse(number); // Store the square of num int squareNum = num * num; // Find the sum of its digits while(squareNum > 0) { summ = summ + (squareNum % 10); squareNum = squareNum / 10; } return summ; } // Driver code public static void Main (String[] args) { String s = "1111"; Console.WriteLine(squareDigitSum(s)); }} // This code is contributed by Princi Singh
<script> // Javascript implementation of the approach // Function to return the sum// of the digits of num ^ 2function squareDigitSum(number){ var summ = 0; var num = parseInt(number); // Store the square of num var squareNum = num * num; // Find the sum of its digits while (squareNum > 0) { summ = summ + (squareNum % 10); squareNum = parseInt(squareNum / 10); } return summ;} // Driver codevar N = "1111"; document.write(squareDigitSum(N)); // This code is contributed by todaysgaurav </script>
16
Efficient approach: It can be observed that in the square of the given number, the sequence [1, 2, 3, 4, 5, 6, 7, 9, 0] repeats in the left part and the sequence [0, 9, 8, 7, 6, 5, 4, 3, 2, 1] repeats in the right part. Both of these sequences appear floor(length(str) / 9) times and the sum of both of these sequences is 81 and the square of the number adds an extra 1 in the end.So, the sum of all these would be [floor(length(str) / 9)] * 81 + 1.And the middle digits have a sequence such as if length(str) % 9 = a then middle sequence is [1, 2, 3....a, a – 1, a – 2, ... 2]. Now, it can be observed that sum of this part [1, 2, 3....a] is equal to (a * (a + 1)) / 2 and sum of the other part [a – 1, a – 2, ... 2] is ((a * (a – 1)) / 2) – 1. Total sum = floor(length(str) / 9) * 81 + 1 + (length(str) % 9)2 – 1 = floor(length(str) / 9) * 81 + (length(str) % 9)2.
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 lli long long int // Function to return the sum// of the digits of num^2lli squareDigitSum(string s){ // To store the number of 1's lli lengthN = s.length(); // Find the sum of the digits of num^2 lli result = (lengthN / 9) * 81 + pow((lengthN % 9), 2); return result;} // Driver codeint main(){ string s = "1111"; cout << squareDigitSum(s); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the sum // of the digits of num^2 static long squareDigitSum(String s) { // To store the number of 1's long lengthN = s.length(); // Find the sum of the digits of num^2 long result = (lengthN / 9) * 81 + (long)Math.pow((lengthN % 9), 2); return result; } // Driver code public static void main (String[] args) { String s = "1111"; System.out.println(squareDigitSum(s)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the sum# of the digits of num ^ 2def squareDigitSum(num): # To store the number of 1's lengthN = len(num) # Find the sum of the digits of num ^ 2 result = (lengthN//9)*81 + (lengthN % 9)**2 return result # Driver codeif __name__ == "__main__" : N = "1111" print(squareDigitSum(N))
// C# implementation of the approachusing System; class GFG{ // Function to return the sum// of the digits of num^2static long squareDigitSum(String s){ // To store the number of 1's long lengthN = s.Length; // Find the sum of the digits of num^2 long result = (lengthN / 9) * 81 + (long)Math.Pow((lengthN % 9), 2); return result;} // Driver codepublic static void Main (String[] args){ String s = "1111"; Console.WriteLine(squareDigitSum(s));}} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach // Function to return the sum// of the digits of num^2function squareDigitSum(s){ // To store the number of 1's let lengthN = s.length; // Find the sum of the digits of num^2 let result = parseInt(lengthN / 9) * 81 + Math.pow((lengthN % 9), 2); return result;} // Driver code let s = "1111"; document.write(squareDigitSum(s)); </script>
16
Time Complexity O(1)
Auxiliary Space: O(1)
ankthon
29AjayKumar
Rajput-Ji
princi singh
todaysgaurav
rishavmahato348
subhamkumarm348
number-digits
Mathematical
Pattern Searching
Mathematical
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Check if an URL is valid or not using Regular Expression
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 220,
"s": 53,
"text": "Given a number represented as string str consisting of the digit 1 only i.e. 1, 11, 111, .... The task is to find the sum of digits of the square of the given number."
},
{
"code": null,
"e": 231,
"s": 220,
"text": "Examples: "
},
{
"code": null,
"e": 281,
"s": 231,
"text": "Input: str = 11 Output: 4 112 = 121 1 + 2 + 1 = 4"
},
{
"code": null,
"e": 312,
"s": 281,
"text": "Input: str = 1111 Output: 16 "
},
{
"code": null,
"e": 401,
"s": 312,
"text": "Naive approach: Find the square of the given number and then find the sum of its digits."
},
{
"code": null,
"e": 454,
"s": 401,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 458,
"s": 454,
"text": "C++"
},
{
"code": null,
"e": 463,
"s": 458,
"text": "Java"
},
{
"code": null,
"e": 471,
"s": 463,
"text": "Python3"
},
{
"code": null,
"e": 474,
"s": 471,
"text": "C#"
},
{
"code": null,
"e": 485,
"s": 474,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum// of the digits of num ^ 2int squareDigitSum(string number){ int summ = 0; int num = stoi(number); // Store the square of num int squareNum = num * num; // Find the sum of its digits while(squareNum > 0) { summ = summ + (squareNum % 10); squareNum = squareNum / 10; } return summ;} // Driver codeint main(){ string N = \"1111\"; cout << squareDigitSum(N); return 0;} // This code is contributed by Princi Singh",
"e": 1064,
"s": 485,
"text": null
},
{
"code": "// Java implementation of the approach// Java implementation of the approachclass GFG{ // Function to return the sum// of the digits of num ^ 2static int squareDigitSum(String number){ int summ = 0; int num = Integer.parseInt(number); // Store the square of num int squareNum = num * num; // Find the sum of its digits while(squareNum > 0) { summ = summ + (squareNum % 10); squareNum = squareNum / 10; } return summ;} // Driver codepublic static void main (String[] args){ String N = \"1111\"; System.out.println(squareDigitSum(N));}} // This code is contributed by Rajput-Ji",
"e": 1692,
"s": 1064,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the sum# of the digits of num ^ 2def squareDigitSum(num): summ = 0 num = int(num) # Store the square of num squareNum = num * num # Find the sum of its digits while squareNum > 0: summ = summ + (squareNum % 10) squareNum = squareNum//10 return summ # Driver codeif __name__ == \"__main__\": N = \"1111\" print(squareDigitSum(N))",
"e": 2133,
"s": 1692,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the sum // of the digits of num ^ 2 static int squareDigitSum(String number) { int summ = 0; int num = int.Parse(number); // Store the square of num int squareNum = num * num; // Find the sum of its digits while(squareNum > 0) { summ = summ + (squareNum % 10); squareNum = squareNum / 10; } return summ; } // Driver code public static void Main (String[] args) { String s = \"1111\"; Console.WriteLine(squareDigitSum(s)); }} // This code is contributed by Princi Singh",
"e": 2826,
"s": 2133,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the sum// of the digits of num ^ 2function squareDigitSum(number){ var summ = 0; var num = parseInt(number); // Store the square of num var squareNum = num * num; // Find the sum of its digits while (squareNum > 0) { summ = summ + (squareNum % 10); squareNum = parseInt(squareNum / 10); } return summ;} // Driver codevar N = \"1111\"; document.write(squareDigitSum(N)); // This code is contributed by todaysgaurav </script>",
"e": 3367,
"s": 2826,
"text": null
},
{
"code": null,
"e": 3370,
"s": 3367,
"text": "16"
},
{
"code": null,
"e": 4239,
"s": 3372,
"text": "Efficient approach: It can be observed that in the square of the given number, the sequence [1, 2, 3, 4, 5, 6, 7, 9, 0] repeats in the left part and the sequence [0, 9, 8, 7, 6, 5, 4, 3, 2, 1] repeats in the right part. Both of these sequences appear floor(length(str) / 9) times and the sum of both of these sequences is 81 and the square of the number adds an extra 1 in the end.So, the sum of all these would be [floor(length(str) / 9)] * 81 + 1.And the middle digits have a sequence such as if length(str) % 9 = a then middle sequence is [1, 2, 3....a, a – 1, a – 2, ... 2]. Now, it can be observed that sum of this part [1, 2, 3....a] is equal to (a * (a + 1)) / 2 and sum of the other part [a – 1, a – 2, ... 2] is ((a * (a – 1)) / 2) – 1. Total sum = floor(length(str) / 9) * 81 + 1 + (length(str) % 9)2 – 1 = floor(length(str) / 9) * 81 + (length(str) % 9)2."
},
{
"code": null,
"e": 4291,
"s": 4239,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4295,
"s": 4291,
"text": "C++"
},
{
"code": null,
"e": 4300,
"s": 4295,
"text": "Java"
},
{
"code": null,
"e": 4308,
"s": 4300,
"text": "Python3"
},
{
"code": null,
"e": 4311,
"s": 4308,
"text": "C#"
},
{
"code": null,
"e": 4322,
"s": 4311,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define lli long long int // Function to return the sum// of the digits of num^2lli squareDigitSum(string s){ // To store the number of 1's lli lengthN = s.length(); // Find the sum of the digits of num^2 lli result = (lengthN / 9) * 81 + pow((lengthN % 9), 2); return result;} // Driver codeint main(){ string s = \"1111\"; cout << squareDigitSum(s); return 0;}",
"e": 4809,
"s": 4322,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the sum // of the digits of num^2 static long squareDigitSum(String s) { // To store the number of 1's long lengthN = s.length(); // Find the sum of the digits of num^2 long result = (lengthN / 9) * 81 + (long)Math.pow((lengthN % 9), 2); return result; } // Driver code public static void main (String[] args) { String s = \"1111\"; System.out.println(squareDigitSum(s)); }} // This code is contributed by AnkitRai01",
"e": 5418,
"s": 4809,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the sum# of the digits of num ^ 2def squareDigitSum(num): # To store the number of 1's lengthN = len(num) # Find the sum of the digits of num ^ 2 result = (lengthN//9)*81 + (lengthN % 9)**2 return result # Driver codeif __name__ == \"__main__\" : N = \"1111\" print(squareDigitSum(N))",
"e": 5786,
"s": 5418,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the sum// of the digits of num^2static long squareDigitSum(String s){ // To store the number of 1's long lengthN = s.Length; // Find the sum of the digits of num^2 long result = (lengthN / 9) * 81 + (long)Math.Pow((lengthN % 9), 2); return result;} // Driver codepublic static void Main (String[] args){ String s = \"1111\"; Console.WriteLine(squareDigitSum(s));}} // This code is contributed by 29AjayKumar",
"e": 6340,
"s": 5786,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the sum// of the digits of num^2function squareDigitSum(s){ // To store the number of 1's let lengthN = s.length; // Find the sum of the digits of num^2 let result = parseInt(lengthN / 9) * 81 + Math.pow((lengthN % 9), 2); return result;} // Driver code let s = \"1111\"; document.write(squareDigitSum(s)); </script>",
"e": 6771,
"s": 6340,
"text": null
},
{
"code": null,
"e": 6774,
"s": 6771,
"text": "16"
},
{
"code": null,
"e": 6797,
"s": 6776,
"text": "Time Complexity O(1)"
},
{
"code": null,
"e": 6820,
"s": 6797,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 6828,
"s": 6820,
"text": "ankthon"
},
{
"code": null,
"e": 6840,
"s": 6828,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6850,
"s": 6840,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6863,
"s": 6850,
"text": "princi singh"
},
{
"code": null,
"e": 6876,
"s": 6863,
"text": "todaysgaurav"
},
{
"code": null,
"e": 6892,
"s": 6876,
"text": "rishavmahato348"
},
{
"code": null,
"e": 6908,
"s": 6892,
"text": "subhamkumarm348"
},
{
"code": null,
"e": 6922,
"s": 6908,
"text": "number-digits"
},
{
"code": null,
"e": 6935,
"s": 6922,
"text": "Mathematical"
},
{
"code": null,
"e": 6953,
"s": 6935,
"text": "Pattern Searching"
},
{
"code": null,
"e": 6966,
"s": 6953,
"text": "Mathematical"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Pattern Searching"
},
{
"code": null,
"e": 7082,
"s": 6984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7114,
"s": 7082,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7160,
"s": 7114,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 7204,
"s": 7160,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 7253,
"s": 7204,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 7295,
"s": 7253,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 7331,
"s": 7295,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 7374,
"s": 7331,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 7416,
"s": 7374,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 7473,
"s": 7416,
"text": "Check if an URL is valid or not using Regular Expression"
}
] |
Check if the string contains consecutive letters and each letter occurs exactly once | 30 Jun, 2022
Given string str. The task is to check if the string contains consecutive letters and each letter occurs exactly once.
Examples:
Input: str = “fced” Output: YesThe string contains ‘c’, ‘d’, ‘e’ and ‘f’ which are consecutive letters.
Input: str = “xyz” Output: Yes
Input: str = “abd” Output: No
Approach:The following steps can be followed to solve the problem:
Sort the given string in ascending order.
Check if s[i]-s[i-1]==1, for every index i from 1 to n-1.
If the condition holds for every index, print “Yes”, else print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if// the condition holdsbool check(string s){ // Get the length of the string int l = s.length(); // sort the given string sort(s.begin(), s.end()); // Iterate for every index and // check for the condition for (int i = 1; i < l; i++) { // If are not consecutive if (s[i] - s[i - 1] != 1) return false; } return true;} // Driver codeint main(){ // 1st example string str = "dcef"; if (check(str)) cout << "Yes\n"; else cout << "No\n"; // 2nd example str = "xyza"; if (check(str)) cout << "Yes\n"; else cout << "No\n"; return 0;}
// Java program to implement// the above approachimport java.util.*;class GfG { // Function to check if // the condition holds static boolean check(char s[]) { // Get the length of the string int l = s.length; // sort the given string Arrays.sort(s); // Iterate for every index and // check for the condition for (int i = 1; i < l; i++) { // If are not consecutive if (s[i] - s[i - 1] != 1) return false; } return true; } // Driver code public static void main(String[] args) { // 1st example String str = "dcef"; if (check(str.toCharArray()) == true) System.out.println("Yes"); else System.out.println("No"); // 2nd example String str1 = "xyza"; if (check(str1.toCharArray()) == true) System.out.println("Yes"); else System.out.println("No"); }}
# Python3 program to implement# the above approach # Function to check if# the condition holdsdef check(s): # Get the length of the string l = len(s) # sort the given string s = ''.join(sorted(s)) # Iterate for every index and # check for the condition for i in range(1, l): # If are not consecutive if ord(s[i]) - ord(s[i - 1]) != 1: return False return True # Driver codeif __name__ == "__main__": # 1st example string = "dcef" if check(string): print("Yes") else: print("No") # 2nd example string = "xyza" if check(string): print("Yes") else: print("No") # This code is contributed by Rituraj Jain
// C# program to implement// the above approachusing System;using System.Collections; class GfG { // Function to check if // the condition holds static bool check(char[] s) { // Get the length of the string int l = s.Length; // sort the given string Array.Sort(s); // Iterate for every index and // check for the condition for (int i = 1; i < l; i++) { // If are not consecutive if (s[i] - s[i - 1] != 1) return false; } return true; } // Driver code public static void Main() { // 1st example string str = "dcef"; if (check(str.ToCharArray()) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); // 2nd example String str1 = "xyza"; if (check(str1.ToCharArray()) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Ryuga
<script> // Javascript program to implement // the above approach // Function to check if // the condition holds function check(s) { // Get the length of the string let l = s.length; // sort the given string s.sort(); // Iterate for every index and // check for the condition for (let i = 1; i < l; i++) { // If are not consecutive if ((s[i].charCodeAt() - s[i - 1].charCodeAt()) != 1) return false; } return true; } // 1st example let str = "dcef"; if (check(str.split('')) == true) document.write("Yes" + "</br>"); else document.write("No" + "</br>"); // 2nd example let str1 = "xyza"; if (check(str1.split('')) == true) document.write("Yes"); else document.write("No"); // This code is contributed by mukesh07.</script>
Yes
No
Time complexity: O(N logN)
Auxiliary Space: O(1)
Efficient approach:
Find max and min ASCII values of the string’s characters
Find the sum of the ASCII values of all the characters from the string
So if a sequence of characters are a(ASCII = 96) to d(ASCII = 99) then, the result expected sum should be (sum from 0 to 99) minus (sum of 0 to 95)
Mathematical Equation:
MAX_VALUE*(MAX_VALUE+1)/2 - (MIN_VALUE-1)*((MIN_VALUE-1)+1)/2
Check whether the calculated sum and the expected sum is equal or not
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; bool check(string str){ int min = INT_MAX; int max = -INT_MAX; int sum = 0; // For all the characters of the string for(int i = 0; i < str.size(); i++) { // Find the ascii value of the character int ascii = str[i]; // Check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // Calculate sum of all the // characters ascii values sum += ascii; // Find minimum ascii value // from the string if (min > ascii) min = ascii; // Find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // Take the expected sum // from the above equation int eSum = ((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // Check if the expected sum is // equals to the calculated sum or not return sum == eSum;} // Driver codeint main(){ // 1st example string str = "dcef"; if (check(str)) cout << ("Yes"); else cout << ("No"); // 2nd example string str1 = "xyza"; if (check(str1)) cout << ("\nYes"); else cout << ("\nNo");} // This code is contributed by amreshkumar3
// Java program to implement// the above approachpublic class GFG { public static boolean check(String str) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int sum = 0; // for all the characters of the string for (int i = 0; i < str.length(); i++) { // find the ascii value of the character int ascii = (int)str.charAt(i); // check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // calculate sum of all the // characters ascii values sum += ascii; // find minimum ascii value // from the string if (min > ascii) min = ascii; // find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // take the expected sum // from the above equation int eSum = ((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // check if the expected sum is // equals to the calculated sum or not return sum == eSum; } // Driver code public static void main(String[] args) { // 1st example String str = "dcef"; if (check(str)) System.out.println("Yes"); else System.out.println("No"); // 2nd example String str1 = "xyza"; if (check(str1)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Arijit Basu(ArijitXfx)
# Python3 program to implement# the above approachimport sys def check(str): min = sys.maxsize max = -sys.maxsize - 1 sum = 0 # For all the characters of the string for i in range(len(str)): # Find the ascii value of the character ascii = str[i] # Check if its a valid character, # if not then return false if (ord(ascii) < 96 or ord(ascii) > 122): return False # Calculate sum of all the # characters ascii values sum += ord(ascii) # Find minimum ascii value # from the string if (min > ord(ascii)): min = ord(ascii) # Find maximum ascii value # from the string if (max < ord(ascii)): max = ord(ascii) # To get the previous element # of the minimum ASCII value min -= 1 # Take the expected sum # from the above equation eSum = (((max * (max + 1)) // 2) - ((min * (min + 1)) // 2)) # Check if the expected sum is # equals to the calculated sum or not return sum == eSum # Driver codeif __name__ == '__main__': # 1st example str = "dcef" if (check(str)): print("Yes") else: print("No") # 2nd example str1 = "xyza" if (check(str1)): print("Yes") else: print("No") # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;class GFG{ static bool check(string str) { int min = Int32.MaxValue; int max = Int32.MinValue; int sum = 0; // for all the characters of the string for (int i = 0; i < str.Length; i++) { // find the ascii value of the character int ascii = (int)str[i]; // check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // calculate sum of all the // characters ascii values sum += ascii; // find minimum ascii value // from the string if (min > ascii) min = ascii; // find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // take the expected sum // from the above equation int eSum = ((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // check if the expected sum is // equals to the calculated sum or not return sum == eSum; } // Driver code static void Main() { // 1st example string str = "dcef"; if (check(str)) Console.WriteLine("Yes"); else Console.WriteLine("No"); // 2nd example string str1 = "xyza"; if (check(str1)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by divyesh072019.
<script>// javascript program to implement// the above approach function check( str) { var min = Number.MAX_VALUE; var max = Number.MIN_VALUE; var sum = 0; // for all the characters of the string for (i = 0; i < str.length; i++) { // find the ascii value of the character var ascii = parseInt( str.charCodeAt(i)); // check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // calculate sum of all the // characters ascii values sum += ascii; // find minimum ascii value // from the string if (min > ascii) min = ascii; // find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // take the expected sum // from the above equation var eSum = parseInt((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // check if the expected sum is // equals to the calculated sum or not return sum == eSum; } // Driver code // 1st example var str = "dcef"; if (check(str)) document.write("Yes<br/>"); else document.write("No<br/>"); // 2nd example var str1 = "xyza"; if (check(str1)) document.write("Yes"); else document.write("No"); // This code contributed by Rajput-Ji</script>
Yes
No
Time Complexity: O(N) Auxiliary Space: O(1)
prerna saini
rituraj_jain
ankthon
Arijit Basu 1
amreshkumar3
khushboogoyal499
mohit kumar 29
divyesh072019
mukesh07
Rajput-Ji
rohitkumarsinghcna
surinderdawra388
school-programming
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexities of all Sorting Algorithms
Count Inversions in an array | Set 1 (Using Merge Sort)
Merge two sorted arrays
Sort an array of 0s, 1s and 2s | Dutch National Flag problem
Radix Sort
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 174,
"s": 54,
"text": "Given string str. The task is to check if the string contains consecutive letters and each letter occurs exactly once. "
},
{
"code": null,
"e": 186,
"s": 174,
"text": "Examples: "
},
{
"code": null,
"e": 291,
"s": 186,
"text": "Input: str = “fced” Output: YesThe string contains ‘c’, ‘d’, ‘e’ and ‘f’ which are consecutive letters. "
},
{
"code": null,
"e": 322,
"s": 291,
"text": "Input: str = “xyz” Output: Yes"
},
{
"code": null,
"e": 352,
"s": 322,
"text": "Input: str = “abd” Output: No"
},
{
"code": null,
"e": 421,
"s": 352,
"text": "Approach:The following steps can be followed to solve the problem: "
},
{
"code": null,
"e": 463,
"s": 421,
"text": "Sort the given string in ascending order."
},
{
"code": null,
"e": 521,
"s": 463,
"text": "Check if s[i]-s[i-1]==1, for every index i from 1 to n-1."
},
{
"code": null,
"e": 591,
"s": 521,
"text": "If the condition holds for every index, print “Yes”, else print “No”."
},
{
"code": null,
"e": 644,
"s": 591,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 648,
"s": 644,
"text": "C++"
},
{
"code": null,
"e": 653,
"s": 648,
"text": "Java"
},
{
"code": null,
"e": 661,
"s": 653,
"text": "Python3"
},
{
"code": null,
"e": 664,
"s": 661,
"text": "C#"
},
{
"code": null,
"e": 675,
"s": 664,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if// the condition holdsbool check(string s){ // Get the length of the string int l = s.length(); // sort the given string sort(s.begin(), s.end()); // Iterate for every index and // check for the condition for (int i = 1; i < l; i++) { // If are not consecutive if (s[i] - s[i - 1] != 1) return false; } return true;} // Driver codeint main(){ // 1st example string str = \"dcef\"; if (check(str)) cout << \"Yes\\n\"; else cout << \"No\\n\"; // 2nd example str = \"xyza\"; if (check(str)) cout << \"Yes\\n\"; else cout << \"No\\n\"; return 0;}",
"e": 1434,
"s": 675,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GfG { // Function to check if // the condition holds static boolean check(char s[]) { // Get the length of the string int l = s.length; // sort the given string Arrays.sort(s); // Iterate for every index and // check for the condition for (int i = 1; i < l; i++) { // If are not consecutive if (s[i] - s[i - 1] != 1) return false; } return true; } // Driver code public static void main(String[] args) { // 1st example String str = \"dcef\"; if (check(str.toCharArray()) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); // 2nd example String str1 = \"xyza\"; if (check(str1.toCharArray()) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 2418,
"s": 1434,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if# the condition holdsdef check(s): # Get the length of the string l = len(s) # sort the given string s = ''.join(sorted(s)) # Iterate for every index and # check for the condition for i in range(1, l): # If are not consecutive if ord(s[i]) - ord(s[i - 1]) != 1: return False return True # Driver codeif __name__ == \"__main__\": # 1st example string = \"dcef\" if check(string): print(\"Yes\") else: print(\"No\") # 2nd example string = \"xyza\" if check(string): print(\"Yes\") else: print(\"No\") # This code is contributed by Rituraj Jain",
"e": 3133,
"s": 2418,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections; class GfG { // Function to check if // the condition holds static bool check(char[] s) { // Get the length of the string int l = s.Length; // sort the given string Array.Sort(s); // Iterate for every index and // check for the condition for (int i = 1; i < l; i++) { // If are not consecutive if (s[i] - s[i - 1] != 1) return false; } return true; } // Driver code public static void Main() { // 1st example string str = \"dcef\"; if (check(str.ToCharArray()) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); // 2nd example String str1 = \"xyza\"; if (check(str1.ToCharArray()) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Ryuga",
"e": 4151,
"s": 3133,
"text": null
},
{
"code": "<script> // Javascript program to implement // the above approach // Function to check if // the condition holds function check(s) { // Get the length of the string let l = s.length; // sort the given string s.sort(); // Iterate for every index and // check for the condition for (let i = 1; i < l; i++) { // If are not consecutive if ((s[i].charCodeAt() - s[i - 1].charCodeAt()) != 1) return false; } return true; } // 1st example let str = \"dcef\"; if (check(str.split('')) == true) document.write(\"Yes\" + \"</br>\"); else document.write(\"No\" + \"</br>\"); // 2nd example let str1 = \"xyza\"; if (check(str1.split('')) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by mukesh07.</script>",
"e": 5073,
"s": 4151,
"text": null
},
{
"code": null,
"e": 5080,
"s": 5073,
"text": "Yes\nNo"
},
{
"code": null,
"e": 5109,
"s": 5082,
"text": "Time complexity: O(N logN)"
},
{
"code": null,
"e": 5131,
"s": 5109,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5152,
"s": 5131,
"text": "Efficient approach: "
},
{
"code": null,
"e": 5209,
"s": 5152,
"text": "Find max and min ASCII values of the string’s characters"
},
{
"code": null,
"e": 5280,
"s": 5209,
"text": "Find the sum of the ASCII values of all the characters from the string"
},
{
"code": null,
"e": 5428,
"s": 5280,
"text": "So if a sequence of characters are a(ASCII = 96) to d(ASCII = 99) then, the result expected sum should be (sum from 0 to 99) minus (sum of 0 to 95)"
},
{
"code": null,
"e": 5451,
"s": 5428,
"text": "Mathematical Equation:"
},
{
"code": null,
"e": 5514,
"s": 5451,
"text": " MAX_VALUE*(MAX_VALUE+1)/2 - (MIN_VALUE-1)*((MIN_VALUE-1)+1)/2"
},
{
"code": null,
"e": 5584,
"s": 5514,
"text": "Check whether the calculated sum and the expected sum is equal or not"
},
{
"code": null,
"e": 5636,
"s": 5584,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5640,
"s": 5636,
"text": "C++"
},
{
"code": null,
"e": 5645,
"s": 5640,
"text": "Java"
},
{
"code": null,
"e": 5653,
"s": 5645,
"text": "Python3"
},
{
"code": null,
"e": 5656,
"s": 5653,
"text": "C#"
},
{
"code": null,
"e": 5667,
"s": 5656,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; bool check(string str){ int min = INT_MAX; int max = -INT_MAX; int sum = 0; // For all the characters of the string for(int i = 0; i < str.size(); i++) { // Find the ascii value of the character int ascii = str[i]; // Check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // Calculate sum of all the // characters ascii values sum += ascii; // Find minimum ascii value // from the string if (min > ascii) min = ascii; // Find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // Take the expected sum // from the above equation int eSum = ((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // Check if the expected sum is // equals to the calculated sum or not return sum == eSum;} // Driver codeint main(){ // 1st example string str = \"dcef\"; if (check(str)) cout << (\"Yes\"); else cout << (\"No\"); // 2nd example string str1 = \"xyza\"; if (check(str1)) cout << (\"\\nYes\"); else cout << (\"\\nNo\");} // This code is contributed by amreshkumar3",
"e": 7121,
"s": 5667,
"text": null
},
{
"code": "// Java program to implement// the above approachpublic class GFG { public static boolean check(String str) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int sum = 0; // for all the characters of the string for (int i = 0; i < str.length(); i++) { // find the ascii value of the character int ascii = (int)str.charAt(i); // check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // calculate sum of all the // characters ascii values sum += ascii; // find minimum ascii value // from the string if (min > ascii) min = ascii; // find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // take the expected sum // from the above equation int eSum = ((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // check if the expected sum is // equals to the calculated sum or not return sum == eSum; } // Driver code public static void main(String[] args) { // 1st example String str = \"dcef\"; if (check(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); // 2nd example String str1 = \"xyza\"; if (check(str1)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Arijit Basu(ArijitXfx)",
"e": 8864,
"s": 7121,
"text": null
},
{
"code": "# Python3 program to implement# the above approachimport sys def check(str): min = sys.maxsize max = -sys.maxsize - 1 sum = 0 # For all the characters of the string for i in range(len(str)): # Find the ascii value of the character ascii = str[i] # Check if its a valid character, # if not then return false if (ord(ascii) < 96 or ord(ascii) > 122): return False # Calculate sum of all the # characters ascii values sum += ord(ascii) # Find minimum ascii value # from the string if (min > ord(ascii)): min = ord(ascii) # Find maximum ascii value # from the string if (max < ord(ascii)): max = ord(ascii) # To get the previous element # of the minimum ASCII value min -= 1 # Take the expected sum # from the above equation eSum = (((max * (max + 1)) // 2) - ((min * (min + 1)) // 2)) # Check if the expected sum is # equals to the calculated sum or not return sum == eSum # Driver codeif __name__ == '__main__': # 1st example str = \"dcef\" if (check(str)): print(\"Yes\") else: print(\"No\") # 2nd example str1 = \"xyza\" if (check(str1)): print(\"Yes\") else: print(\"No\") # This code is contributed by mohit kumar 29",
"e": 10245,
"s": 8864,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ static bool check(string str) { int min = Int32.MaxValue; int max = Int32.MinValue; int sum = 0; // for all the characters of the string for (int i = 0; i < str.Length; i++) { // find the ascii value of the character int ascii = (int)str[i]; // check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // calculate sum of all the // characters ascii values sum += ascii; // find minimum ascii value // from the string if (min > ascii) min = ascii; // find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // take the expected sum // from the above equation int eSum = ((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // check if the expected sum is // equals to the calculated sum or not return sum == eSum; } // Driver code static void Main() { // 1st example string str = \"dcef\"; if (check(str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); // 2nd example string str1 = \"xyza\"; if (check(str1)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by divyesh072019.",
"e": 11907,
"s": 10245,
"text": null
},
{
"code": "<script>// javascript program to implement// the above approach function check( str) { var min = Number.MAX_VALUE; var max = Number.MIN_VALUE; var sum = 0; // for all the characters of the string for (i = 0; i < str.length; i++) { // find the ascii value of the character var ascii = parseInt( str.charCodeAt(i)); // check if its a valid character, // if not then return false if (ascii < 96 || ascii > 122) return false; // calculate sum of all the // characters ascii values sum += ascii; // find minimum ascii value // from the string if (min > ascii) min = ascii; // find maximum ascii value // from the string if (max < ascii) max = ascii; } // To get the previous element // of the minimum ASCII value min -= 1; // take the expected sum // from the above equation var eSum = parseInt((max * (max + 1)) / 2) - ((min * (min + 1)) / 2); // check if the expected sum is // equals to the calculated sum or not return sum == eSum; } // Driver code // 1st example var str = \"dcef\"; if (check(str)) document.write(\"Yes<br/>\"); else document.write(\"No<br/>\"); // 2nd example var str1 = \"xyza\"; if (check(str1)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by Rajput-Ji</script>",
"e": 13546,
"s": 11907,
"text": null
},
{
"code": null,
"e": 13553,
"s": 13546,
"text": "Yes\nNo"
},
{
"code": null,
"e": 13600,
"s": 13555,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13613,
"s": 13600,
"text": "prerna saini"
},
{
"code": null,
"e": 13626,
"s": 13613,
"text": "rituraj_jain"
},
{
"code": null,
"e": 13634,
"s": 13626,
"text": "ankthon"
},
{
"code": null,
"e": 13648,
"s": 13634,
"text": "Arijit Basu 1"
},
{
"code": null,
"e": 13661,
"s": 13648,
"text": "amreshkumar3"
},
{
"code": null,
"e": 13678,
"s": 13661,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 13693,
"s": 13678,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 13707,
"s": 13693,
"text": "divyesh072019"
},
{
"code": null,
"e": 13716,
"s": 13707,
"text": "mukesh07"
},
{
"code": null,
"e": 13726,
"s": 13716,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13745,
"s": 13726,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 13762,
"s": 13745,
"text": "surinderdawra388"
},
{
"code": null,
"e": 13781,
"s": 13762,
"text": "school-programming"
},
{
"code": null,
"e": 13789,
"s": 13781,
"text": "Sorting"
},
{
"code": null,
"e": 13797,
"s": 13789,
"text": "Strings"
},
{
"code": null,
"e": 13805,
"s": 13797,
"text": "Strings"
},
{
"code": null,
"e": 13813,
"s": 13805,
"text": "Sorting"
},
{
"code": null,
"e": 13911,
"s": 13813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13955,
"s": 13911,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 14011,
"s": 13955,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 14035,
"s": 14011,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 14096,
"s": 14035,
"text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem"
},
{
"code": null,
"e": 14107,
"s": 14096,
"text": "Radix Sort"
},
{
"code": null,
"e": 14153,
"s": 14107,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 14178,
"s": 14153,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 14238,
"s": 14178,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 14253,
"s": 14238,
"text": "C++ Data Types"
}
] |
Python | Pandas dataframe.reindex() | 22 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.reindex() function conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False
Syntax: DataFrame.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
Parameters :labels : New labels/index to conform the axis specified by ‘axis’ to.index, columns : New labels / index to conform to. Preferably an Index object to avoid duplicating dataaxis : Axis to target. Can be either the axis name (‘index’, ‘columns’) or number (0, 1).method : {None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}, optionalcopy : Return a new object, even if the passed indexes are the samelevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.limit : Maximum number of consecutive elements to forward or backward filltolerance : Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation abs(index[indexer] – target) <= tolerance.
Returns : reindexed : DataFrame
Example #1: Use reindex() function to reindex the dataframe. By default values in the new index that do not have corresponding records in the dataframe are assigned NaN.Note : We can fill in the missing values by passing a value to the keyword fill_value.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["first", "second", "third", "fourth", "fifth"]) # Print the dataframedf
Let’s use the dataframe.reindex() function to reindex the dataframe
# reindexing with new index valuesdf.reindex(["first", "dues", "trois", "fourth", "fifth"])
Output :Notice the output, new indexes are populated with NaN values, we can fill in the missing values using the parameter, fill_value
# filling the missing values by 100df.reindex(["first", "dues", "trois", "fourth", "fifth"], fill_value = 100)
Output : Example #2: Use reindex() function to reindex the column axis
# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # reindexing the column axis with# old and new index valuesdf.reindex(columns =["A", "B", "D", "E"])
Output :Notice, we have NaN values in the new columns after reindexing, we can take care of the missing values at the time of reindexing. By passing an argument fill_value to the function.
# reindex the columns# fill the missing values by 25df.reindex(columns =["A", "B", "D", "E"], fill_value = 25)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 499,
"s": 242,
"text": "Pandas dataframe.reindex() function conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False"
},
{
"code": null,
"e": 655,
"s": 499,
"text": "Syntax: DataFrame.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)"
},
{
"code": null,
"e": 1663,
"s": 655,
"text": "Parameters :labels : New labels/index to conform the axis specified by ‘axis’ to.index, columns : New labels / index to conform to. Preferably an Index object to avoid duplicating dataaxis : Axis to target. Can be either the axis name (‘index’, ‘columns’) or number (0, 1).method : {None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}, optionalcopy : Return a new object, even if the passed indexes are the samelevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.limit : Maximum number of consecutive elements to forward or backward filltolerance : Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation abs(index[indexer] – target) <= tolerance."
},
{
"code": null,
"e": 1695,
"s": 1663,
"text": "Returns : reindexed : DataFrame"
},
{
"code": null,
"e": 1951,
"s": 1695,
"text": "Example #1: Use reindex() function to reindex the dataframe. By default values in the new index that do not have corresponding records in the dataframe are assigned NaN.Note : We can fill in the missing values by passing a value to the keyword fill_value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"first\", \"second\", \"third\", \"fourth\", \"fifth\"]) # Print the dataframedf",
"e": 2279,
"s": 1951,
"text": null
},
{
"code": null,
"e": 2347,
"s": 2279,
"text": "Let’s use the dataframe.reindex() function to reindex the dataframe"
},
{
"code": "# reindexing with new index valuesdf.reindex([\"first\", \"dues\", \"trois\", \"fourth\", \"fifth\"])",
"e": 2439,
"s": 2347,
"text": null
},
{
"code": null,
"e": 2575,
"s": 2439,
"text": "Output :Notice the output, new indexes are populated with NaN values, we can fill in the missing values using the parameter, fill_value"
},
{
"code": "# filling the missing values by 100df.reindex([\"first\", \"dues\", \"trois\", \"fourth\", \"fifth\"], fill_value = 100)",
"e": 2686,
"s": 2575,
"text": null
},
{
"code": null,
"e": 2757,
"s": 2686,
"text": "Output : Example #2: Use reindex() function to reindex the column axis"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # reindexing the column axis with# old and new index valuesdf.reindex(columns =[\"A\", \"B\", \"D\", \"E\"])",
"e": 3098,
"s": 2757,
"text": null
},
{
"code": null,
"e": 3287,
"s": 3098,
"text": "Output :Notice, we have NaN values in the new columns after reindexing, we can take care of the missing values at the time of reindexing. By passing an argument fill_value to the function."
},
{
"code": "# reindex the columns# fill the missing values by 25df.reindex(columns =[\"A\", \"B\", \"D\", \"E\"], fill_value = 25)",
"e": 3398,
"s": 3287,
"text": null
},
{
"code": null,
"e": 3407,
"s": 3398,
"text": "Output :"
},
{
"code": null,
"e": 3431,
"s": 3407,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3463,
"s": 3431,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 3477,
"s": 3463,
"text": "Python-pandas"
},
{
"code": null,
"e": 3484,
"s": 3477,
"text": "Python"
},
{
"code": null,
"e": 3582,
"s": 3484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3600,
"s": 3582,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3642,
"s": 3600,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3664,
"s": 3642,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3699,
"s": 3664,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3731,
"s": 3699,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3760,
"s": 3731,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3787,
"s": 3760,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3817,
"s": 3787,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3838,
"s": 3817,
"text": "Python OOPs Concepts"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.